<?php
// /elms/admin/dashboard.php — Super Admin / Branch Admin / Coordinator dashboard (ELMS-only)
// Safe for go-live: defensive helpers, no RMS/Exam writes, column detection guards.

declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

/* ------------ DEBUG (enable with ?debug=1) -------------------------- */
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
if ($DEBUG) {
  @ini_set('display_errors','1');
  @ini_set('display_startup_errors','1');
  error_reporting(E_ALL);
} else {
  @ini_set('display_errors','0');
  error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
}

/* ------------ Includes (with graceful fallbacks) -------------------- */
require_once __DIR__ . '/../includes/auth.php'; // require_role()
require_once __DIR__ . '/../includes/db.php';   // $mysqli (preferred)
$helpers = __DIR__ . '/../includes/helpers.php';
if (is_file($helpers)) require_once $helpers;

if (!function_exists('require_role')) {
  // If your auth already guarantees role in session, this guard prevents open access.
  function require_role(array $need): void {
    $roles = (array)($_SESSION['roles'] ?? $_SESSION['user']['roles'] ?? [strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''))]);
    foreach ($need as $r) if (in_array($r, $roles, true)) return;
    http_response_code(403); echo 'Forbidden'; exit;
  }
}
require_role(['super_admin','branch_admin','coordinator']);

/* DB fallback if includes/db.php didn’t set $mysqli */
if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
  $mysqli = new mysqli('localhost','root','','edencamp_edencampus');
  $mysqli->set_charset('utf8mb4');
}

/* Minimal helper fallbacks if helpers.php didn’t define them */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}
if (!function_exists('table_exists')) {
  function table_exists(mysqli $db, string $t): bool {
    try {
      $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
      $st->bind_param('s',$t); $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
    } catch(Throwable $e){ return false; }
  }
}

/* ------------- Optional branch list provider ------------------------ */
if (!function_exists('elms_all_branches')) {
  function elms_all_branches(mysqli $db): array {
    $map = [];
    if (table_exists($db,'branches')) {
      try {
        $rs = $db->query("SELECT id, COALESCE(name, CONCAT('Branch #',id)) AS label FROM branches ORDER BY id ASC");
        while ($r = $rs->fetch_assoc()) { $map[(int)$r['id']] = (string)$r['label']; }
        $rs->close();
      } catch(Throwable $e){}
    }
    return [$map];
  }
}

/* ------------- Compatibility shim for user display name ------------- */
if (!function_exists('ec_user')) {
  function ec_user(): array {
    $nameCandidates = [
      $_SESSION['user']['name']  ?? null,
      $_SESSION['admin']['name'] ?? null,
      $_SESSION['user_name']     ?? null,
      $_SESSION['admin_name']    ?? null,
      $_SESSION['name']          ?? null,
    ];
    $name = 'Admin';
    foreach ($nameCandidates as $n) {
      if ($n && trim((string)$n) !== '') { $name = (string)$n; break; }
    }
    $id = $_SESSION['user']['id'] ?? $_SESSION['admin']['id'] ?? ($_SESSION['user_id'] ?? null);
    return ['id' => $id, 'name' => $name];
  }
}

/* ------------- Tiny helpers (no collisions) ------------------------- */
if (!function_exists('eden_column_exists')) {
  function eden_column_exists(mysqli $db, string $table, string $col): bool {
    try{
      $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
      $st->bind_param('ss',$table,$col); $st->execute();
      $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
    }catch(Throwable $e){ return false; }
  }
}
if (!function_exists('eden_one')) {
  function eden_one(mysqli $db, string $sql, string $types='', array $params=[]): ?array {
    try{ $st=$db->prepare($sql); if($types){ $st->bind_param($types,...$params); }
      $st->execute(); $r=$st->get_result()->fetch_row(); $st->close(); return $r?:null;
    }catch(Throwable $e){ return null; }
  }
}
if (!function_exists('eden_count')) {
  function eden_count(mysqli $db, string $sql, string $types='', array $params=[]): int {
    $r = eden_one($db,$sql,$types,$params); return (int)($r[0]??0);
  }
}
if (!function_exists('eden_map')) {
  function eden_map(mysqli $db, string $sql, string $types='', array $params=[]): array {
    try{
      $st=$db->prepare($sql); if($types){ $st->bind_param($types,...$params); }
      $st->execute(); $rs=$st->get_result(); $out=[];
      while($row=$rs->fetch_row()){ $out[(int)$row[0]]=(int)$row[1]; }
      $st->close(); return $out;
    }catch(Throwable $e){ return []; }
  }
}
if (!function_exists('eden_choose_table')) {
  function eden_choose_table(mysqli $db, array $cands): ?string {
    foreach ($cands as $t) { if (table_exists($db,$t)) return $t; }
    return null;
  }
}
if (!function_exists('eden_has_role')) {
  function eden_has_role(array $need): bool {
    $roles = (array)($_SESSION['roles'] ?? $_SESSION['user']['roles'] ?? [strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''))]);
    foreach ($need as $r) if (in_array($r, $roles, true)) return true;
    return false;
  }
}

/* ------------- Micro-cache (APCu → session fallback) ---------------- */
if (!function_exists('eden_cache_get')) {
  function eden_cache_get(string $key) {
    if (function_exists('apcu_fetch')) { $v = apcu_fetch($key, $ok); return $ok ? $v : null; }
    $b = $_SESSION['__cache'][$key] ?? null;
    if (!$b) return null;
    if (($b['exp'] ?? 0) < time()) { unset($_SESSION['__cache'][$key]); return null; }
    return $b['v'];
  }
}
if (!function_exists('eden_cache_set')) {
  function eden_cache_set(string $key, $val, int $ttl=60): void {
    if (function_exists('apcu_store')) { apcu_store($key, $val, $ttl); return; }
    $_SESSION['__cache'][$key] = ['v'=>$val,'exp'=>time()+$ttl];
  }
}
if (!function_exists('eden_cache_remember')) {
  function eden_cache_remember(string $key, int $ttl, callable $fn) {
    $v = eden_cache_get($key);
    if ($v !== null) return $v;
    $v = $fn();
    eden_cache_set($key, $v, $ttl);
    return $v;
  }
}

/* ------------- Branch selector state -------------------------------- */
$BRANCH_OPTIONS = '';
$BRANCH_ID = (int)($_SESSION['branch_id'] ?? 0);
[$branchMap] = elms_all_branches($mysqli);
if (isset($_GET['branch_id'])) {
  $_SESSION['branch_id'] = (int)$_GET['branch_id'];
  $BRANCH_ID = (int)$_SESSION['branch_id'];
}
if ($branchMap) {
  $BRANCH_OPTIONS = '<option value="0">SELECT BRANCH</option>';
  foreach ($branchMap as $id=>$label) {
    $BRANCH_OPTIONS .= '<option value="'.$id.'"'.($id===$BRANCH_ID?' selected':'').'>'.esc($label).'</option>';
  }
}

/* ------------- Detect ELMS tables (never touches RMS) --------------- */
$T_ENROLL     = eden_choose_table($mysqli, ['lms_enrollments','enrollments']);
$T_MODULES    = eden_choose_table($mysqli, ['lms_modules','modules']);
$T_ASSESS     = eden_choose_table($mysqli, ['lms_assessments','assessments']);
$T_SUBMIT     = eden_choose_table($mysqli, ['lms_student_assessments','lms_submissions','submissions']);
$T_GRADES     = eden_choose_table($mysqli, ['lms_grades','grades']);
$T_STUDENTS   = eden_choose_table($mysqli, ['students']);
$T_BATCHES    = eden_choose_table($mysqli, ['batches']);
$T_COURSES    = eden_choose_table($mysqli, ['courses']);
$T_VERIFY     = eden_choose_table($mysqli, ['elms_verifications']); // optional

/* ------------- KPIs (branch-aware, cached 60s) ---------------------- */
$activeStudents = eden_cache_remember('kpi_active_'.$BRANCH_ID, 60, function() use($mysqli,$T_STUDENTS,$BRANCH_ID){
  if (!$T_STUDENTS) return 0;
  $w = ($BRANCH_ID && eden_column_exists($mysqli,$T_STUDENTS,'branch_id')) ? " WHERE branch_id=? " : "";
  $p = ($w ? 'i' : ''); $v = ($w ? [$BRANCH_ID] : []);
  if (eden_column_exists($mysqli,$T_STUDENTS,'status')) {
    return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_STUDENTS} {$w}".($w?" AND ":" WHERE ")." status IN ('Active','active',1)", $p, $v);
  }
  return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_STUDENTS} {$w}", $p, $v);
});

$nonActivated = eden_cache_remember('kpi_nonact_'.$BRANCH_ID, 60, function() use($mysqli,$T_STUDENTS,$BRANCH_ID){
  if (!$T_STUDENTS) return 0;
  $w = ($BRANCH_ID && eden_column_exists($mysqli,$T_STUDENTS,'branch_id')) ? " WHERE branch_id=? " : "";
  $p = ($w ? 'i' : ''); $v = ($w ? [$BRANCH_ID] : []);
  if (eden_column_exists($mysqli,$T_STUDENTS,'is_active')) {
    return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_STUDENTS} {$w}".($w?" AND ":" WHERE ")." COALESCE(is_active,0)=0",$p,$v);
  } elseif (eden_column_exists($mysqli,$T_STUDENTS,'activated')) {
    return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_STUDENTS} {$w}".($w?" AND ":" WHERE ")." COALESCE(activated,0)=0",$p,$v);
  }
  return 0;
});

$suspended = eden_cache_remember('kpi_susp_'.$BRANCH_ID, 60, function() use($mysqli,$T_STUDENTS,$BRANCH_ID){
  if (!$T_STUDENTS || !eden_column_exists($mysqli,$T_STUDENTS,'status')) return 0;
  $w = ($BRANCH_ID && eden_column_exists($mysqli,$T_STUDENTS,'branch_id')) ? " WHERE branch_id=? " : "";
  $p = ($w ? 'i' : ''); $v = ($w ? [$BRANCH_ID] : []);
  return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_STUDENTS} {$w}".($w?" AND ":" WHERE ")." status IN ('Suspended','suspended')",$p,$v);
});

$delayedBatches = eden_cache_remember('kpi_delayed_'.$BRANCH_ID, 60, function() use($mysqli,$T_BATCHES,$BRANCH_ID){
  if (!$T_BATCHES || !eden_column_exists($mysqli,$T_BATCHES,'batch_end_date')) return 0;
  $w = " WHERE COALESCE(batch_end_date,'0000-00-00') < CURDATE() AND COALESCE(status,'') NOT IN ('Completed','Finished') ";
  if ($BRANCH_ID && eden_column_exists($mysqli,$T_BATCHES,'branch_id')) {
    return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_BATCHES} {$w} AND branch_id=?", 'i', [$BRANCH_ID]);
  }
  return eden_count($mysqli,"SELECT COUNT(*) FROM {$T_BATCHES} {$w}");
});

$nonSubmitted = eden_cache_remember('kpi_nosub_'.$BRANCH_ID, 60, function() use($mysqli,$T_ASSESS,$T_SUBMIT,$T_MODULES,$T_BATCHES,$BRANCH_ID){
  if (!$T_ASSESS || !$T_SUBMIT || !$T_MODULES) return 0;
  $joinBranch = ($BRANCH_ID && $T_BATCHES && eden_column_exists($mysqli,$T_BATCHES,'branch_id'))
    ? " JOIN {$T_BATCHES} b ON b.id=m.batch_id AND b.branch_id=? " : " ";
  $p = ($BRANCH_ID && strpos($joinBranch,'branch_id')!==false) ? 'i' : '';
  $v = ($p ? [$BRANCH_ID] : []);
  return eden_count(
    $mysqli,
    "SELECT COUNT(*) FROM {$T_ASSESS} a
     JOIN {$T_MODULES} m ON m.id=a.module_id
     {$joinBranch}
     LEFT JOIN (SELECT DISTINCT assessment_id, student_id FROM {$T_SUBMIT}) s
       ON s.assessment_id=a.id
     WHERE s.assessment_id IS NULL",
    $p, $v
  );
});

$nonMarked = eden_cache_remember('kpi_nomark_'.$BRANCH_ID, 60, function() use($mysqli,$T_ASSESS,$T_SUBMIT,$T_GRADES,$T_MODULES,$T_BATCHES,$BRANCH_ID){
  if (!$T_ASSESS || !$T_SUBMIT || !$T_GRADES || !$T_MODULES) return 0;
  $joinBranch = ($BRANCH_ID && $T_BATCHES && eden_column_exists($mysqli,$T_BATCHES,'branch_id'))
    ? " JOIN {$T_BATCHES} b ON b.id=m.batch_id AND b.branch_id=? " : " ";
  $p = ($BRANCH_ID && strpos($joinBranch,'branch_id')!==false) ? 'i' : '';
  $v = ($p ? [$BRANCH_ID] : []);
  return eden_count(
    $mysqli,
    "SELECT COUNT(*) FROM (
       SELECT DISTINCT sa.assessment_id, sa.student_id
       FROM {$T_SUBMIT} sa
     ) sub
     LEFT JOIN (
       SELECT DISTINCT g.assessment_id, g.student_id
       FROM {$T_GRADES} g
     ) g ON g.assessment_id=sub.assessment_id AND g.student_id=sub.student_id
     JOIN {$T_ASSESS} a ON a.id=sub.assessment_id
     JOIN {$T_MODULES} m ON m.id=a.module_id
     {$joinBranch}
     WHERE g.assessment_id IS NULL",
    $p, $v
  );
});

/* ------------- Batches row (with course) ---------------------------- */
$batchesRows = [];
if ($T_BATCHES) {
  $extra = '';
  $types = ''; $args = [];
  if ($BRANCH_ID && eden_column_exists($mysqli,$T_BATCHES,'branch_id')) { $extra = " WHERE b.branch_id=? "; $types='i'; $args=[$BRANCH_ID]; }
  $courseSel = ($T_COURSES && eden_column_exists($mysqli,$T_COURSES,'course_name')) ? "c.course_name" : "NULL";
  $sql = "SELECT b.id, b.batch_name, b.course_id, COALESCE(b.status,'In progress') AS status,
                 COALESCE(b.batch_start_date,NULL) AS s, COALESCE(b.batch_end_date,NULL) AS e,
                 {$courseSel} AS course_name
          FROM {$T_BATCHES} b
          LEFT JOIN {$T_COURSES} c ON c.id=b.course_id
          {$extra}
          ORDER BY b.id DESC LIMIT 6";
  try {
    $st=$mysqli->prepare($sql); if($types){ $st->bind_param($types,...$args); }
    $st->execute(); $rs=$st->get_result();
    while($r=$rs->fetch_assoc()) $batchesRows[]=$r;
    $st->close();
  } catch(Throwable $e) {}
}

/* ------------- Overdue Top-5 ---------------------------------------- */
$overdueRows = [];
if ($T_BATCHES && eden_column_exists($mysqli,$T_BATCHES,'batch_end_date')) {
  $extra = '';
  $types = ''; $args=[];
  if ($BRANCH_ID && eden_column_exists($mysqli,$T_BATCHES,'branch_id')) { $extra = " AND b.branch_id=? "; $types='i'; $args=[$BRANCH_ID]; }
  $sql = "SELECT b.id, b.batch_name, b.batch_end_date e, COALESCE(b.status,'In progress') status
          FROM {$T_BATCHES} b
          WHERE COALESCE(b.batch_end_date,'0000-00-00') < CURDATE()
            AND COALESCE(b.status,'') NOT IN ('Completed','Finished')
            {$extra}
          ORDER BY b.batch_end_date ASC
          LIMIT 5";
  try {
    $st=$mysqli->prepare($sql); if($types){ $st->bind_param($types,...$args); }
    $st->execute(); $rs=$st->get_result();
    while($r=$rs->fetch_assoc()) $overdueRows[]=$r;
    $st->close();
  } catch(Throwable $e) {}
}

/* ------------- Precomputed metrics (1 round) ------------------------ */
$metrics = []; $semMap = [];
if ($batchesRows && $T_MODULES && $T_ASSESS && $T_SUBMIT) {
  $ids = array_map(fn($r)=>(int)$r['id'], $batchesRows);
  $ph  = implode(',', array_fill(0,count($ids),'?'));
  $typ = str_repeat('i', count($ids));

  $assMap = eden_map($mysqli,
    "SELECT m.batch_id, COUNT(*) AS cnt
     FROM {$T_ASSESS} a JOIN {$T_MODULES} m ON m.id=a.module_id
     WHERE m.batch_id IN ($ph) GROUP BY m.batch_id", $typ, $ids);

  $stuMap = [];
  if ($T_ENROLL) {
    $stuMap = eden_map($mysqli,
      "SELECT batch_id, COUNT(*) AS cnt
       FROM {$T_ENROLL}
       WHERE batch_id IN ($ph) GROUP BY batch_id", $typ, $ids);
  }

  $subMap = eden_map($mysqli,
    "SELECT t.batch_id, COUNT(*) AS cnt
     FROM (
       SELECT DISTINCT m.batch_id, sa.assessment_id, sa.student_id
       FROM {$T_SUBMIT} sa
       JOIN {$T_ASSESS} a ON a.id=sa.assessment_id
       JOIN {$T_MODULES} m ON m.id=a.module_id
       WHERE m.batch_id IN ($ph)
     ) t GROUP BY t.batch_id", $typ, $ids);

  $mrkMap = [];
  if ($T_GRADES) {
    $mrkMap = eden_map($mysqli,
      "SELECT t.batch_id, COUNT(*) AS cnt
       FROM (
         SELECT DISTINCT m.batch_id, g.assessment_id, g.student_id
         FROM {$T_GRADES} g
         JOIN {$T_ASSESS} a ON a.id=g.assessment_id
         JOIN {$T_MODULES} m ON m.id=a.module_id
         WHERE m.batch_id IN ($ph)
       ) t GROUP BY t.batch_id", $typ, $ids);
  }

  if (eden_column_exists($mysqli,$T_MODULES,'semester')) {
    $semMap = eden_map($mysqli,
      "SELECT batch_id, MAX(semester) FROM {$T_MODULES} WHERE batch_id IN ($ph) GROUP BY batch_id", $typ, $ids);
  }

  foreach ($ids as $bid) {
    $ass = (int)($assMap[$bid] ?? 0);
    $stu = (int)($stuMap[$bid] ?? 0);
    $exp = ($ass && $stu) ? ($ass*$stu) : 0;
    $sub = (int)($subMap[$bid] ?? 0);
    $mrk = (int)($mrkMap[$bid] ?? 0);
    $metrics[$bid] = ['expected'=>$exp,'submitted'=>$sub,'marked'=>$mrk];
  }
}

/* ------------- Smart admin link resolver ---------------------------- */
$script = $_SERVER['SCRIPT_NAME'] ?? '/';
$base   = rtrim(str_replace('\\','/', dirname(dirname($script))), '/');
if ($base === '' || $base === '.') { $base = '/elms'; }
if ($base[0] !== '/') $base = '/'.$base;
$BASE = $base;

if (!function_exists('eden_ends_with')) {
  function eden_ends_with(string $s, string $suffix): bool {
    return $suffix === '' || substr($s, -strlen($suffix)) === $suffix;
  }
}
if (!function_exists('admin_url_guess')) {
  function admin_url_guess(string $BASE, string $rel): string {
    $rel = ltrim($rel,'/');
    $absAdmin = __DIR__; // .../elms/admin
    $cands = [];
    if (eden_ends_with($rel, '.php')) {
      $cands[] = $rel;                           // students.php
      $cands[] = substr($rel,0,-4).'/index.php'; // students/index.php
    } else {
      $cands[] = $rel.'.php';                    // students.php
      $cands[] = rtrim($rel,'/').'/index.php';   // students/index.php
    }
    foreach ($cands as $cand) {
      if (file_exists($absAdmin.'/'.$cand)) {
        if (eden_ends_with($cand, '/index.php')) {
          $path = rtrim(dirname($cand),'/').'/';
        } else {
          $path = $cand;
        }
        return rtrim($BASE,'/').'/admin/'.$path;
      }
    }
    // Fallback: prefer directory-style URL
    return rtrim($BASE,'/').'/admin/'.(eden_ends_with($rel,'.php') ? $rel : rtrim($rel,'/').'/');
  }
}
if (!function_exists('eden_url_with_qs')) {
  function eden_url_with_qs(string $url, array $qs): string {
    return $url.(strpos($url,'?')===false ? '?' : '&').http_build_query($qs);
  }
}

/* ------------- Resolve admin links ---------------------------------- */
$lnkExams        = admin_url_guess($BASE, 'assessments');
$lnkSessions     = admin_url_guess($BASE, 'assessments/sessions');
$lnkQuestions    = admin_url_guess($BASE, 'assessments/questions');
$lnkResults      = admin_url_guess($BASE, 'results');
$lnkBranches     = admin_url_guess($BASE, 'branches');
$lnkBatches      = admin_url_guess($BASE, 'batches');
$lnkCourses      = admin_url_guess($BASE, 'courses');
$lnkAnnouncements= admin_url_guess($BASE, 'announcements');

$lnkAnnIndex = $lnkAnnouncements;
$lnkAnnNew   = eden_url_with_qs($lnkAnnouncements, ['new'=>1]);

/* KPI drill links */
$lnkStudentsBase = admin_url_guess($BASE, 'students');
$lnkStudentsAll  = $lnkStudentsBase;
$lnkStudentsAct  = eden_url_with_qs($lnkStudentsBase, ['status'=>'active']);
$lnkStudentsNA   = eden_url_with_qs($lnkStudentsBase, ['status'=>'nonactivated']);
$lnkStudentsSusp = eden_url_with_qs($lnkStudentsBase, ['status'=>'suspended']);
$lnkAssessAll      = $lnkExams;
$lnkNonSubmitted   = eden_url_with_qs($lnkExams,   ['status'=>'unsubmitted']);
$lnkNonMarked      = eden_url_with_qs($lnkResults, ['status'=>'unmarked']);
$lnkDelayedBatches = eden_url_with_qs($lnkBatches, ['overdue'=>1]);

/* Optional shortcuts (only show if exist) */
$lnkVerify =
  (is_dir(__DIR__.'/verify') ? admin_url_guess($BASE, 'verify') :
  (is_dir(dirname(__DIR__).'/verify') ? rtrim($BASE,'/').'/verify/' : null));

$lnkTracking =
  (is_file(__DIR__.'/reports/tracking_sheet.php') ? admin_url_guess($BASE, 'reports/tracking_sheet') :
  (is_file(dirname(__DIR__).'/reports/tracking_sheet.php') ? rtrim($BASE,'/').'/reports/tracking_sheet.php' : null));

$PAGE_TITLE  = 'Dashboard';
$ACTIVE_MENU = 'home';

include __DIR__ . '/../includes/admin_layout_top.php';
?>
<style>
  :root{ --chip1:#f3d4e1; --chip2:#d3e6ff; --chip3:#e6d7ff; --chip4:#ffe3f1; --chip5:#eaeef7; --chip6:#f5e6ff; --card:#ffffff; }
  .pill{display:inline-block;padding:.15rem .5rem;border-radius:999px;font-size:.75rem;background:#eef2ff;color:#334155}
  .stat{border:1px solid #e6eaf3;border-radius:12px;background:var(--card);box-shadow:0 6px 24px rgba(2,8,23,.05)}
  .stat .num{display:inline-grid;place-items:center;width:36px;height:26px;font-weight:700;border-radius:6px;margin-right:.5rem}
  .chip1{background:var(--chip1)} .chip2{background:var(--chip2)} .chip3{background:var(--chip3)}
  .chip4{background:var(--chip4)} .chip5{background:var(--chip5)} .chip6{background:var(--chip6)}
  .box{border:1px solid #e8ecf5;border-radius:12px;background:var(--card)}
  .table thead th{font-size:.82rem;color:#64748b}
  tbody tr:hover{background:#f6f8ff}
  .subtle{font-size:.78rem;color:#6b7280}
  .mini-bar{position:relative;height:6px;background:#eef2ff;border-radius:999px;overflow:hidden}
  .mini-bar > i{display:block;height:100%;background:#4f46e5}
  a.text-decoration-none{color:inherit}
</style>

<div class="container-fluid">

  <div class="mb-2 d-flex flex-wrap align-items-center justify-content-between gap-2">
    <div>
      <?php $who = trim((string)ec_user()['name']) !== '' ? ec_user()['name'] : 'Admin'; ?>
      <div class="h5 mb-0">Welcome back, <?= esc($who) ?></div>
      <div class="mt-1 d-flex align-items-center flex-wrap gap-2">
        <span class="pill">Students: <?= (int)($activeStudents + $nonActivated + $suspended) ?></span>
        <span class="pill">Assessments: <?= (int)($delayedBatches + $nonSubmitted + $nonMarked) ?></span>
        <?php if ($T_VERIFY): ?>
          <span class="pill">Verify pending: <?= eden_count($mysqli,"SELECT COUNT(*) FROM {$T_VERIFY} WHERE status='pending'") ?></span>
        <?php endif; ?>
      </div>
    </div>
    <div class="d-flex flex-wrap align-items-center gap-2">
      <?php if ($BRANCH_OPTIONS): ?>
        <form method="get" class="d-flex align-items-center gap-2">
          <select name="branch_id" class="form-select form-select-sm" style="min-width:220px"><?= $BRANCH_OPTIONS ?></select>
          <button class="btn btn-sm btn-outline-secondary">Filter</button>
        </form>
      <?php endif; ?>
      <!-- Quick search to Batches -->
      <form method="get" action="<?= esc($lnkBatches) ?>" class="d-flex align-items-center gap-2">
        <input type="text" name="q" class="form-control form-control-sm" placeholder="Search batches…">
        <button class="btn btn-sm btn-outline-secondary">Go</button>
      </form>
    </div>
  </div>

<?php try { ?>
  <!-- KPI Row (clickable) -->
  <div class="row g-3">
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkStudentsAct) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip1"><?= (int)$activeStudents ?></div><div class="text-dark">Active Students</div></div>
      </a>
    </div>
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkStudentsNA) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip2"><?= (int)$nonActivated ?></div><div class="text-dark">Non-Activated</div></div>
      </a>
    </div>
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkDelayedBatches) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip3"><?= (int)$delayedBatches ?></div><div class="text-dark">Delayed Batches</div></div>
      </a>
    </div>
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkNonSubmitted) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip4"><?= (int)$nonSubmitted ?></div><div class="text-dark">Non-Submitted</div></div>
      </a>
    </div>
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkStudentsSusp) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip5"><?= (int)$suspended ?></div><div class="text-dark">Suspended</div></div>
      </a>
    </div>
    <div class="col-lg-4 col-xl-3">
      <a class="text-decoration-none" href="<?= esc($lnkNonMarked) ?>">
        <div class="stat p-3 d-flex align-items-center"><div class="num chip6"><?= (int)$nonMarked ?></div><div class="text-dark">Non-Marked</div></div>
      </a>
    </div>
  </div>
<?php } catch (Throwable $e) {
  echo '<div class="alert alert-warning mt-3">KPI panel disabled: '.esc($e->getMessage()).'</div>';
} ?>

  <!-- Overdue batches panel -->
  <?php if ($overdueRows): ?>
    <div class="box p-3 mt-3">
      <div class="fw-semibold mb-2">Overdue batches (Top 5)</div>
      <div class="table-responsive">
        <table class="table mb-0 align-middle">
          <thead><tr><th>Batch</th><th>Ended</th><th>Days Overdue</th><th>Status</th><th></th></tr></thead>
          <tbody>
            <?php foreach ($overdueRows as $r):
              $ended = (string)$r['e'];
              $days = ($ended && $ended!=='0000-00-00') ? (new DateTime($ended))->diff(new DateTime())->format('%a') : '—'; ?>
              <tr>
                <td><?= esc($r['batch_name'] ?: ('#'.$r['id'])) ?></td>
                <td><?= $ended && $ended!=='0000-00-00' ? esc(date('d/M/Y', strtotime($ended))) : '—' ?></td>
                <td><span class="badge bg-danger"><?= esc((string)$days) ?></span></td>
                <td><?= esc((string)$r['status']) ?></td>
                <td><a class="btn btn-sm btn-outline-secondary" href="<?= esc($lnkBatches.'#bid-'.$r['id']) ?>">Open</a></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

  <!-- Batches table -->
  <div class="box mt-3">
    <div class="table-responsive">
      <table class="table mb-0 align-middle">
        <thead>
          <tr>
            <th>Batch</th>
            <th>Course</th>
            <th>Days to End</th>
            <th>Current Semester / Stage</th>
            <th>Submitted</th>
            <th>Not-Submitted</th>
            <th>Marked</th>
            <th>Not-Marked</th>
            <th>Batch Status</th>
            <?php if ($lnkTracking): ?><th></th><?php endif; ?>
          </tr>
        </thead>
        <tbody>
        <?php if (!$batchesRows): ?>
          <tr><td colspan="<?= $lnkTracking?10:9 ?>" class="text-center text-muted py-4">No batches to display.</td></tr>
        <?php else:
          foreach ($batchesRows as $r):
            $bid = (int)$r['id'];
            $courseLabel = esc($r['course_name'] ?? '—');

            $daysTo = '—';
            $e = (string)($r['e'] ?? '');
            if ($e && $e!=='0000-00-00') {
              $d = (new DateTime())->diff(new DateTime($e))->format('%r%a');
              $daysTo = (int)$d;
            }

            $curSem = '—';
            if (isset($semMap[$bid]) && (int)$semMap[$bid] > 0) $curSem = 'Sem '.(int)$semMap[$bid];

            $m   = $metrics[$bid] ?? ['expected'=>0,'submitted'=>0,'marked'=>0];
            $exp = max((int)$m['expected'], 1);
            $sub = max(0,(int)$m['submitted']);
            $mrk = max(0,(int)$m['marked']);

            $pSub    = (int)round(($sub/$exp)*100);
            $pNot    = max(0, 100 - $pSub);
            $pMrk    = (int)round(($mrk/$exp)*100);
            $pNotMrk = max(0, 100 - $pMrk);
        ?>
          <tr id="<?= 'bid-'.$bid ?>">
            <td><?= esc($r['batch_name'] ?: ('#'.$bid)) ?></td>
            <td><?= $courseLabel ?></td>
            <td><?= is_numeric($daysTo) ? ($daysTo>=0 ? $daysTo.' days' : '<span class="text-danger">'.$daysTo.' days</span>') : '—' ?></td>
            <td><?= esc($curSem) ?></td>
            <td>
              <div class="mini-bar mb-1"><i style="width:<?= $pSub ?>%"></i></div>
              <span class="badge bg-primary"><?= $pSub ?>%</span>
              <span class="subtle ms-1">(<?= $sub ?>/<?= $exp ?>)</span>
            </td>
            <td><span class="badge bg-danger"><?= $pNot ?>%</span></td>
            <td>
              <div class="mini-bar mb-1"><i style="width:<?= $pMrk ?>%"></i></div>
              <span class="badge bg-success"><?= $pMrk ?>%</span>
              <span class="subtle ms-1">(<?= $mrk ?>/<?= $exp ?>)</span>
            </td>
            <td><span class="badge bg-warning text-dark"><?= $pNotMrk ?>%</span></td>
            <td><?= esc((string)$r['status']) ?></td>
            <?php if ($lnkTracking): ?>
              <td><a class="btn btn-sm btn-outline-secondary" href="<?= esc($lnkTracking.'?batch='.$bid) ?>">Tracking</a></td>
            <?php endif; ?>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Bottom boxes -->
  <div class="row g-3 mt-3">
    <div class="col-lg-6">
      <div class="box p-3">
        <div class="fw-semibold mb-2">Assessments &amp; Quizzes</div>
        <div class="d-flex flex-wrap gap-2">
          <a class="btn btn-sm btn-primary"           href="<?= esc($lnkExams) ?>">Exams</a>
          <a class="btn btn-sm btn-outline-primary"   href="<?= esc($lnkSessions) ?>">Sessions</a>
          <a class="btn btn-sm btn-outline-primary"   href="<?= esc($lnkQuestions) ?>">Questions</a>
          <a class="btn btn-sm btn-outline-primary"   href="<?= esc($lnkResults) ?>">Results</a>
          <?php if ($lnkVerify && eden_has_role(['super_admin'])): ?>
            <a class="btn btn-sm btn-outline-primary" href="<?= esc($lnkVerify) ?>">Verification</a>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="box p-3">
        <div class="fw-semibold mb-2">Branches · Batches · Courses</div>
        <div class="d-flex flex-wrap gap-2">
          <a class="btn btn-sm btn-outline-secondary" href="<?= esc($lnkBranches) ?>">Branches</a>
          <a class="btn btn-sm btn-primary"           href="<?= esc($lnkBatches) ?>">Batches</a>
          <a class="btn btn-sm btn-outline-secondary" href="<?= esc($lnkCourses) ?>">Courses</a>
        </div>
      </div>
    </div>
    <div class="col-lg-2">
      <div class="box p-3">
        <div class="fw-semibold mb-2">Announcements</div>
        <div class="d-grid gap-2">
          <a class="btn btn-sm btn-primary"           href="<?= esc($lnkAnnIndex) ?>">Manage</a>
          <a class="btn btn-sm btn-outline-secondary" href="<?= esc($lnkAnnNew) ?>">New</a>
        </div>
      </div>
    </div>
  </div>

  <?php if ($DEBUG): ?>
    <div class="alert alert-info mt-3">
      <strong>Debug:</strong>
      <pre style="white-space:pre-wrap"><?php
        $tables = ['students','batches','courses','lms_modules','modules','lms_assessments','assessments','lms_student_assessments','lms_submissions','submissions','lms_grades','grades','lms_enrollments','enrollments','elms_verifications'];
        foreach ($tables as $t) {
          echo $t.': '.(table_exists($mysqli,$t)?'YES':'no').PHP_EOL;
        }
      ?></pre>
    </div>
  <?php endif; ?>

</div>

<?php include __DIR__ . '/../includes/admin_layout_bottom.php';
