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

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

// ========= Helpers =========
function fetchScalar(mysqli $conn, string $sql, string $types = '', ...$params) {
  $stmt = $conn->prepare($sql);
  if (!$stmt) return 0;
  if ($types) $stmt->bind_param($types, ...$params);
  if (!$stmt->execute()) { $stmt->close(); return 0; }
  $stmt->bind_result($val);
  $stmt->fetch();
  $stmt->close();
  return (int)$val;
}

function fetchRows(mysqli $conn, string $sql, string $types = '', ...$params) {
  $stmt = $conn->prepare($sql);
  if (!$stmt) return [];
  if ($types) $stmt->bind_param($types, ...$params);
  if (!$stmt->execute()) { $stmt->close(); return []; }
  $res = $stmt->get_result();
  $rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
  $stmt->close();
  return $rows;
}

function tableExists(mysqli $conn, string $table): bool {
  $sql = "SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?";
  $stmt = $conn->prepare($sql);
  if (!$stmt) return false;
  $stmt->bind_param('s', $table);
  $ok = $stmt->execute();
  if (!$ok) { $stmt->close(); return false; }
  $stmt->store_result();
  $exists = $stmt->num_rows > 0;
  $stmt->close();
  return $exists;
}

// ========= KPI: Members & Pending =========
$totalMembers      = fetchScalar($conn, "SELECT COUNT(*) FROM members");
$totalActive       = fetchScalar($conn, "SELECT COUNT(*) FROM members WHERE status=1");
$totalInactive     = fetchScalar($conn, "SELECT COUNT(*) FROM members WHERE status=0");

$pendingExcoAll    = fetchScalar($conn, "SELECT COUNT(*) FROM pending_exco WHERE exco_approval IS NULL");
$pendingAjkAll     = fetchScalar($conn, "SELECT COUNT(*) FROM pending_ajk  WHERE ajk_approval  IS NULL");

// Scope ikut role
if ($role === 'exco') {
  $pendingExco = fetchScalar($conn, "SELECT COUNT(*) FROM pending_exco WHERE exco_approval IS NULL AND exco_auto = ?", 's', $name);
  $pendingAjk  = 0; // EXCO tak jaga AJK list
} elseif ($role === 'ajk') {
  $pendingExco = 0; // AJK tak jaga EXCO list
  $pendingAjk  = fetchScalar($conn, "SELECT COUNT(*) FROM pending_ajk WHERE ajk_approval IS NULL AND exco_select = ?", 's', $name);
} else {
  // admin
  $pendingExco = $pendingExcoAll;
  $pendingAjk  = $pendingAjkAll;
}

// ========= Recent logs (approval_logs) =========
$recentActions = [];
if (tableExists($conn, 'approval_logs')) {
  // Ikut role: filter supaya EXCO/AJK nampak log berkaitan mereka
  if ($role === 'exco') {
    $recentActions = fetchRows(
      $conn,
      "SELECT id, member_id, member_name, approved_by, role, action, rejection_reason, timestamp
         FROM approval_logs
        WHERE role='exco' AND approved_by = ?
        ORDER BY timestamp DESC, id DESC
        LIMIT 12",
      'i', (int)($_SESSION['user']['id'] ?? 0)
    );
  } elseif ($role === 'ajk') {
    $recentActions = fetchRows(
      $conn,
      "SELECT id, member_id, member_name, approved_by, role, action, rejection_reason, timestamp
         FROM approval_logs
        WHERE role='ajk' AND approved_by = ?
        ORDER BY timestamp DESC, id DESC
        LIMIT 12",
      'i', (int)($_SESSION['user']['id'] ?? 0)
    );
  } else {
    // admin: semua
    $recentActions = fetchRows(
      $conn,
      "SELECT id, member_id, member_name, approved_by, role, action, rejection_reason, timestamp
         FROM approval_logs
        ORDER BY timestamp DESC, id DESC
        LIMIT 12"
    );
  }
}

// ========= Optional: Audit logs (jika wujud) =========
// Cuba detect beberapa jadual audit yang mungkin ada di sistem anda
$auditTables = [
  'audit_trail_access',   // contoh: catat view
  'audit_trail_download', // contoh: catat download/print
  'audit_trail_action',   // contoh umum
];
$recentAudits = [];
foreach ($auditTables as $tbl) {
  if (tableExists($conn, $tbl)) {
    // cuba ambil kolum standard: id, user_id, action, target, created_at (fail-soft jika tidak wujud)
    $rows = fetchRows(
      $conn,
      "SELECT * FROM {$tbl} ORDER BY 1 DESC LIMIT 8"
    );
    if (!empty($rows)) {
      $recentAudits[$tbl] = $rows;
    }
  }
}

ob_start();
?>
<style>
/* ------- self-contained styles (no bootstrap) ------- */
.content{max-width:1200px;margin:24px auto;padding:0 16px}
.row{display:flex;gap:16px;flex-wrap:wrap}
.col{flex:1 1 280px}
.card{background:#fff;border:1px solid #e5e7eb;border-radius:12px;box-shadow:0 1px 2px rgba(0,0,0,.04)}
.card-header{padding:14px 16px;border-bottom:1px solid #f2f4f7;font-weight:700}
.card-body{padding:16px}
.kpi{display:flex;align-items:center;justify-content:space-between;padding:18px;border-radius:12px;background:#f9fafb}
.kpi .num{font-size:30px;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-ajk{background:#fff2d8;color:#92400e;border:1px solid #fde68a}
.badge-green{background:#dcfce7;color:#166534;border:1px solid #bbf7d0}
.badge-gray{background:#f3f4f6;color:#374151;border:1px solid #e5e7eb}
.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}
.m-0{margin:0}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.mt-4{margin-top:16px}.mb-0{margin-bottom:0}
.kv{display:flex;gap:8px}.kv .k{min-width:140px;color:#6b7280}
.text-right{text-align:right}
.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace}
</style>

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

  <!-- KPI Row -->
  <div class="row mt-3">
    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= number_format($totalMembers) ?></div>
          <div class="lbl">Total Members</div>
        </div>
        <span class="badge badge-green">All</span>
      </div>
    </div>

    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= number_format($totalActive) ?></div>
          <div class="lbl">Active</div>
        </div>
        <span class="badge badge-green">Active</span>
      </div>
    </div>

    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= number_format($totalInactive) ?></div>
          <div class="lbl">Inactive</div>
        </div>
        <span class="badge badge-gray">Inactive</span>
      </div>
    </div>

    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= number_format($pendingExco) ?></div>
          <div class="lbl">Pending EXCO</div>
        </div>
        <span class="badge badge-exco">EXCO</span>
      </div>
    </div>

    <div class="col">
      <div class="kpi card">
        <div>
          <div class="num"><?= number_format($pendingAjk) ?></div>
          <div class="lbl">Pending AJK</div>
        </div>
        <span class="badge badge-ajk">AJK</span>
      </div>
    </div>
  </div>

  <!-- Recent Actions -->
  <div class="card mt-4">
    <div class="card-header">Recent Approval Actions</div>
    <div class="card-body" style="padding:0">
      <?php if (!empty($recentActions)): ?>
      <table class="table">
        <thead>
          <tr>
            <th style="width:80px">#</th>
            <th>Member</th>
            <th>Action</th>
            <th>By (Role)</th>
            <th>Reason</th>
            <th class="text-right" style="width:200px">Timestamp</th>
          </tr>
        </thead>
        <tbody>
          <?php $i=1; foreach($recentActions as $row): ?>
          <tr>
            <td><?= $i++ ?></td>
            <td>
              <div><strong><?= htmlspecialchars($row['member_name'] ?? '-') ?></strong></div>
              <div class="small mono">ID: <?= (int)($row['member_id'] ?? 0) ?></div>
            </td>
            <td>
              <?php
                $act = strtolower($row['action'] ?? '');
                echo $act==='approved' ? '<span class="badge badge-green">Approved</span>' :
                     ($act==='rejected' ? '<span class="badge badge-ajk">Rejected</span>' :
                     '<span class="badge badge-gray">'.htmlspecialchars(strtoupper($act)).'</span>');
              ?>
            </td>
            <td>
              <div><?= htmlspecialchars($row['approved_by'] ?? '-') ?></div>
              <div class="small"><?= strtoupper(htmlspecialchars($row['role'] ?? '-')) ?></div>
            </td>
            <td><?= htmlspecialchars($row['rejection_reason'] ?? '') ?></td>
            <td class="text-right"><?= htmlspecialchars($row['timestamp'] ?? '') ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
      <?php else: ?>
        <div class="card-body"><em class="small">Tiada rekod tindakan terkini.</em></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Optional: Recent Audits (fail-soft) -->
  <?php if (!empty($recentAudits)): ?>
    <?php foreach($recentAudits as $tbl => $rows): ?>
      <div class="card mt-4">
        <div class="card-header">Audit (<?= htmlspecialchars($tbl) ?>)</div>
        <div class="card-body" style="padding:0">
          <table class="table">
            <thead>
              <tr>
                <?php
                  // Papar hingga 6 kolum pertama sahaja untuk kemas
                  $first = $rows[0];
                  $cols = array_keys($first);
                  $cols = array_slice($cols, 0, 6);
                  foreach ($cols as $c) echo "<th>".htmlspecialchars($c)."</th>";
                ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach($rows as $r): ?>
                <tr>
                <?php foreach($cols as $c): ?>
                  <td class="small mono"><?= htmlspecialchars((string)($r[$c] ?? '')) ?></td>
                <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>

<?php
// Optionally render within a layout shell if you have layout.php
// If your pages normally set $content and include 'layout.php', wrap as below:
$html = ob_get_clean();
if (file_exists(__DIR__.'/layout.php')) {
  $content = $html;
  include 'layout.php';
} else {
  echo $html;
}
