<?php
declare(strict_types=1);

/**
 * modules/payroll/staff/list.php
 * Staff directory + monthly payroll KPIs + quick actions + this-month activity.
 * Visible to: MD, Accounts, Admin
 */

require_once dirname(__DIR__, 3) . '/config/functions.php';
require_role(['MD','Accounts','Admin']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$notice = null;

/* -----------------------------
   Helpers
------------------------------*/
function parse_bank(?string $raw): array {
  $out = [
    'bank_name'      => '',
    'account_name'   => '',
    'account_number' => '',
    'sort_code'      => '',
    'iban'           => '',
    'swift'          => '',
    'notes'          => '',
    'raw'            => '',
  ];
  if (!$raw) return $out;
  $s = trim((string)$raw);

  $j = json_decode($s, true);
  if (is_array($j)) {
    foreach (['bank_name','account_name','account_number','sort_code','iban','swift','notes'] as $k) {
      if (isset($j[$k]) && is_string($j[$k])) $out[$k] = trim((string)$j[$k]);
    }
    return $out;
  }

  foreach (preg_split('/\r\n|\r|\n/', $s) as $line) {
    $line = trim($line);
    if ($line === '') continue;
    if (preg_match('/^(bank\s*name)\s*[:\-]\s*(.+)$/i', $line, $m))              { $out['bank_name'] = trim($m[2]);   continue; }
    if (preg_match('/^(account\s*name|account\s*holder)\s*[:\-]\s*(.+)$/i',$line,$m)) { $out['account_name'] = trim($m[2]); continue; }
    if (preg_match('/^(account\s*number|acc(?:ount)?\.?|acc)\s*[:\-]\s*(.+)$/i',$line,$m)) { $out['account_number'] = trim($m[2]); continue; }
    if (preg_match('/^(sort\s*code|sort)\s*[:\-]\s*([0-9\-\s]+)$/i', $line, $m))   { $out['sort_code'] = trim($m[2]); continue; }
    if (preg_match('/^(iban)\s*[:\-]\s*(.+)$/i', $line, $m))                       { $out['iban'] = trim($m[2]);       continue; }
    if (preg_match('/^(swift|bic)\s*[:\-]\s*(.+)$/i', $line, $m))                  { $out['swift'] = trim($m[2]);      continue; }
    $out['raw'] .= ($out['raw'] ? "\n" : "") . $line;
  }
  return $out;
}

function next_pay_date_label(array $s): string {
  $cycle = strtolower((string)($s['pay_cycle'] ?? 'monthly'));
  $today = new DateTimeImmutable('today');

  if ($cycle === 'weekly') {
    $wd = (int)($s['salary_weekday'] ?? 5); // 0=Sun..6=Sat ; default Fri
    $delta = ($wd - (int)$today->format('w') + 7) % 7;
    if ($delta === 0) $delta = 7;
    return $today->modify("+{$delta} day")->format('D, j M Y');
  }

  $day = (int)($s['salary_day'] ?? 25);
  if ($day < 1) $day = 1;
  if ($day > 28) $day = 28; // safe
  $first     = $today->modify('first day of this month');
  $candidate = DateTimeImmutable::createFromFormat('Y-m-d', $first->format('Y-m-') . str_pad((string)$day, 2, '0', STR_PAD_LEFT));
  if ($candidate <= $today) {
    $firstNext = $today->modify('first day of next month');
    $candidate = DateTimeImmutable::createFromFormat('Y-m-d', $firstNext->format('Y-m-') . str_pad((string)$day, 2, '0', STR_PAD_LEFT));
  }
  return $candidate ? $candidate->format('D, j M Y') : '—';
}

/* -----------------------------
   Inline micro-endpoint: Bank popup
------------------------------*/
if (($_GET['fetch_bank'] ?? '') === '1' && isset($_GET['id'])) {
  header('Content-Type: text/html; charset=utf-8');
  try {
    $sid = (int)$_GET['id'];
    $q = db()->prepare("
      SELECT full_name, bank_details, department, job_title
        FROM staff_members
       WHERE id=:id AND company_id=:cid
       LIMIT 1
    ");
    $q->execute([':id'=>$sid, ':cid'=>$cid]);
    if ($st = $q->fetch()) {
      $b = parse_bank((string)($st['bank_details'] ?? ''));
      ?>
      <div class="mb-2">
        <div class="fw-semibold" style="font-size:1.05rem"><?= e($st['full_name'] ?? '') ?></div>
        <div class="text-muted small">
          <?= e($st['job_title'] ?? '—') ?> · <?= e($st['department'] ?? 'Chauffeur') ?>
        </div>
      </div>
      <table class="table table-sm align-middle mb-0">
        <tbody>
          <tr><th style="width:220px">Bank</th><td><?= e($b['bank_name'] ?: '—') ?></td></tr>
          <tr><th>Account Holder</th><td><?= e($b['account_name'] ?: '—') ?></td></tr>
          <tr><th>Account Number</th><td><?= e($b['account_number'] ?: '—') ?></td></tr>
          <tr><th>Sort Code</th><td><?= e($b['sort_code'] ?: '—') ?></td></tr>
          <tr><th>IBAN</th><td><?= e($b['iban'] ?: '—') ?></td></tr>
          <tr><th>SWIFT</th><td><?= e($b['swift'] ?: '—') ?></td></tr>
          <?php if (!empty($b['raw'])): ?>
          <tr><th>Additional</th><td><pre class="mb-0" style="white-space:pre-wrap"><?= e($b['raw']) ?></pre></td></tr>
          <?php endif; ?>
          <?php if (!empty($b['notes'])): ?>
          <tr><th>Notes</th><td><?= nl2br(e($b['notes'])) ?></td></tr>
          <?php endif; ?>
        </tbody>
      </table>
      <?php
    } else {
      echo '<div class="text-muted">Not found.</div>';
    }
  } catch (Throwable $e) {
    http_response_code(500);
    echo (defined('APP_ENV') && APP_ENV==='dev') ? e($e->getMessage()) : 'Error';
  }
  exit;
}

/* -----------------------------
   Filters
------------------------------*/
$today      = new DateTimeImmutable('today');
$monthStart = $today->modify('first day of this month')->format('Y-m-01');
$monthEnd   = $today->modify('last day of this month')->format('Y-m-d');

$show = (string)($_GET['show'] ?? 'active');            // active|inactive|all
$dept = (string)($_GET['department'] ?? '');            // ''|Rent|Chauffeur
$q    = trim((string)($_GET['q'] ?? ''));

if (!in_array($show, ['active','inactive','all'], true)) $show = 'active';
if ($dept !== '' && !in_array($dept, ['Rent','Chauffeur'], true)) $dept = '';

/* -----------------------------
   KPIs (this calendar month; paid_at date)
------------------------------*/
$activeCount = 0;
$advMonth    = 0.0;
$salMonth    = 0.0;

try {
  $stmt = db()->prepare("SELECT COUNT(*) FROM staff_members WHERE company_id=:cid AND is_active=1");
  $stmt->execute([':cid'=>$cid]);
  $activeCount = (int)$stmt->fetchColumn();
} catch (Throwable) {}

try {
  $stmt = db()->prepare("
    SELECT COALESCE(SUM(a.amount),0)
      FROM staff_advances a
     WHERE a.company_id=:cid
       AND DATE(a.paid_at) BETWEEN :f AND :t
  ");
  $stmt->execute([':cid'=>$cid, ':f'=>$monthStart, ':t'=>$monthEnd]);
  $advMonth = (float)$stmt->fetchColumn();
} catch (Throwable) {}

try {
  $stmt = db()->prepare("
    SELECT COALESCE(SUM(s.amount),0)
      FROM staff_salaries s
     WHERE s.company_id=:cid
       AND DATE(s.paid_at) BETWEEN :f AND :t
  ");
  $stmt->execute([':cid'=>$cid, ':f'=>$monthStart, ':t'=>$monthEnd]);
  $salMonth = (float)$stmt->fetchColumn();
} catch (Throwable) {}

/* -----------------------------
   Fetch staff rows
------------------------------*/
$rows = [];
try {
  $w = ["company_id = :cid"];
  $args = [':cid'=>$cid];

  if ($show === 'active')   { $w[] = "is_active = 1"; }
  if ($show === 'inactive') { $w[] = "is_active = 0"; }

  if ($dept !== '') {
    $w[] = "department = :dept";
    $args[':dept'] = $dept;
  }

  if ($q !== '') {
    $w[] = "(full_name LIKE :q OR email LIKE :q OR phone LIKE :q OR job_title LIKE :q)";
    $args[':q'] = '%'.$q.'%';
  }

  $sql = "
    SELECT id, full_name, email, phone, job_title, department,
           pay_cycle, salary_amount, salary_day, salary_weekday,
           start_date, end_date, is_active
      FROM staff_members
     WHERE ".implode(' AND ', $w)."
     ORDER BY full_name ASC
     LIMIT 500
  ";
  $stmt = db()->prepare($sql);
  $stmt->execute($args);
  $rows = $stmt->fetchAll();
} catch (Throwable $e) {
  $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load staff.';
}

/* -----------------------------
   This Month activity (detail lists)
------------------------------*/
$salRows = $advRows = [];
try {
  // Salaries paid this month
  $q1 = db()->prepare("
    SELECT s.id, s.staff_id, s.amount, s.paid_at, s.method, s.reference,
           st.full_name, st.job_title, st.department
      FROM staff_salaries s
      JOIN staff_members st ON st.id=s.staff_id AND st.company_id=s.company_id
     WHERE s.company_id=:cid
       AND DATE(s.paid_at) BETWEEN :f AND :t
     ORDER BY s.paid_at DESC, s.id DESC
     LIMIT 200
  ");
  $q1->execute([':cid'=>$cid, ':f'=>$monthStart, ':t'=>$monthEnd]);
  $salRows = $q1->fetchAll() ?: [];

  // Advances paid this month
  $q2 = db()->prepare("
    SELECT a.id, a.staff_id, a.amount, a.paid_at, a.method, a.reference,
           st.full_name, st.job_title, st.department
      FROM staff_advances a
      JOIN staff_members st ON st.id=a.staff_id AND st.company_id=a.company_id
     WHERE a.company_id=:cid
       AND DATE(a.paid_at) BETWEEN :f AND :t
     ORDER BY a.paid_at DESC, a.id DESC
     LIMIT 200
  ");
  $q2->execute([':cid'=>$cid, ':f'=>$monthStart, ':t'=>$monthEnd]);
  $advRows = $q2->fetchAll() ?: [];
} catch (Throwable $e) {
  $errors[] = (defined('APP_ENV') && APP_ENV==='dev') ? $e->getMessage() : 'Unable to load this month activity.';
}

/* -----------------------------
   Render
------------------------------*/
include dirname(__DIR__, 3) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Payroll — Staff</h1>
    <div class="text-muted">Manage staff profiles, advances, and salaries.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('dashboard/md.php')) ?>">← MD Dashboard</a>
    <a class="btn btn-dark" href="<?= e(url_modules('payroll/staff/edit.php')) ?>">+ Add Staff</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div>
<?php endif; ?>

<!-- KPI Cards -->
<div class="row g-3 mb-3">
  <div class="col-12 col-md-4">
    <div class="card shadow-sm h-100 border-primary">
      <div class="card-body">
        <div class="small text-muted">Active Staff</div>
        <div class="display-6"><?= number_format($activeCount) ?></div>
      </div>
    </div>
  </div>
  <div class="col-12 col-md-4">
    <div class="card shadow-sm h-100 border-warning">
      <div class="card-body">
        <div class="small text-muted">Advances (This Month)</div>
        <div class="display-6">£<?= number_format($advMonth, 2) ?></div>
      </div>
    </div>
  </div>
  <div class="col-12 col-md-4">
    <div class="card shadow-sm h-100 border-success">
      <div class="card-body">
        <div class="small text-muted">Salaries Paid (This Month)</div>
        <div class="display-6">£<?= number_format($salMonth, 2) ?></div>
      </div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <div class="col-sm-3 col-md-2">
        <label class="form-label">Show</label>
        <select class="form-select" name="show">
          <option value="active"   <?= $show==='active'  ?'selected':'' ?>>Active</option>
          <option value="inactive" <?= $show==='inactive'?'selected':'' ?>>Inactive</option>
          <option value="all"      <?= $show==='all'     ?'selected':'' ?>>All</option>
        </select>
      </div>

      <div class="col-sm-3 col-md-2">
        <label class="form-label">Department</label>
        <select class="form-select" name="department">
          <option value="" <?= $dept===''?'selected':'' ?>>— Any —</option>
          <option value="Chauffeur" <?= $dept==='Chauffeur'?'selected':'' ?>>Chauffeur</option>
          <option value="Rent" <?= $dept==='Rent'?'selected':'' ?>>Rent</option>
        </select>
      </div>

      <div class="col-sm-6 col-md-5">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Name / Email / Phone / Job Title" value="<?= e($q) ?>">
      </div>

      <div class="col-sm-12 col-md-3 d-grid">
        <button class="btn btn-primary">Filter</button>
      </div>
    </form>
  </div>
</div>

<!-- Staff Table -->
<div class="card shadow-sm mb-4">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Staff</th>
          <th>Job Title</th>
          <th>Department</th>
          <th>Pay Cycle</th>
          <th class="text-end">£ Salary / Cycle</th>
          <th>Next Pay Date</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php if ($rows): foreach ($rows as $s):
        $isActive = (int)$s['is_active'] === 1;
        $badge = $isActive ? 'success' : 'secondary';
        $next = next_pay_date_label($s);
        $cycle = (string)($s['pay_cycle'] ?? 'Monthly');
      ?>
        <tr>
          <td>
            <div class="fw-semibold"><?= e($s['full_name'] ?? '') ?></div>
            <div class="small text-muted"><?= e($s['email'] ?? '') ?><?php if(!empty($s['phone'])): ?> · <?= e($s['phone']) ?><?php endif; ?></div>
          </td>
          <td><?= e($s['job_title'] ?? '—') ?></td>
          <td><span class="badge text-bg-light"><?= e($s['department'] ?? 'Chauffeur') ?></span></td>
          <td><?= e(ucfirst(strtolower($cycle))) ?></td>
          <td class="text-end">£<?= number_format((float)($s['salary_amount'] ?? 0), 2) ?></td>
          <td><?= e($next) ?></td>
          <td><span class="badge text-bg-<?= e($badge) ?>"><?= $isActive?'Active':'Inactive' ?></span></td>
          <td class="text-end">
            <div class="btn-group btn-group-sm">
              <a class="btn btn-outline-primary"
                 href="<?= e(url_modules('payroll/staff/pay.php')) . '?staff_id=' . (int)$s['id'] . '&return=' . urlencode($_SERVER['REQUEST_URI'] ?? '') ?>">
                Pay Salary
              </a>
              <a class="btn btn-outline-warning"
                 href="<?= e(url_modules('payroll/staff/advance.php')) . '?staff_id=' . (int)$s['id'] . '&return=' . urlencode($_SERVER['REQUEST_URI'] ?? '') ?>">
                Advance
              </a>
              <a class="btn btn-outline-secondary"
                 href="<?= e(url_modules('payroll/staff/edit.php')) . '?id=' . (int)$s['id'] ?>">
                Edit
              </a>
              <button type="button" class="btn btn-outline-secondary js-bank" data-id="<?= (int)$s['id'] ?>">Bank</button>
            </div>
          </td>
        </tr>
      <?php endforeach; else: ?>
        <tr><td colspan="8" class="text-center text-muted py-4">No staff found.</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- This Month — Salaries -->
<div class="card shadow-sm mb-3">
  <div class="card-body">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h2 class="h6 mb-0">This Month — Salaries Paid (<?= e(date('M Y', strtotime($monthStart))) ?>)</h2>
      <div class="small text-muted">Total £<?= number_format($salMonth, 2) ?></div>
    </div>
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Paid At</th>
            <th>Staff</th>
            <th>Department</th>
            <th>Method</th>
            <th>Reference</th>
            <th class="text-end">£ Amount</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($salRows): foreach ($salRows as $r): ?>
            <tr>
              <td><?= e(date('Y-m-d H:i', strtotime($r['paid_at']))) ?></td>
              <td><div class="fw-semibold"><?= e($r['full_name']) ?></div><div class="small text-muted"><?= e($r['job_title'] ?? '—') ?></div></td>
              <td><?= e($r['department'] ?? '—') ?></td>
              <td><?= e($r['method'] ?? '—') ?></td>
              <td><?= e($r['reference'] ?? '—') ?></td>
              <td class="text-end">£<?= number_format((float)$r['amount'], 2) ?></td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="6" class="text-center text-muted py-4">No salaries paid this month.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- This Month — Advances -->
<div class="card shadow-sm">
  <div class="card-body">
    <div class="d-flex justify-content-between align-items-center mb-2">
      <h2 class="h6 mb-0">This Month — Advances Paid (<?= e(date('M Y', strtotime($monthStart))) ?>)</h2>
      <div class="small text-muted">Total £<?= number_format($advMonth, 2) ?></div>
    </div>
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead class="table-light">
          <tr>
            <th>Paid At</th>
            <th>Staff</th>
            <th>Department</th>
            <th>Method</th>
            <th>Reference</th>
            <th class="text-end">£ Amount</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($advRows): foreach ($advRows as $r): ?>
            <tr>
              <td><?= e(date('Y-m-d H:i', strtotime($r['paid_at']))) ?></td>
              <td><div class="fw-semibold"><?= e($r['full_name']) ?></div><div class="small text-muted"><?= e($r['job_title'] ?? '—') ?></div></td>
              <td><?= e($r['department'] ?? '—') ?></td>
              <td><?= e($r['method'] ?? '—') ?></td>
              <td><?= e($r['reference'] ?? '—') ?></td>
              <td class="text-end">£<?= number_format((float)$r['amount'], 2) ?></td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="6" class="text-center text-muted py-4">No advances paid this month.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include dirname(__DIR__, 3) . '/includes/footer.php'; ?>

<script>
(function(){
  const bankModal = new bootstrap.Modal(document.getElementById('bankModal'));
  const bankBody  = document.getElementById('bankBody');

  document.addEventListener('click', async function(e){
    const btn = e.target.closest('.js-bank'); if(!btn) return;
    bankBody.innerHTML = '<div class="text-muted">Loading…</div>';
    try{
      const res = await fetch('list.php?fetch_bank=1&id='+encodeURIComponent(btn.dataset.id), {headers:{'X-Requested-With':'XMLHttpRequest'}});
      if(!res.ok) throw new Error('HTTP '+res.status);
      bankBody.innerHTML = await res.text();
      bankModal.show();
    }catch(err){
      bankBody.innerHTML = '<div class="text-danger">Unable to load bank details.</div>';
      console.error(err);
      bankModal.show();
    }
  });
})();
</script>

<!-- Bank Modal -->
<div class="modal fade" id="bankModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Bank Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="bankBody">Loading…</div>
      </div>
    </div>
  </div>
</div>
