<?php
session_start();
require_once 'db.php';

// ========= Auth =========
if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; }
$role  = $_SESSION['user']['role']; // admin|exco|ajk|lain2 (normal user)
$name  = $_SESSION['user']['name'] ?? ($_SESSION['user']['full_name'] ?? '');
$userId= (int)($_SESSION['user']['id'] ?? 0);

$isAdmin = ($role === 'admin');
$isExco  = ($role === 'exco');
$isAjk   = ($role === 'ajk'); // legacy, kini dianggap EXCO (Penyokong)
$canModerate = ($isAdmin || $isExco || $isAjk); // moderator lihat KPI & pending

// ========= CSRF (untuk tindakan pada dashboard) =========
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf_token'];

// ========= Helpers =========
function get_user_district_ids(mysqli $conn, int $memberId, string $role): array {
  $ids = [];
  $sql = "SELECT district_id FROM district_role_assignment WHERE member_id=? AND role=? AND is_active=1";
  if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param('is', $memberId, $role);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($r = $res->fetch_assoc()) $ids[] = (int)$r['district_id'];
    $stmt->close();
  }
  return array_values(array_unique($ids));
}

// ========= Dashboard Statistics (untuk moderator sahaja) =========
$statPendingExco = 0;
$statPendingSupport = 0; // EXCO (Penyokong)
$excoDids = [];

if ($canModerate) {
  if ($isAdmin) {
    // Admin lihat semua
    if ($r = $conn->query("SELECT COUNT(*) AS c FROM pending_exco WHERE (exco_approval IS NULL OR exco_approval = 0)")) {
      $statPendingExco = (int)$r->fetch_assoc()['c'];
    }
    if ($r = $conn->query("SELECT COUNT(*) AS c FROM pending_ajk WHERE (ajk_approval IS NULL OR ajk_approval = 0)")) {
      $statPendingSupport = (int)$r->fetch_assoc()['c'];
    }
  } else {
    // EXCO — KPI EXCO ikut district lantikan
    if ($isExco) {
      $excoDids = get_user_district_ids($conn, $userId, 'exco');
      if ($excoDids) {
        $in  = implode(',', array_fill(0, count($excoDids), '?'));
        $sql = "SELECT COUNT(*) AS c
                FROM pending_exco
                WHERE (exco_approval IS NULL OR exco_approval = 0)
                  AND district_id IN ($in)";
        if ($stmt = $conn->prepare($sql)) {
          $types = str_repeat('i', count($excoDids));
          $stmt->bind_param($types, ...$excoDids);
          $stmt->execute();
          $stmt->bind_result($c); $stmt->fetch(); $statPendingExco = (int)$c;
          $stmt->close();
        }
      }
      // KPI EXCO (Penyokong) = rekod assigned kepada EXCO ini
      if ($stmt = $conn->prepare("SELECT COUNT(*) AS c
                                  FROM pending_ajk
                                  WHERE (ajk_approval IS NULL OR ajk_approval = 0)
                                    AND assigned_ajk_id=?")) {
        $stmt->bind_param('i', $userId);
        $stmt->execute(); $stmt->bind_result($c); $stmt->fetch();
        $statPendingSupport = (int)$c; $stmt->close();
      }
    }

    // AJK (legacy) — hanya KPI EXCO (Penyokong) = rekod assigned kepadanya
    if ($isAjk) {
      if ($stmt = $conn->prepare("SELECT COUNT(*) AS c
                                  FROM pending_ajk
                                  WHERE (ajk_approval IS NULL OR ajk_approval = 0)
                                    AND assigned_ajk_id=?")) {
        $stmt->bind_param('i', $userId);
        $stmt->execute(); $stmt->bind_result($c); $stmt->fetch();
        $statPendingSupport = (int)$c; $stmt->close();
      }
    }
  }
}

// ========= (Admin) Password Reset Requests =========
$pwdReq = false; $statPwdReq = 0;
if ($isAdmin) {
  $stmt = $conn->prepare("
    SELECT r.id, r.member_id, r.staff_number, r.email, r.ic_last4, r.phone, r.requested_at,
           m.full_name
    FROM password_reset_requests r
    LEFT JOIN members m ON m.id = r.member_id
    WHERE r.status='pending'
    ORDER BY r.requested_at DESC
  ");
  $stmt->execute();
  $pwdReq = $stmt->get_result();
  $statPwdReq = $pwdReq ? $pwdReq->num_rows : 0;
  $stmt->close();
}

// ========= Data: Pending users by role (untuk moderator sahaja) =========
$pendingUsers = false;
if ($isAdmin) {
  // Admin: hanya yang pending
  $sql = "
    SELECT p.id, p.full_name, p.staff_number, p.email, p.phone, p.created_at, 'EXCO' AS stage, d.name AS district
    FROM pending_exco p
    LEFT JOIN districts d ON d.id = p.district_id
    WHERE (p.exco_approval IS NULL OR p.exco_approval = 0)
    UNION ALL
    SELECT a.id, a.full_name, a.staff_number, a.email, a.phone, a.created_at, 'EXCO (Penyokong)'  AS stage, d.name AS district
    FROM pending_ajk a
    LEFT JOIN districts d ON d.id = a.district_id
    WHERE (a.ajk_approval IS NULL OR a.ajk_approval = 0)
    ORDER BY created_at DESC
  ";
  $pendingUsers = $conn->query($sql);

} elseif ($isExco) {
  // Gabungan: EXCO (ikut district lantikan & pending) + EXCO (Penyokong) pending & assigned kepada EXCO ini
  $parts = [];
  $bindTypes = '';
  $bindVals  = [];

  $excoDids = $excoDids ?: get_user_district_ids($conn, $userId, 'exco');
  if (!empty($excoDids)) {
    $in = implode(',', array_fill(0, count($excoDids), '?'));
    $parts[] = "
      SELECT p.id, p.full_name, p.staff_number, p.email, p.phone, p.created_at, 'EXCO' AS stage, p.district_id
      FROM pending_exco p
      WHERE (p.exco_approval IS NULL OR p.exco_approval = 0)
        AND p.district_id IN ($in)
    ";
    $bindTypes .= str_repeat('i', count($excoDids));
    foreach ($excoDids as $did) $bindVals[] = $did;
  }

  // EXCO (Penyokong): pending & assigned kepada user ini
  $parts[]   = "
    SELECT a.id, a.full_name, a.staff_number, a.email, a.phone, a.created_at, 'EXCO (Penyokong)' AS stage, a.district_id
    FROM pending_ajk a
    WHERE (a.ajk_approval IS NULL OR a.ajk_approval = 0)
      AND a.assigned_ajk_id = ?
  ";
  $bindTypes .= 'i';
  $bindVals[] = $userId;

  if ($parts) {
    $sql = "
      SELECT u.id, u.full_name, u.staff_number, u.email, u.phone, u.created_at, u.stage, d.name AS district
      FROM (
        ".implode("\nUNION ALL\n", $parts)."
      ) AS u
      LEFT JOIN districts d ON d.id = u.district_id
      ORDER BY u.created_at DESC
    ";
    if ($stmt = $conn->prepare($sql)) {
      if ($bindTypes !== '') $stmt->bind_param($bindTypes, ...$bindVals);
      $stmt->execute();
      $pendingUsers = $stmt->get_result();
      $stmt->close();
    }
  }

} elseif ($isAjk) {
  // AJK (legacy) → EXCO (Penyokong) pending & assigned kepada user ini
  $sql = "
    SELECT a.id, a.full_name, a.staff_number, a.email, a.phone, a.created_at, 'EXCO (Penyokong)' AS stage, d.name AS district
    FROM pending_ajk a
    LEFT JOIN districts d ON d.id = a.district_id
    WHERE (a.ajk_approval IS NULL OR a.ajk_approval = 0)
      AND a.assigned_ajk_id = ?
    ORDER BY a.created_at DESC
  ";
  if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $pendingUsers = $stmt->get_result();
    $stmt->close();
  }
}

// ========= Master: Rejection Reasons (aktif) -> hanya bila moderator =========
$reasons = [];
if ($canModerate) {
  $qr = $conn->query("SELECT id, reason FROM rejection_reasons WHERE active=1 ORDER BY reason ASC");
  if ($qr) while ($r = $qr->fetch_assoc()) $reasons[] = $r;
}

/* ========= Announcements (active only) + pagination ========= */
$annPageSize = 5;
$annPage = max(1, (int)($_GET['ann_page'] ?? 1));
$annOffset = ($annPage - 1) * $annPageSize;

// Kira jumlah aktif
$annTotal = 0;
if ($rs = $conn->query("SELECT COUNT(*) AS c FROM announcements WHERE is_active=1")) {
  $annTotal = (int)$rs->fetch_assoc()['c'];
}
$annPages = (int)ceil($annTotal / $annPageSize);
if ($annPages < 1) $annPages = 1;
if ($annPage > $annPages) $annPage = $annPages;

// Dapatkan senarai (latest first)
$annRows = [];
if ($st = $conn->prepare("
  SELECT id, title, body, media_path, media_type, created_name, created_at
  FROM announcements
  WHERE is_active=1
  ORDER BY created_at DESC, id DESC
  LIMIT ? OFFSET ?
")) {
  $st->bind_param("ii", $annPageSize, $annOffset);
  $st->execute();
  $res = $st->get_result();
  while($row = $res->fetch_assoc()) $annRows[] = $row;
  $st->close();
}

/* ======================================================================
   MODE CETAK (admin sahaja): ?print=pending
   ====================================================================== */
if (isset($_GET['print']) && $_GET['print'] === 'pending' && $isAdmin) {

    // Helper: safely read column
    $col = function(array $row, string $key, $fallback='-') {
        if (!array_key_exists($key, $row)) return $fallback;
        $v = (string)$row[$key];
        return $v !== '' ? htmlspecialchars($v) : $fallback;
    };

    // Ambil dua set & gabung
    $rows = [];
    $totalExco = 0; $totalSup = 0;

    $q1 = $conn->query("SELECT p.*, d.name AS district
                        FROM pending_exco p
                        LEFT JOIN districts d ON d.id=p.district_id
                        WHERE (p.exco_approval IS NULL OR p.exco_approval = 0)
                        ORDER BY p.created_at ASC");
    if ($q1) while ($x = $q1->fetch_assoc()) { $x['stage'] = 'EXCO'; $rows[] = $x; $totalExco++; }

    $q2 = $conn->query("SELECT a.*, d.name AS district
                        FROM pending_ajk a
                        LEFT JOIN districts d ON d.id=a.district_id
                        WHERE (a.ajk_approval IS NULL OR a.ajk_approval = 0)
                        ORDER BY a.created_at ASC");
    if ($q2) while ($x = $q2->fetch_assoc()) { $x['stage'] = 'EXCO (Penyokong)';  $rows[] = $x; $totalSup++;  }

    // Susun: EXCO dahulu, kemudian EXCO (Penyokong); dalam stage ikut created_at ASC
    usort($rows, function($a,$b){
        $wa = ($a['stage']==='EXCO') ? 0 : 1;
        $wb = ($b['stage']==='EXCO') ? 0 : 1;
        if ($wa !== $wb) return $wa - $wb;
        $ta = strtotime($a['created_at'] ?? '1970-01-01 00:00:00');
        $tb = strtotime($b['created_at'] ?? '1970-01-01 00:00:00');
        return $ta <=> $tb;
    });

    $totalAll = $totalExco + $totalSup;

    ?><!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="utf-8">
<title>Cetakan — Senarai Permohonan Baharu</title>
<style>
  :root{--ink:#111827;--muted:#6b7280;--line:#e5e7eb}
  *{box-sizing:border-box}
  body{font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Helvetica Neue',Arial,'Noto Sans','Apple Color Emoji','Segoe UI Emoji'; color:var(--ink); margin:24px}
  h1{font-size:20px;margin:0 0 6px 0}
  h2{font-size:16px;margin:18px 0 8px 0}
  .meta{font-size:12px;color:var(--muted);margin-bottom:14px}
  .summary{display:flex;gap:16px;flex-wrap:wrap;margin:10px 0 18px 0}
  .pill{border:1px solid var(--line);padding:8px 10px;border-radius:10px;font-size:13px;background:#fafafa}
  table{width:100%;border-collapse:collapse}
  th,td{border:1px solid var(--line);padding:8px 10px;font-size:13px;vertical-align:top}
  th{background:#f9fafb;text-transform:uppercase;letter-spacing:.02em;font-size:12px}
  .stage-exco{background:#eef2ff}
  .stage-sup{background:#fff7ed}
  .muted{color:#6b7280}
  .note{font-size:12px;color:#374151;margin-top:8px}
  .noprint{margin:0 0 14px 0}
  .btn{display:inline-block;border:1px solid var(--line);padding:7px 10px;border-radius:8px;text-decoration:none;color:#111;background:#fff}
  .details{background:#fcfcfc;border:1px dashed var(--line);padding:10px;border-radius:8px;margin-top:8px}
  .grid{display:grid;grid-template-columns:200px 1fr;gap:6px 12px}
  .label{color:#374151}
  .value{color:#111}
  .spacer{height:10px}
  @media print{
    .noprint{display:none!important}
    body{margin:0.7cm}
    a[href]:after{content:""}
  }
</style>
</head>
<body>
  <div class="noprint">
    <a class="btn" href="dashboard.php">← Kembali</a>
    <a class="btn" href="#" onclick="window.print();return false;">🖨️ Cetak</a>
  </div>

  <h1>Senarai Permohonan Baharu Untuk Kelulusan Mesyuarat</h1>
  <div class="meta">
    Dicetak oleh: <strong><?= htmlspecialchars($name) ?></strong> (ADMIN) —
    Tarikh: <?= date('d M Y, H:i') ?>
  </div>
  <div class="summary">
    <div class="pill">Jumlah Keseluruhan: <strong><?= (int)$totalAll ?></strong></div>
    <div class="pill">Menunggu EXCO: <strong><?= (int)$totalExco ?></strong></div>
    <div class="pill">Menunggu EXCO (Penyokong): <strong><?= (int)$totalSup ?></strong></div>
  </div>
  <div class="note">Nota: Senarai ini menggabungkan semua permohonan baharu yang berada pada peringkat EXCO dan EXCO (Penyokong) untuk tujuan kelulusan mesyuarat.</div>

  <h2>Butiran Permohonan</h2>
  <table>
    <thead>
      <tr>
        <th style="width:48px">#</th>
        <th>Nama Penuh</th>
        <th>No. Staf</th>
        <th>Emel</th>
        <th>Telefon</th>
        <th>District</th>
        <th>Stage</th>
        <th style="width:140px">Tarikh Permohonan</th>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="8" class="muted" style="text-align:center">Tiada permohonan baharu.</td></tr>
      <?php else: $i=1; foreach($rows as $r): ?>
        <?php
          $isExcoRow = ($r['stage']==='EXCO');
          $created = isset($r['created_at']) ? date('d M Y H:i', strtotime($r['created_at'])) : '-';
          $ic           = $col($r,'ic_number');
          $jobTitle     = $col($r,'job_title');
          $race         = $col($r,'race');
          $location     = $col($r,'location');
          $districtName = $col($r,'district');
          $excoAuto     = $col($r,'exco_auto','-');
          $supportSel   = $col($r,'exco_select','-');
          $homePhone    = $col($r,'home_phone');
          $address      = $col($r,'address');
          $postcode     = $col($r,'postcode');
          $warisName    = $col($r,'waris_name');
          $warisPhone   = $col($r,'waris_phone');
        ?>
        <tr class="<?= $isExcoRow ? 'stage-exco' : 'stage-sup' ?>">
          <td><?= $i ?></td>
          <td><strong><?= htmlspecialchars($r['full_name'] ?? '-') ?></strong></td>
          <td><?= htmlspecialchars($r['staff_number'] ?? '-') ?></td>
          <td><?= htmlspecialchars($r['email'] ?? '-') ?></td>
          <td><?= htmlspecialchars(($r['phone'] ?? '') !== '' ? $r['phone'] : '-') ?></td>
          <td><?= $districtName ?></td>
          <td><?= $isExcoRow ? 'EXCO' : 'EXCO (Penyokong)' ?></td>
          <td><?= $created ?></td>
        </tr>
        <tr>
          <td colspan="8">
            <div class="details">
              <div class="grid">
                <div class="label">IC</div><div class="value"><?= $ic ?></div>
                <div class="label">Jawatan</div><div class="value"><?= $jobTitle ?></div>
                <div class="label">Kaum</div><div class="value"><?= $race ?></div>
                <div class="label">Lokasi Bertugas</div><div class="value"><?= $location ?></div>
                <?php if ($isExcoRow): ?>
                  <div class="label">EXCO (Auto)</div><div class="value"><?= $excoAuto ?></div>
                <?php else: ?>
                  <div class="label">EXCO (Penyokong) Dipilih</div><div class="value"><?= $supportSel ?></div>
                <?php endif; ?>
                <div class="label">Alamat</div><div class="value"><?= $address ?></div>
                <div class="label">Poskod</div><div class="value"><?= $postcode ?></div>
                <div class="label">Telefon Rumah</div><div class="value"><?= $homePhone ?></div>
                <div class="label">Waris</div><div class="value"><?= $warisName ?></div>
                <div class="label">Telefon Waris</div><div class="value"><?= $warisPhone ?></div>
              </div>
            </div>
          </td>
        </tr>
        <tr><td colspan="8" class="spacer"></td></tr>
        <?php $i++; endforeach; endif; ?>
    </tbody>
  </table>

  <script>
    setTimeout(function(){ window.print(); }, 200);
  </script>
</body>
</html>
<?php
    exit;
}

// ====================== PAPARAN DASHBOARD BIASA ======================
ob_start();
?>
<style>
/* ------- self-contained styles (no bootstrap needed) ------- */
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
.card-header{padding:14px 16px;border-bottom:1px solid #f0f0f0;font-weight:600;display:flex;align-items:center;justify-content:space-between;gap:8px}
.card-body{padding:12px 16px}
.row{display:flex;gap:16px;flex-wrap:wrap}
.col{flex:1 1 280px}
.kpi{display:flex;align-items:center;justify-content:space-between;padding:16px;border-radius:10px;background:#f9fafb}
.kpi .num{font-size:28px;font-weight:800}
.kpi .lbl{color:#6b7280}
.badge{display:inline-block;padding:3px 8px;border-radius:9999px;font-size:12px;font-weight:600;vertical-align:middle}
.badge-exco{background:#e8efff;color:#1d4ed8;border:1px solid #c7d2fe}
.badge-support{background:#fff2d8;color:#92400e;border:1px solid #fde68a}
.badge-reset{background:#eefdf3;color:#047857;border:1px solid #bbf7d0}
.badge-district{background:#eefdf3;color:#065f46;border:1px solid #a7f3d0}
.table{width:100%;border-collapse:separate;border-spacing:0}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #f0f0f0}
.table thead th{position:sticky;top:0;background:#f8fafc;font-size:13px;text-transform:uppercase;letter-spacing:.02em;color:#4b5563}
.table tbody tr:hover{background:#fafafa}
.small{font-size:12px;color:#6b7280}
.actions{display:flex;gap:6px;justify-content:flex-end;align-items:center;flex-wrap:wrap}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:6px 10px;font-size:13px;cursor:pointer;text-decoration:none;display:inline-block}
.btn:disabled{opacity:.6;cursor:not-allowed}
.btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
.btn-success{background:#16a34a;color:#fff;border-color:#16a34a}
.btn-danger{background:#dc2626;color:#fff;border-color:#dc2626}
.btn-light{background:#f3f4f6}
.select{padding:6px 8px;border:1px solid #d1d5db;border-radius:8px;min-width:220px}
.notice{background:#fffbeb;border:1px solid #fde68a;color:#92400e;padding:10px 12px;border-radius:10px}
.m-0{margin:0}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.mt-4{margin-top:16px}.mb-0{margin-bottom:0}
.text-end{text-align:right}
.w-100{width:100%}
.reject-panel{display:none;margin-top:8px;padding:10px;border:1px dashed #e5e7eb;border-radius:8px;background:#fff}
.reject-panel.show{display:block}
.stage-cell{white-space:nowrap}
.header-actions{display:flex;gap:8px;align-items:center}

/* ------- Announcement thread styles ------- */
.thread-item{border:1px solid #eef2f7;border-radius:12px;padding:12px 14px;background:#fff}
.thread-head{display:flex;align-items:center;justify-content:space-between;gap:8px}

/* ✅ TITLE BESARKAN DI SINI */
.thread-title{
  font-weight:800;
  margin:0;
  font-size:18px;      /* <-- BESARKAN */
  line-height:1.25;
}

.thread-meta{font-size:12px;color:#6b7280}
.thread-body{margin-top:6px;white-space:pre-wrap;word-wrap:break-word}

/* ANNOUNCEMENT MEDIA — WIDTH FIXED, HEIGHT AUTO */
.thread-media-wrap{
  margin-top:10px;
  width:100%;
  border-radius:8px;
  overflow:hidden;
  background:transparent;
}

/* IMAGE */
.thread-media{
  display:block;
  width:100%;
  height:auto;
  max-width:100%;
  border-radius:8px;
}

/* VIDEO */
.thread-video{
  display:block;
  width:100%;
  height:auto;
  max-width:100%;
  border-radius:8px;
}

.pagination{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.page-link{display:inline-block;border:1px solid #e5e7eb;border-radius:8px;padding:6px 10px;text-decoration:none;color:#111}
.page-link.active{background:#2563eb;border-color:#2563eb;color:#fff}
.page-link[aria-disabled="true"]{opacity:.5;pointer-events:none}
</style>

<div class="content">
  <h2 class="m-0">Dashboard</h2>

  <?php if ($canModerate): ?>
  <div class="row mt-3">
    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= htmlspecialchars($statPendingExco) ?></div>
          <div class="lbl">Pending EXCO (Pencadang)</div>
        </div>
        <span class="badge badge-exco">EXCO</span>
      </div>
    </div>
    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= htmlspecialchars($statPendingSupport) ?></div>
          <div class="lbl">Pending EXCO (Penyokong)</div>
        </div>
        <span class="badge badge-support">SUPPORT</span>
      </div>
    </div>
    <?php if ($isAdmin): ?>
    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= htmlspecialchars($statPwdReq) ?></div>
          <div class="lbl">Pending Password Resets</div>
        </div>
        <span class="badge badge-reset">RESET</span>
      </div>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <p class="mt-3">Welcome, <strong><?= htmlspecialchars($name) ?></strong> (<?= strtoupper($role) ?>).</p>

  <!-- =================== ANNOUNCEMENTS (Thread) =================== -->
  <div class="card mt-4">
    <div class="card-header">
      <div>📣 Announcements <span class="small">— <?= (int)$annTotal ?> total</span></div>
      <?php if ($isAdmin): ?>
        <a href="settings-announcement.php" class="btn btn-primary">Manage</a>
      <?php endif; ?>
    </div>
    <div class="card-body">
      <?php if (!$annRows): ?>
        <div class="small">No announcements at the moment.</div>
      <?php else: ?>
        <?php foreach($annRows as $a): ?>
          <div class="thread-item mb-3">
            <div class="thread-head">
              <h6 class="thread-title"><?= htmlspecialchars($a['title']) ?></h6>
              <div class="thread-meta">
                <?= htmlspecialchars($a['created_at']) ?> · By <?= htmlspecialchars($a['created_name'] ?: 'System') ?>
              </div>
            </div>
            <div class="thread-body"><?= nl2br(htmlspecialchars($a['body'])) ?></div>

            <?php if (!empty($a['media_path'])): ?>
              <?php if ($a['media_type'] === 'image'): ?>
                <div class="thread-media-wrap">
                  <img class="thread-media" src="<?= htmlspecialchars($a['media_path']) ?>" alt="announcement media">
                </div>
              <?php elseif ($a['media_type'] === 'video'): ?>
                <div class="thread-media-wrap">
                  <video class="thread-video" controls preload="metadata">
                    <source src="<?= htmlspecialchars($a['media_path']) ?>">
                    Your browser does not support the video tag.
                  </video>
                </div>
              <?php endif; ?>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>

        <?php if ($annPages > 1): ?>
          <nav aria-label="Announcement pages" class="pagination">
            <?php $prev = $annPage - 1; $next = $annPage + 1; ?>
            <a class="page-link" href="?ann_page=<?= max(1,$prev) ?>" aria-disabled="<?= $annPage<=1?'true':'false' ?>">Prev</a>
            <?php for($i=1;$i<=$annPages;$i++): ?>
              <a class="page-link <?= $i===$annPage?'active':'' ?>" href="?ann_page=<?= $i ?>"><?= $i ?></a>
            <?php endfor; ?>
            <a class="page-link" href="?ann_page=<?= min($annPages,$next) ?>" aria-disabled="<?= $annPage>=$annPages?'true':'false' ?>">Next</a>
          </nav>
        <?php endif; ?>
      <?php endif; ?>
    </div>
  </div>
  <!-- =================== /ANNOUNCEMENTS (Thread) =================== -->

  <?php if ($isAdmin): ?>
    <!-- =================== Admin: Password Reset Requests (Embedded) =================== -->
    <div class="card mt-4">
      <div class="card-header">🔐 Password Reset Requests
        <span class="small">— <?= $pwdReq ? $pwdReq->num_rows : 0 ?> pending</span>
      </div>
      <div class="card-body" style="padding:0">
        <table class="table">
          <thead>
            <tr>
              <th style="width:60px">#</th>
              <th style="min-width:220px">Name</th>
              <th>Staff No.</th>
              <th>Email</th>
              <th>Phone</th>
              <th>IC (last 4)</th>
              <th class="text-end" style="width:260px">Action</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!$pwdReq || $pwdReq->num_rows === 0): ?>
            <tr><td colspan="7" class="small" style="text-align:center">Tiada permintaan reset.</td></tr>
          <?php else: $i=1; while($r=$pwdReq->fetch_assoc()): ?>
            <tr>
              <td><?= $i++ ?></td>
              <td>
                <div><strong><?= htmlspecialchars($r['full_name'] ?: '-') ?></strong></div>
                <div class="small">Requested: <?= date('d M Y H:i', strtotime($r['requested_at'])) ?></div>
              </td>
              <td><?= htmlspecialchars($r['staff_number']) ?></td>
              <td><a href="mailto:<?= htmlspecialchars($r['email']) ?>"><?= htmlspecialchars($r['email']) ?></a></td>
              <td><?= htmlspecialchars($r['phone'] ?: '-') ?></td>
              <td><?= htmlspecialchars($r['ic_last4']) ?></td>
              <td class="text-end">
                <form method="post" action="admin-password-reset.php" style="display:inline">
                  <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
                  <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-success" type="submit">Reset & Tetapkan</button>
                </form>
                <form method="post" action="admin-password-reject.php" style="display:inline">
                  <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
                  <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-danger" type="submit">Tolak</button>
                </form>
              </td>
            </tr>
          <?php endwhile; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
    <!-- =================== /Admin: Password Reset Requests (Embedded) =================== -->
  <?php endif; ?>

  <?php if ($canModerate): ?>
    <!-- =================== Pending Users (EXCO/EXCO Penyokong/Admin sahaja) =================== -->
    <?php if ($pendingUsers && $pendingUsers->num_rows > 0): ?>
      <div class="notice mt-3">
        ⚠️ You have <strong><?= $pendingUsers->num_rows ?></strong> new application(s) pending your approval.
      </div>

      <div class="card mt-4">
        <div class="card-header">
          <div>📝 New User(s) List <span class="small">— <?= $pendingUsers->num_rows ?> pending</span></div>
          <?php if ($isAdmin): ?>
            <div class="header-actions">
              <a class="btn" href="dashboard.php?print=pending" title="Cetak senarai permohonan baharu">🖨️ Cetak</a>
            </div>
          <?php endif; ?>
        </div>
        <div class="card-body" style="padding:0">
          <table class="table">
            <thead>
              <tr>
                <th style="width:60px">#</th>
                <th style="min-width:220px">Full Name</th>
                <th>Staff Number</th>
                <th>Email</th>
                <th>Phone</th>
                <th>District</th>
                <?php if ($isAdmin): ?><th class="stage-cell">Stage</th><?php endif; ?>
                <th class="text-end" style="width:280px">Action</th>
              </tr>
            </thead>
            <tbody>
              <?php $i=1; while($row=$pendingUsers->fetch_assoc()):
                $rowId   = (int)$row['id'];
                $stageLbl= (string)$row['stage']; // 'EXCO' atau 'EXCO (Penyokong)'
                $isExcoStage = ($stageLbl === 'EXCO');
                // Untuk handler lama: EXCO (Penyokong) dihantar sebagai stage='ajk'
                $stageLo = $isExcoStage ? 'exco' : 'ajk';
                $panelId = "rej_{$stageLo}_{$rowId}";
                $districtName = trim((string)($row['district'] ?? ''));
              ?>
              <tr>
                <td><?= $i++ ?></td>
                <td>
                  <div><strong><?= htmlspecialchars($row['full_name']) ?></strong></div>
                  <div class="small">Registered: <?= date('d M Y H:i', strtotime($row['created_at'])) ?></div>
                </td>
                <td><?= htmlspecialchars($row['staff_number']) ?></td>
                <td><a href="mailto:<?= htmlspecialchars($row['email']) ?>"><?= htmlspecialchars($row['email']) ?></a></td>
                <td><a href="tel:<?= htmlspecialchars($row['phone']) ?>"><?= htmlspecialchars($row['phone']) ?></a></td>
                <td>
                  <?php if ($districtName): ?>
                    <span class="badge badge-district"><?= htmlspecialchars($districtName) ?></span>
                  <?php else: ?>
                    <span class="small" style="color:#b91c1c">N/A</span>
                  <?php endif; ?>
                </td>
                <?php if ($isAdmin): ?>
                  <td class="stage-cell">
                    <span class="badge <?= $isExcoStage?'badge-exco':'badge-support' ?>"><?= htmlspecialchars($stageLbl) ?></span>
                  </td>
                <?php endif; ?>
                <td class="text-end">
                  <form action="view-user.php" method="get" style="display:inline">
                    <input type="hidden" name="id" value="<?= $rowId ?>">
                    <input type="hidden" name="level" value="<?= htmlspecialchars($role) ?>">
                    <input type="hidden" name="stage" value="<?= htmlspecialchars($stageLbl) ?>">
                    <button class="btn btn-primary" type="submit">View</button>
                  </form>

                  <form method="post" action="approval-action.php" style="display:inline" onsubmit="return validateRejectReason(event, this);">
                    <input type="hidden" name="id" value="<?= $rowId ?>">
                    <input type="hidden" name="level" value="<?= htmlspecialchars($role) ?>">
                    <input type="hidden" name="stage" value="<?= htmlspecialchars($stageLo) ?>">
                    <input type="hidden" name="action" value="approve" class="action-field">

                    <button class="btn btn-success" type="submit" data-action="approve"
                            onclick="this.closest('form').querySelector('.action-field').value='approve'">
                      Approve
                    </button>

                    <button class="btn btn-danger" type="button" onclick="toggleReject('<?= $panelId ?>', this)">Reject</button>

                    <div id="<?= $panelId ?>" class="reject-panel">
                      <?php if (count($reasons)): ?>
                        <div class="small" style="margin-bottom:6px;font-weight:600">Pilih Alasan Penolakan</div>
                        <select name="reason_id" class="select" disabled>
                          <option value="">-- Pilih alasan --</option>
                          <?php foreach($reasons as $rs): ?>
                            <option value="<?= (int)$rs['id'] ?>"><?= htmlspecialchars($rs['reason']) ?></option>
                          <?php endforeach; ?>
                        </select>
                        <div class="actions mt-2">
                          <button class="btn btn-light" type="button" onclick="toggleReject('<?= $panelId ?>')">Batal</button>
                          <button class="btn btn-danger" type="button" onclick="submitReject(this)">Hantar Penolakan</button>
                        </div>
                        <div class="small mt-2">Penolakan memerlukan pemilihan alasan daripada senarai yang disediakan.</div>
                      <?php else: ?>
                        <div class="small" style="color:#b91c1c">
                          Tiada senarai alasan aktif. Sila tambah di <em>Settings → Rejection Reasons</em>.
                        </div>
                      <?php endif; ?>
                    </div>
                  </form>
                </td>
              </tr>
              <?php endwhile; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endif; ?>
    <!-- =================== /Pending Users =================== -->
  <?php endif; ?>
</div>

<?php if ($canModerate): ?>
<script>
(function(){
  window.toggleReject = function(id, btn){
    var panel = document.getElementById(id);
    if (!panel) return;
    panel.classList.toggle('show');
    var opened = panel.classList.contains('show');

    var sel = panel.querySelector('select[name="reason_id"]');
    if (sel) { sel.disabled = !opened; if (!opened) sel.value = ''; }

    var form = btn ? btn.closest('form') : panel.closest('form');
    if (form) {
      var actionField = form.querySelector('.action-field');
      if (actionField) actionField.value = opened ? 'reject' : 'approve';
    }
  };

  window.submitReject = function(btn){
    var form = btn.closest('form');
    if (!form) return;
    var actionField = form.querySelector('.action-field');
    if (actionField) actionField.value = 'reject';
    form.submit();
  };

  window.validateRejectReason = function(ev, f){
    try {
      var intendedAction = (f.querySelector('.action-field') || {}).value || 'approve';
      if (ev && ev.submitter && ev.submitter.dataset && ev.submitter.dataset.action) {
        intendedAction = ev.submitter.dataset.action;
      }
      if (intendedAction !== 'reject') return true;

      var sel = f.querySelector('select[name="reason_id"]');
      if (!sel || sel.disabled || !sel.value) {
        alert('Sila pilih alasan penolakan.');
        return false;
      }
      return true;
    } catch(e) {
      return true;
    }
  };
})();
</script>
<?php endif; ?>

<?php if (!empty($_SESSION['temp_password'])):
  $tmp = $_SESSION['temp_password'];
  $who = $_SESSION['temp_password_for'] ?? '';
  unset($_SESSION['temp_password'], $_SESSION['temp_password_for']); // sekali guna
?>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script>
    (function(){
      try{
        const tmpPass = <?= json_encode($tmp) ?>;
        const who     = <?= json_encode($who) ?>;

        Swal.fire({
          title: 'Kata laluan sementara',
          html: `
            <div style="text-align:left">
              ${who ? `<div style="font-size:13px;margin-bottom:6px;color:#555">Untuk: <b>${who}</b></div>` : ``}
              <div style="font-size:13px;margin-bottom:10px;color:#555">
                Sila salin dan serahkan melalui saluran rasmi.
              </div>
              <div style="display:flex;gap:8px;align-items:center;margin:10px 0">
                <input id="tmpPassInput" type="text" value="${tmpPass}" readonly
                       style="flex:1;padding:10px;border:1px solid #ddd;border-radius:8px">
                <button id="copyBtn" class="swal2-confirm swal2-styled">Copy</button>
              </div>
              <label style="font-size:12px"><input type="checkbox" id="maskToggle"> Sembunyikan</label>
            </div>
          `,
          showConfirmButton: true,
          confirmButtonText: 'Tutup',
          allowOutsideClick: false,
          allowEscapeKey: false,
          didOpen: () => {
            const inp = document.getElementById('tmpPassInput');
            const btn = document.getElementById('copyBtn');
            const tog = document.getElementById('maskToggle');
            inp.focus(); inp.select();
            btn.addEventListener('click', async () => {
              try { await navigator.clipboard.writeText(inp.value); btn.textContent = 'Disalin'; }
              catch(e){ inp.select(); document.execCommand('copy'); btn.textContent = 'Disalin'; }
            });
            tog.addEventListener('change', (e) => { inp.type = e.target.checked ? 'password' : 'text'; });
          }
        });
      }catch(e){
        console.warn('SweetAlert init skipped:', e);
      }
    })();
  </script>
<?php endif; ?>

<?php
$content = ob_get_clean();
include 'layout.php';
