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

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

// Fallback: jika tiada id dalam session, cuba dapatkan dari nama (compat lama)
if (!$memberId && $name) {
  $stmt = $conn->prepare("SELECT id FROM members WHERE full_name=? AND status=1 LIMIT 1");
  $stmt->bind_param('s', $name);
  $stmt->execute();
  $stmt->bind_result($mid);
  if ($stmt->fetch()) $memberId = (int)$mid;
  $stmt->close();
}

/** Helper: ambil senarai district_id untuk user ikut role (exco|ajk) */
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));
}

// ========= Data: Pending users by role (Approval Module) =========
$pending = false;

if ($role === 'admin') {
  // Admin: gabungkan semua dengan label baharu "EXCO" dan "EXCO (Penyokong)"
  $sql = "
    SELECT u.id, u.full_name, u.staff_number, u.email, u.phone, u.created_at, u.stage, d.name AS district
    FROM (
      SELECT id, full_name, staff_number, email, phone, created_at, 'EXCO' AS stage, district_id
        FROM pending_exco
      UNION ALL
      SELECT id, full_name, staff_number, email, phone, created_at, 'EXCO (Penyokong)' AS stage, district_id
        FROM pending_ajk
    ) AS u
    LEFT JOIN districts d ON d.id = u.district_id
    ORDER BY u.created_at DESC
  ";
  $pending = $conn->query($sql);

} elseif ($role === 'exco') {
  // EXCO: UNION antara
  // 1) pending_exco ikut district assignment EXCO
  // 2) pending_ajk yang assigned kepada EXCO ini (EXCO (Penyokong))
  if ($memberId) {
    $dids = get_user_district_ids($conn, $memberId, 'exco');
    $parts = [];
    $bindTypes = '';
    $bindVals  = [];

    if (!empty($dids)) {
      $in = implode(',', array_fill(0, count($dids), '?'));
      $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.district_id IN ($in)
      ";
      $bindTypes .= str_repeat('i', count($dids));
      foreach ($dids as $did) $bindVals[] = $did;
    }

    // Sentiasa masukkan bahagian penyokong (assigned_ajk_id = saya)
    $parts[] = "
      SELECT p.id, p.full_name, p.staff_number, p.email, p.phone, p.created_at, 'EXCO (Penyokong)' AS stage, p.district_id
      FROM pending_ajk p
      WHERE p.assigned_ajk_id = ?
    ";
    $bindTypes .= 'i';
    $bindVals[] = $memberId;

    $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)) {
      // bind dinamik
      if ($bindTypes !== '') {
        $stmt->bind_param($bindTypes, ...$bindVals);
      }
      $stmt->execute();
      $pending = $stmt->get_result();
      $stmt->close();
    }
  }

} elseif ($role === 'ajk') {
  // LEGACY: ikut proses baharu, AJK = EXCO (Penyokong) yang terima tugasan (assigned_ajk_id)
  if ($memberId) {
    $sql = "
      SELECT p.id, p.full_name, p.staff_number, p.email, p.phone, p.created_at,
             'EXCO (Penyokong)' AS stage, p.district_id
      FROM pending_ajk p
      WHERE p.assigned_ajk_id = ?
      ORDER BY p.created_at DESC
    ";
    if ($stmt = $conn->prepare($sql)) {
      $stmt->bind_param('i', $memberId);
      $stmt->execute();
      $res = $stmt->get_result();
      // Balut dengan join untuk district name supaya seragam dengan admin/exco
      $rows = [];
      while ($r = $res->fetch_assoc()) $rows[] = $r;
      $stmt->close();

      if (!empty($rows)) {
        // Buat temporary table result set manual (mysqli tidak ada cara mudah)
        // Jadi, kita render terus dari array di bawah; namun untuk kekalkan struktur sedia ada (while->fetch_assoc),
        // kita tukar pendekatan: bina satu VIEW sementara melalui UNION dengan LEFT JOIN.
        $idsOnly = array_column($rows, 'id');
        // Jika mahu kekal simple: tukar kepada $pendingRows array dan render dari array.
        // Namun untuk minimum perubahan UI, jalankan semula query dengan join.
        $sql2 = "
          SELECT p.id, p.full_name, p.staff_number, p.email, p.phone, p.created_at,
                 'EXCO (Penyokong)' AS stage, d.name AS district
          FROM pending_ajk p
          LEFT JOIN districts d ON d.id = p.district_id
          WHERE p.assigned_ajk_id = ?
          ORDER BY p.created_at DESC
        ";
        if ($stmt2 = $conn->prepare($sql2)) {
          $stmt2->bind_param('i', $memberId);
          $stmt2->execute();
          $pending = $stmt2->get_result();
          $stmt2->close();
        }
      } else {
        $pending = false;
      }
    }
  }
} else {
  $pending = false;
}

// ========= Master: Rejection Reasons (active) =========
$reasons = [];
$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;

ob_start();
?>
<style>
/* ------- self-contained styles ------- */
.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}
.card-body{padding:12px 16px}
.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}
.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}
.text-end{text-align:right}
.stage-cell{white-space:nowrap}
.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-district{background:#eefdf3;color:#065f46;border:1px solid #a7f3d0}
.reject-panel{display:none;margin-top:8px;padding:10px;border:1px dashed #e5e7eb;border-radius:8px;background:#fff}
.reject-panel.show{display:block}
</style>

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

  <?php if ($pending && $pending instanceof mysqli_result && $pending->num_rows > 0): ?>
    <div class="notice mt-3">
      📝 Terdapat <strong><?= $pending->num_rows ?></strong> permohonan baharu menunggu tindakan anda.
    </div>

    <div class="card mt-4">
      <div class="card-header">Senarai Permohonan</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 ($role === 'admin'): ?><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=$pending->fetch_assoc()):
              $rowId    = (int)$row['id'];
              $district = trim((string)($row['district'] ?? ''));
              $stageLbl = (string)$row['stage']; // 'EXCO' atau 'EXCO (Penyokong)'
              $stageLo  = (strtolower($stageLbl)==='exco (penyokong)') ? 'ajk' : 'exco'; // untuk handler lama (approval-action.php)
              $panelId  = "rej_".preg_replace('/\s+/', '_', strtolower($stageLo))."_{$rowId}";
              $isExco   = ($stageLbl === 'EXCO');
            ?>
            <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 class="stage-cell">
                <?php if ($district): ?>
                  <span class="badge badge-district"><?= htmlspecialchars($district) ?></span>
                <?php else: ?>
                  <span class="small" style="color:#b91c1c">N/A</span>
                <?php endif; ?>
              </td>

              <?php if ($role === 'admin'): ?>
                <td class="stage-cell">
                  <span class="badge <?= $isExco ? 'badge-exco' : 'badge-support' ?>"><?= $stageLbl ?></span>
                </td>
              <?php endif; ?>

              <td class="text-end">
                <!-- View -->
                <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="<?= $stageLbl ?>">
                  <button class="btn btn-primary" type="submit">View</button>
                </form>

                <!-- Approve / Reject -->
                <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="<?= $stageLo ?>"><!-- lowercase untuk handler lama -->
                  <input type="hidden" name="action" value="approve" class="action-field">

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

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

                  <!-- Reject panel -->
                  <div id="<?= $panelId ?>" class="reject-panel">
                    <?php if (count($reasons)): ?>
                      <div class="small" style="margin-bottom:6px;font-weight:600">Pilih Alasan Penolakan</div>
                      <!-- MULA disabled; enable bila panel dibuka -->
                      <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 else: ?>
    <div class="card mt-3"><div class="card-body"><em>Tiada permohonan menunggu kelulusan.</em></div></div>
  <?php endif; ?>
</div>

<script>
// Tunjuk/sembunyi panel reject.
function toggleReject(id, btn){
  var panel = document.getElementById(id);
  if (!panel) return;

  panel.classList.toggle('show');
  var opened = panel.classList.contains('show');

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

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

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

// Validasi kebal: enforce alasan hanya bila Reject
function validateRejectReason(ev, f){
  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;
}
</script>

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