<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db   = Database::getInstance();
$page = 'Employee List';

// Filters
$search = get('search');
  // will cast below
$dept   = cleanInt($_GET['dept'] ?? 0);
$company= cleanInt($_GET['company'] ?? 0);
$status = get('status');
$loc    = cleanInt($_GET['loc'] ?? 0);
$pg     = max(1, cleanInt($_GET['page'] ?? 1));
$perPage = 15;

// FIX (07 Jul 2026): scope every employee query to the current user's
// organization (across all its companies) — otherwise one organization's
// admin could see another organization's employees here. This uses a
// fails-closed clause: if something's wrong and no companies resolve,
// it matches nothing rather than everything.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');

// Build query
$where  = [$orgClause];
$params = $orgParams;
if ($search) { $where[] = "(e.first_name LIKE ? OR e.last_name LIKE ? OR e.employee_id LIKE ?)"; $params = array_merge($params, ["%$search%","%$search%","%$search%"]); }
if ($dept)   { $where[] = 'e.department_id = ?'; $params[] = $dept; }
if ($company){ $where[] = 'e.company_id = ?'; $params[] = $company; }
if ($status) { $where[] = 'e.status = ?'; $params[] = $status; }
if ($loc)    { $where[] = 'e.location_id = ?'; $params[] = $loc; }

$whereStr = implode(' AND ', $where);
$total    = $db->fetchValue("SELECT COUNT(*) FROM employees e WHERE $whereStr", $params);
$pag      = paginate($total, $perPage, $pg);

$employees = $db->fetchAll(
    "SELECT e.id, e.employee_id, e.first_name, e.last_name, e.mobile,
            e.date_of_joining, e.status, e.photo,
            d.name AS dept, des.name AS designation,
            l.name AS location, es.gross_monthly, c.name AS company_name
       FROM employees e
  LEFT JOIN departments d ON d.id = e.department_id
  LEFT JOIN designations des ON des.id = e.designation_id
  LEFT JOIN locations l ON l.id = e.location_id
  LEFT JOIN employee_salary es ON es.employee_id = e.id
  LEFT JOIN companies c ON c.id = e.company_id
      WHERE $whereStr
      ORDER BY e.created_at DESC
      LIMIT {$pag['limit']} OFFSET {$pag['offset']}",
    $params
);

$departments = $db->fetchAll("SELECT id, name FROM departments WHERE is_active=1 ORDER BY name");
$locations   = $db->fetchAll("SELECT id, name FROM locations WHERE is_active=1 ORDER BY name");
// FIX: companies has no `is_active` column (that was never part of its
// schema), and this must only list companies inside the current org anyway.
$companies   = $db->fetchAll("SELECT id, name FROM companies WHERE organization_id=? ORDER BY name", [organizationId()]);

$headerActions = '<a href="' . BASE_URL . '/modules/employees/create.php" class="btn btn-pc btn-sm"><i class="ti ti-plus me-1"></i>Add Employee</a>
<a href="' . BASE_URL . '/modules/employees/import.php" class="btn btn-sm btn-outline-secondary"><i class="ti ti-upload me-1"></i>Import</a>
<a href="' . BASE_URL . '/modules/employees/export.php?'.http_build_query($_GET).'" class="btn btn-sm btn-outline-secondary"><i class="ti ti-download me-1"></i>Export</a>';
include __DIR__ . '/../../includes/header.php';
?>

<!-- Filters -->
<div class="pc-card mb-3">
  <form method="GET" class="pc-filters">
    <input type="text" name="search" class="form-control form-control-sm" placeholder="Search name / ID..." value="<?= clean($search) ?>" style="width:200px">
    <select name="company" class="form-select form-select-sm" style="width:150px">
      <option value="">All Companies</option>
      <?php foreach ($companies as $c): ?>
      <option value="<?= $c['id'] ?>" <?= $company==$c['id']?'selected':'' ?>><?= clean($c['name']) ?></option>
      <?php endforeach; ?>
    </select>
    <select name="dept" class="form-select form-select-sm" style="width:160px">
      <option value="">All Departments</option>
      <?php foreach ($departments as $d): ?>
      <option value="<?= $d['id'] ?>" <?= $dept==$d['id']?'selected':'' ?>><?= clean($d['name']) ?></option>
      <?php endforeach; ?>
    </select>
    <select name="loc" class="form-select form-select-sm" style="width:140px">
      <option value="">All Locations</option>
      <?php foreach ($locations as $l): ?>
      <option value="<?= $l['id'] ?>" <?= $loc==$l['id']?'selected':'' ?>><?= clean($l['name']) ?></option>
      <?php endforeach; ?>
    </select>
    <select name="status" class="form-select form-select-sm" style="width:130px">
      <option value="">All Status</option>
      <?php foreach (['active','inactive','probation','on_leave','resigned','terminated'] as $s): ?>
      <option value="<?= $s ?>" <?= $status===$s?'selected':'' ?>><?= ucfirst(str_replace('_',' ',$s)) ?></option>
      <?php endforeach; ?>
    </select>
    <button type="submit" class="btn btn-pc btn-sm"><i class="ti ti-search me-1"></i>Search</button>
    <a href="?" class="btn btn-sm btn-outline-secondary">Reset</a>
  </form>
</div>

<!-- Table -->
<div class="pc-card">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div class="small text-muted">Showing <?= count($employees) ?> of <?= $total ?> employees</div>
    <?= paginationHtml($pag, '?' . http_build_query(array_diff_key($_GET, ['page'=>'']))) ?>
  </div>
  <div class="pc-table-wrap">
    <table class="pc-table">
      <thead>
        <tr>
          <th>#</th>
          <th>Employee</th>
          <th>Company</th>
          <th>Designation</th>
          <th>Department</th>
          <th>Location</th>
          <th>DOJ</th>
          <th>Gross Salary</th>
          <th>Status</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($employees as $i => $e): ?>
      <tr>
        <td class="text-muted"><?= $pag['offset'] + $i + 1 ?></td>
        <td>
          <div class="d-flex align-items-center gap-2">
            <div class="pc-stat-icon brand" style="width:30px;height:30px;font-size:11px;border-radius:50%">
              <?= strtoupper(substr($e['first_name'],0,1).substr($e['last_name'],0,1)) ?>
            </div>
            <div>
              <div class="fw-semibold"><?= clean($e['first_name'].' '.$e['last_name']) ?></div>
              <div style="font-size:10px;color:var(--pc-text2)"><?= clean($e['employee_id']) ?></div>
            </div>
          </div>
        </td>
        <td><span class="badge" style="background:var(--pc-brand-light);color:var(--pc-brand);font-size:10px"><?= clean($e['company_name'] ?? '—') ?></span></td>
        <td><?= clean($e['designation'] ?? '—') ?></td>
        <td><?= clean($e['dept'] ?? '—') ?></td>
        <td><?= clean($e['location'] ?? '—') ?></td>
        <td><?= fmtDate($e['date_of_joining']) ?></td>
        <td><?= $e['gross_monthly'] ? money($e['gross_monthly']) : '—' ?></td>
        <td><?= statusBadge($e['status']) ?></td>
        <td>
          <div class="d-flex gap-1">
            <a href="view.php?id=<?= $e['id'] ?>" class="btn btn-sm btn-outline-secondary" title="View"><i class="ti ti-eye"></i></a>
            <a href="edit.php?id=<?= $e['id'] ?>" class="btn btn-sm btn-outline-primary" title="Edit"><i class="ti ti-edit"></i></a>
            <a href="payslip.php?id=<?= $e['id'] ?>" class="btn btn-sm btn-outline-success" title="Payslip"><i class="ti ti-receipt"></i></a>
            <button class="btn btn-sm btn-outline-danger" onclick="confirmDelete(<?= $e['id'] ?>, '<?= clean($e['first_name'].' '.$e['last_name']) ?>')" title="Delete"><i class="ti ti-trash"></i></button>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if (!$employees): ?>
      <tr><td colspan="9" class="text-center text-muted py-4"><i class="ti ti-users-off d-block fs-1 mb-2"></i>No employees found</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
  <div class="mt-3 d-flex justify-content-end">
    <?= paginationHtml($pag, '?' . http_build_query(array_diff_key($_GET, ['page'=>'']))) ?>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Confirm Delete</h6></div>
      <div class="modal-body small" id="deleteMsg">Are you sure?</div>
      <div class="modal-footer">
        <button class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <a href="#" id="deleteBtn" class="btn btn-sm btn-danger">Delete</a>
      </div>
    </div>
  </div>
</div>

<?php $extraJs = "<script>
function confirmDelete(id, name) {
  document.getElementById('deleteMsg').textContent = 'Delete employee: ' + name + '?';
  document.getElementById('deleteBtn').href = 'delete.php?id='+id+'&csrf='+CSRF_TOKEN;
  new bootstrap.Modal(document.getElementById('deleteModal')).show();
}
</script>"; ?>
<?php include __DIR__ . '/../../includes/footer.php'; ?>