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

// Admin only
if (!isset($_SESSION['user']) || ($_SESSION['user']['role'] ?? '') !== 'admin') {
    header("Location: dashboard.php");
    exit;
}

/* =========================
   Filters & pagination
   ========================= */
$start   = trim($_GET['start']  ?? '');
$end     = trim($_GET['end']    ?? '');
$role    = trim($_GET['role']   ?? '');                 // exco|ajk|admin|''(all)
$action  = strtoupper(trim($_GET['action'] ?? ''));     // APPROVED|REJECTED|''(all)
$q       = trim($_GET['q']      ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset  = ($page - 1) * $perPage;

$conds  = [];
$types  = '';
$params = [];

// Tarikh (rujuk lajur al.timestamp)
if ($start !== '') { $conds[] = "al.`timestamp` >= ?"; $types .= 's'; $params[] = $start . ' 00:00:00'; }
if ($end   !== '') { $conds[] = "al.`timestamp` <= ?"; $types .= 's'; $params[] = $end   . ' 23:59:59'; }

/* =========================
   Role filter: cover EXCO varian
   ========================= */
$excoVariants = [
  'exco','exco_proposer','exco_supporter',
  'exco_pencadang','exco_penyokong',
  'proposer','supporter','pencadang','penyokong'
];

if ($role !== '') {
    if (strtolower($role) === 'exco') {
        // WHERE al.role IN (exco + semua varian EXCO)
        $placeholders = implode(',', array_fill(0, count($excoVariants), '?'));
        $conds[] = "LOWER(al.role) IN ($placeholders)";
        $types  .= str_repeat('s', count($excoVariants));
        foreach ($excoVariants as $rv) { $params[] = strtolower($rv); }
    } else {
        // AJK atau ADMIN ikut nilai tepat
        $conds[] = "LOWER(al.role) = ?";
        $types  .= 's';
        $params[]= strtolower($role);
    }
}

// Action (DB simpan lowercase, kita banding uppercase untuk mudah)
if ($action === 'APPROVED' || $action === 'REJECTED') {
    $conds[] = "UPPER(al.action) = ?";
    $types  .= 's';
    $params[]= $action;
}

// Carian umum (nama, role, action, alasan, pelulus, district)
if ($q !== '') {
    $conds[] = "("
        ."COALESCE(al.member_name, m.full_name) LIKE ? "
        ."OR al.role LIKE ? "
        ."OR al.action LIKE ? "
        ."OR COALESCE(rr.reason, al.rejection_reason) LIKE ? "
        ."OR approver.full_name LIKE ? "
        ."OR d.name LIKE ?"
        .")";
    $kw = "%$q%";
    $types  .= 'ssssss';
    array_push($params, $kw, $kw, $kw, $kw, $kw, $kw);
}

$where = $conds ? ('WHERE '.implode(' AND ', $conds)) : '';

/* =========================
   Helpers
   ========================= */
function mustPrepare(mysqli $conn, string $sql): mysqli_stmt {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        error_log("[approval-history] prepare failed: ".$conn->error." :: SQL=".$sql);
        die("Server error: failed to prepare statement.");
    }
    return $stmt;
}
function displayRoleLabel(?string $dbRole): string {
    $r = strtolower($dbRole ?? '');
    // EXCO variants → map jelas
    if (in_array($r, ['exco','exco_proposer','proposer','pencadang','exco_pencadang'], true)) {
        return 'EXCO (Pencadang)';
    }
    if (in_array($r, ['exco_supporter','supporter','penyokong','exco_penyokong'], true)) {
        return 'EXCO (Penyokong)';
    }
    if ($r === 'ajk')   return 'AJK';
    if ($r === 'admin') return 'Admin';
    return strtoupper($r ?: '-');
}
function actionBadge(string $act): string {
    return strtoupper($act) === 'APPROVED'
        ? '<span class="badge badge-ok">Approved</span>'
        : '<span class="badge badge-ng">Rejected</span>';
}

/* =========================
   Export CSV
   ========================= */
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $sql = "
      SELECT
        al.id,
        COALESCE(al.member_name, m.full_name) AS member_name,
        UPPER(al.action) AS action,
        COALESCE(rr.reason, al.rejection_reason) AS reason_text,
        approver.full_name AS actor_name,
        al.role AS role_raw,
        d.name AS district_name,
        al.`timestamp`
      FROM approval_logs al
      LEFT JOIN members m              ON m.id = al.member_id
      LEFT JOIN rejection_reasons rr   ON rr.id = al.rejection_reason_id
      LEFT JOIN members approver       ON approver.id = al.approved_by
      LEFT JOIN districts d            ON d.id = al.district_id
      $where
      ORDER BY al.`timestamp` DESC
    ";
    $stmt = mustPrepare($conn, $sql);
    if ($types !== '') $stmt->bind_param($types, ...$params);
    if (!$stmt->execute()) { error_log("[approval-history] execute export: ".$stmt->error); die("Server error during export."); }
    $res = $stmt->get_result();

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=approval_history.csv');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Nama Pemohon','Tindakan','Alasan','Pelulus','Role','District','Tarikh']);
    while ($r = $res->fetch_assoc()) {
        fputcsv($out, [
            $r['member_name'] ?: '',
            $r['action'],
            $r['reason_text'] ?: '',
            $r['actor_name'] ?: '',
            displayRoleLabel($r['role_raw']),
            $r['district_name'] ?: 'N/A',
            date('Y-m-d H:i:s', strtotime($r['timestamp']))
        ]);
    }
    fclose($out);
    exit;
}

/* =========================
   Count + Rows (paginated)
   ========================= */
// COUNT
$sqlCount = "
  SELECT COUNT(*) AS c
  FROM approval_logs al
  LEFT JOIN members m            ON m.id = al.member_id
  LEFT JOIN rejection_reasons rr ON rr.id = al.rejection_reason_id
  LEFT JOIN members approver     ON approver.id = al.approved_by
  LEFT JOIN districts d          ON d.id = al.district_id
  $where
";
$stmt = mustPrepare($conn, $sqlCount);
if ($types !== '') $stmt->bind_param($types, ...$params);
if (!$stmt->execute()) { error_log("[approval-history] execute count: ".$stmt->error); die("Server error."); }
$total = (int)$stmt->get_result()->fetch_assoc()['c'];
$stmt->close();

$totalPages = max(1, (int)ceil($total / $perPage));

// ROWS (LIMIT/OFFSET as integers)
$limit  = (int)$perPage;
$off    = (int)$offset;

$sqlRows = "
  SELECT
    al.id,
    COALESCE(al.member_name, m.full_name) AS member_name,
    UPPER(al.action) AS action,
    COALESCE(rr.reason, al.rejection_reason) AS reason_text,
    approver.full_name AS actor_name,
    al.role AS role_raw,
    d.name AS district_name,
    al.`timestamp`
  FROM approval_logs al
  LEFT JOIN members m            ON m.id = al.member_id
  LEFT JOIN rejection_reasons rr ON rr.id = al.rejection_reason_id
  LEFT JOIN members approver     ON approver.id = al.approved_by
  LEFT JOIN districts d          ON d.id = al.district_id
  $where
  ORDER BY al.`timestamp` DESC
  LIMIT $limit OFFSET $off
";
$stmt = mustPrepare($conn, $sqlRows);
if ($types !== '') $stmt->bind_param($types, ...$params);
if (!$stmt->execute()) { error_log("[approval-history] execute rows: ".$stmt->error); die("Server error."); }
$res  = $stmt->get_result();
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
$stmt->close();

/* =========================
   View
   ========================= */
ob_start();
?>
<style>
.card{background:#fff;border:1px solid #e5e7eb;border-radius:10px}
.card-header{padding:12px 14px;border-bottom:1px solid #f0f0f0;font-weight:600}
.card-body{padding:12px 14px}
.table{width:100%;border-collapse:separate;border-spacing:0}
.table th,.table td{padding:10px 12px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
.table thead th{background:#343a40;color:#fff}
.badge{display:inline-block;padding:4px 10px;border-radius:9999px;font-size:12px;font-weight:600}
.badge-ok{background:#16a34a;color:#fff}
.badge-ng{background:#dc2626;color:#fff}
.badge-role{background:#6b7280;color:#fff}
.badge-district{background:#eefdf3;color:#065f46;border:1px solid #a7f3d0}
.input,.select{padding:8px;border:1px solid #d1d5db;border-radius:8px}
.btn{border:1px solid #d1d5db;background:#fff;border-radius:8px;padding:6px 10px;font-size:13px;cursor:pointer}
.btn-primary{background:#2563eb;color:#fff;border-color:#2563eb}
.btn-light{background:#f3f4f6}
.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0}
.pager{display:flex;gap:6px;flex-wrap:wrap;margin-top:12px}
.pager a{padding:6px 10px;border:1px solid #d1d5db;border-radius:8px;text-decoration:none;color:#111}
.pager a.active{background:#2563eb;color:#fff;border-color:#2563eb}
.small{font-size:12px;color:#6b7280}
.reason{white-space:pre-wrap}
</style>

<div class="content">
  <h2>Approval History</h2>

  <div class="card" style="margin:12px 0;">
    <div class="card-body">
      <form method="get" class="toolbar">
        <input class="input" type="date" name="start" value="<?= htmlspecialchars($start) ?>">
        <input class="input" type="date" name="end"   value="<?= htmlspecialchars($end) ?>">
        <select name="action" class="select">
          <option value="">All Actions</option>
          <option value="APPROVED" <?= $action==='APPROVED'?'selected':'' ?>>Approved</option>
          <option value="REJECTED" <?= $action==='REJECTED'?'selected':'' ?>>Rejected</option>
        </select>
        <select name="role" class="select">
          <option value="">All Roles</option>
          <option value="exco"  <?= $role==='exco' ?'selected':'' ?>>EXCO (Semua: Pencadang & Penyokong)</option>
          <option value="ajk"   <?= $role==='ajk'  ?'selected':'' ?>>AJK</option>
          <option value="admin" <?= $role==='admin'?'selected':'' ?>>Admin</option>
        </select>
        <input class="input" type="text" name="q" placeholder="Cari nama/alasan/pelulus/district" value="<?= htmlspecialchars($q) ?>" style="min-width:260px">
        <button class="btn btn-primary" type="submit">Filter</button>
        <a class="btn btn-light" href="approval-history.php">Reset</a>
        <a class="btn btn-light" href="approval-history.php?<?= http_build_query(['start'=>$start,'end'=>$end,'action'=>$action,'role'=>$role,'q'=>$q,'export'=>'csv']) ?>">Export CSV</a>
      </form>
      <div class="small">Jumlah rekod: <strong><?= number_format($total) ?></strong></div>
    </div>
  </div>

  <div class="card">
    <div class="card-body" style="padding:0">
      <table class="table">
        <thead>
          <tr>
            <th style="width:60px">#</th>
            <th>Nama Pemohon</th>
            <th style="width:120px">Tindakan</th>
            <th>Alasan</th>
            <th>Pelulus</th>
            <th style="width:160px">District</th>
            <th style="width:180px">Role</th>
            <th style="width:160px">Tarikh</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="8" style="text-align:center;">Tiada log pengesahan ditemui.</td></tr>
          <?php else: $i=$offset+1; foreach ($rows as $r): ?>
            <tr>
              <td><?= $i++ ?></td>
              <td><?= htmlspecialchars($r['member_name'] ?: 'N/A') ?></td>
              <td style="text-align:center;"><?= actionBadge($r['action']) ?></td>
              <td class="reason"><?= htmlspecialchars($r['reason_text'] ?: '-') ?></td>
              <td><?= htmlspecialchars($r['actor_name'] ?: 'N/A') ?></td>
              <td>
                <?php if (!empty($r['district_name'])): ?>
                  <span class="badge badge-district"><?= htmlspecialchars($r['district_name']) ?></span>
                <?php else: ?>
                  <span class="small" style="color:#b91c1c">N/A</span>
                <?php endif; ?>
              </td>
              <td><span class="badge badge-role"><?= htmlspecialchars(displayRoleLabel($r['role_raw'])) ?></span></td>
              <td><?= date('d/m/Y H:i', strtotime($r['timestamp'])) ?></td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <?php if ($totalPages > 1): ?>
  <div class="pager">
    <?php for ($p=1; $p<=$totalPages; $p++):
      $qs = $_GET; $qs['page']=$p; $href='?'.http_build_query($qs); ?>
      <a href="<?= $href ?>" class="<?= $p===$page?'active':'' ?>"><?= $p ?></a>
    <?php endfor; ?>
  </div>
  <?php endif; ?>
</div>

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