<?php
/*
  MY SMART KOKU - PREMIUM MINIMALIS
  Fungsi:
  - Dashboard bersepadu
  - 1 carian kod koko
  - Mendaftar Projek Khas / Tiada Projek Khas
  - Paparan data lengkap
  - Carta pie CSS
  - Kategori warna berbeza
  - Projek disusun ikut kategori
  - Print slip individu A4
  - Print slip kelas A4

  Simpan sebagai index.php
*/

$LOGO_KOLEJ = "https://kistarp.edu.my/pentadbiran/logo/01%20LOGO%20KISTARP%20TIADA%20LATAR.png";

$CSV_KEHADIRAN = [
  "KPA" => [
    "label" => "Kelab Persatuan / Akademik",
    "url" => "https://docs.google.com/spreadsheets/d/e/2PACX-1vRvCUlR8BTeas0WN1BJdukvsrMDahMozGqxn4tXzP9wJ30k1O45M96U8oQCiz75jha_xnaDbnJR6V-B/pub?gid=238356273&single=true&output=csv"
  ],
  "KSP" => [
    "label" => "Kelab Sukan Permainan",
    "url" => "https://docs.google.com/spreadsheets/d/e/2PACX-1vQQ1pkm5-9-orMBgaL2FT95dOCEG9QDjujjeWJFZFWnBD8Ms2Fh2jdc_P_LpZEoFV3MBXPOGP2YvaaM/pub?gid=670357784&single=true&output=csv"
  ],
  "PBB" => [
    "label" => "Pasukan Badan Beruniform",
    "url" => "https://docs.google.com/spreadsheets/d/e/2PACX-1vQ0q6bqJrJMEp4hOuekT-yJQj6akUspHI2BN0eZo5iUvvqc3a05kzNMnKPIuFXUbVDeN-8HhqK5CaoC/pub?gid=1899593118&single=true&output=csv"
  ]
];

$CSV_MAKLUMAT_KOKU = "https://docs.google.com/spreadsheets/d/e/2PACX-1vTRaTOBtzhUyVBSXWZt2kRO6ERQ26ZKTjPrepp-BNTAYLyNYizu0SdeHGBhVijraCaB-pL3_nyKqw7-/pub?gid=1638833648&single=true&output=csv";
$CSV_SENARAI_NAMA  = "https://docs.google.com/spreadsheets/d/e/2PACX-1vTRaTOBtzhUyVBSXWZt2kRO6ERQ26ZKTjPrepp-BNTAYLyNYizu0SdeHGBhVijraCaB-pL3_nyKqw7-/pub?gid=324221260&single=true&output=csv";

/* =========================
   HELPER
========================= */

function e($text){
  return htmlspecialchars((string)$text, ENT_QUOTES, "UTF-8");
}

function clean_text($text){
  $text = preg_replace('/^\xEF\xBB\xBF/', '', (string)$text);
  $text = preg_replace('/\x{FEFF}/u', '', $text);
  $text = str_replace("\xc2\xa0", " ", $text);
  $text = trim($text);
  $text = preg_replace('/\s+/', ' ', $text);
  return $text;
}

function norm($text){
  $text = clean_text($text);
  $text = str_replace([" ", "\t", "\n", "\r", "-"], "", $text);
  return strtoupper($text);
}

function upper_clean($text){
  return strtoupper(clean_text($text));
}

function has_text($haystack, $needle){
  return stripos((string)$haystack, (string)$needle) !== false;
}

function fetch_csv_rows($url){
  $context = stream_context_create([
    "http" => [
      "method" => "GET",
      "timeout" => 25,
      "header" => "User-Agent: MY-SMART-KOKU/5.0\r\n"
    ]
  ]);

  $csv = @file_get_contents($url, false, $context);

  if ($csv === false && function_exists("curl_init")) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_CONNECTTIMEOUT => 10,
      CURLOPT_TIMEOUT => 25,
      CURLOPT_USERAGENT => "MY-SMART-KOKU/5.0"
    ]);
    $csv = curl_exec($ch);
    curl_close($ch);
  }

  if (!$csv) return ["headers" => [], "rows" => []];

  $csv = preg_replace('/^\xEF\xBB\xBF/', '', $csv);

  $fp = fopen("php://temp", "r+");
  fwrite($fp, $csv);
  rewind($fp);

  $headers = fgetcsv($fp);
  if (!$headers) return ["headers" => [], "rows" => []];

  $headers = array_map("clean_text", $headers);
  $rows = [];

  while (($data = fgetcsv($fp)) !== false) {
    $hasData = false;
    foreach ($data as $v) {
      if (trim((string)$v) !== "") {
        $hasData = true;
        break;
      }
    }
    if (!$hasData) continue;

    $row = [];
    foreach ($headers as $i => $h) {
      if ($h === "") continue;
      $row[$h] = clean_text(isset($data[$i]) ? $data[$i] : "");
    }
    $rows[] = $row;
  }

  fclose($fp);
  return ["headers" => $headers, "rows" => $rows];
}

function getv($row, $keys, $default = ""){
  foreach ((array)$keys as $key) {
    if (isset($row[$key]) && clean_text($row[$key]) !== "") {
      return clean_text($row[$key]);
    }
  }
  return $default;
}

function find_col($headers, $keys){
  foreach ($headers as $h) {
    $hh = upper_clean($h);
    foreach ($keys as $k) {
      if (strpos($hh, upper_clean($k)) !== false) return $h;
    }
  }
  return "";
}

function is_identity_header($h){
  $h = upper_clean($h);
  $skip = [
    "TIMESTAMP", "NAMA", "KOD", "KELAS", "SEMESTER", "UNIT",
    "NO KAD", "KAD PENGENALAN", "IC", "NO KP", "JANTINA"
  ];
  foreach ($skip as $s) {
    if (strpos($h, $s) !== false) return true;
  }
  return false;
}

function kategori_unit($unit){
  $u = upper_clean($unit);

  if ($u === "KELAB SUKAN PERMAINAN") return "SUKAN DAN PERMAINAN";
  if ($u === "KELAB PERSATUAN AKADEMIK") return "KELAB DAN PERSATUAN";
  if ($u === "PASUKAN BADAN BERUNIFORM") return "BADAN BERUNIFORM";

  if (has_text($u, "BADAN BERUNIFORM") || has_text($u, "BERUNIFORM")) return "BADAN BERUNIFORM";
  if (has_text($u, "SUKAN") || has_text($u, "PERMAINAN")) return "SUKAN DAN PERMAINAN";
  if (has_text($u, "PERSATUAN") || has_text($u, "AKADEMIK") || has_text($u, "KELAB")) return "KELAB DAN PERSATUAN";

  return "LAIN-LAIN";
}

function kategori_order($kategori){
  $order = [
    "KELAB DAN PERSATUAN" => 1,
    "SUKAN DAN PERMAINAN" => 2,
    "BADAN BERUNIFORM" => 3,
    "LAIN-LAIN" => 4
  ];
  return isset($order[$kategori]) ? $order[$kategori] : 9;
}

function kategori_class($kategori){
  if ($kategori === "KELAB DAN PERSATUAN") return "cat-kpa";
  if ($kategori === "SUKAN DAN PERMAINAN") return "cat-ksp";
  if ($kategori === "BADAN BERUNIFORM") return "cat-pbb";
  return "cat-other";
}

function markah_jawatan($jawatan){
  $j = upper_clean($jawatan);

  if (
    has_text($j, "PENOLONG SETIAUSAHA") ||
    has_text($j, "PENOLONG BENDAHARI") ||
    has_text($j, "AHLI JAWATANKUASA") ||
    preg_match('/\bAJK\b/u', $j)
  ) return 6;

  if (
    has_text($j, "NAIB PENGERUSI") ||
    has_text($j, "PENOLONG KETUA RUMAH") ||
    has_text($j, "PENOLONG KAPTEN") ||
    has_text($j, "SETIAUSAHA") ||
    has_text($j, "BENDAHARI")
  ) return 8;

  if (
    has_text($j, "PENGERUSI") ||
    has_text($j, "KAPTEN PASUKAN") ||
    has_text($j, "KETUA RUMAH")
  ) return 10;

  if (has_text($j, "AHLI AKTIF")) return 4;
  if (has_text($j, "AHLI BERDAFTAR")) return 2;

  return 2;
}

function jawatan_fields(){
  return [
    "PENGERUSI",
    "NAIB PENGERUSI",
    "SETIAUSAHA",
    "PENOLONG SETIAUSAHA",
    "BENDAHARI",
    "PENOLONG BENDAHARI",
    "AJK 1",
    "AJK 2",
    "AJK 3",
    "AJK 4"
  ];
}

function sort_kod($a, $b){
  preg_match('/^([A-Z]+)(\d+)/i', $a, $ma);
  preg_match('/^([A-Z]+)(\d+)/i', $b, $mb);

  $pa = strtoupper(isset($ma[1]) ? $ma[1] : $a);
  $pb = strtoupper(isset($mb[1]) ? $mb[1] : $b);

  $order = ["L" => 1, "P" => 2];

  $oa = isset($order[$pa]) ? $order[$pa] : 9;
  $ob = isset($order[$pb]) ? $order[$pb] : 9;

  if ($oa !== $ob) return $oa - $ob;

  $na = intval(isset($ma[2]) ? $ma[2] : 0);
  $nb = intval(isset($mb[2]) ? $mb[2] : 0);

  if ($na !== $nb) return $na - $nb;
  return strcmp($a, $b);
}

function status_projek($s){
  return count($s["projek"]) > 0 ? "ADA PROJEK KHAS" : "TIADA PROJEK KHAS";
}

function status_kehadiran($s){
  return intval($s["jumlahHadir"]) > 0 ? "ADA KEHADIRAN" : "TIADA KEHADIRAN";
}

function sort_projek(&$projek){
  usort($projek, function($a, $b){
    $ka = kategori_order($a["kategori"]);
    $kb = kategori_order($b["kategori"]);
    if ($ka !== $kb) return $ka - $kb;
    return strcmp($a["program"], $b["program"]);
  });
}

function pie_style($a, $b, $c){
  $total = max(1, $a + $b + $c);
  $p1 = ($a / $total) * 100;
  $p2 = (($a + $b) / $total) * 100;
  return "background:conic-gradient(#2563eb 0 {$p1}%, #16a34a {$p1}% {$p2}%, #f59e0b {$p2}% 100%);";
}

function render_slip($s, $kod, $autoPageBreak = false){
  sort_projek($s["projek"]);

  $pageClass = $autoPageBreak ? " slip-page" : "";

  echo '<section class="slip'.$pageClass.'">';
  echo '<div class="slip-top">';
  echo '<div class="slip-brand">';
  echo '<img src="https://kistarp.edu.my/pentadbiran/logo/01%20LOGO%20KISTARP%20TIADA%20LATAR.png" alt="Logo">';
  echo '<div>';
  echo '<div class="slip-kicker">MY SMART KOKU</div>';
  echo '<h2>Slip Rumusan Kokurikulum</h2>';
  echo '<p>Kolej Tingkatan Enam (Prauniversiti) Tunku Abdul Rahman Putra</p>';
  echo '</div>';
  echo '</div>';
  echo '<div class="slip-code">'.e($s["kod"] ?: $kod).'</div>';
  echo '</div>';

  echo '<div class="slip-profile">';
  echo '<div><span>Nama</span><b>'.e($s["nama"] ?: "-").'</b></div>';
  echo '<div><span>Kelas</span><b>'.e($s["kelas"] ?: "-").'</b></div>';
  echo '<div><span>No. KP</span><b>'.e($s["kp"] ?: "-").'</b></div>';
  echo '<div><span>Jantina</span><b>'.e($s["jantina"] ?: "-").'</b></div>';
  echo '</div>';

  echo '<div class="slip-status">';
  echo '<div><span>Status Projek</span><b>'.e(status_projek($s)).'</b></div>';
  echo '<div><span>Status Kehadiran</span><b>'.e(status_kehadiran($s)).'</b></div>';
  echo '<div><span>Jumlah Kehadiran</span><b>'.e($s["jumlahHadir"]).'</b></div>';
  echo '<div><span>Markah Jawatan</span><b>'.e($s["jumlahMarkah"]).'</b></div>';
  echo '</div>';

  echo '<h3>Kehadiran Kokurikulum</h3>';
  echo '<table class="slip-table">';
  echo '<thead><tr><th>Komponen</th><th>Unit</th><th>Kehadiran</th></tr></thead>';
  echo '<tbody>';
  echo '<tr><td>KPA</td><td>'.e($s["unit"]["KPA"]).'</td><td>'.e($s["hadir"]["KPA"]).'</td></tr>';
  echo '<tr><td>KSP</td><td>'.e($s["unit"]["KSP"]).'</td><td>'.e($s["hadir"]["KSP"]).'</td></tr>';
  echo '<tr><td>PBB</td><td>'.e($s["unit"]["PBB"]).'</td><td>'.e($s["hadir"]["PBB"]).'</td></tr>';
  echo '</tbody></table>';

  echo '<h3>Projek Khas / Program</h3>';
  if (!count($s["projek"])) {
    echo '<p class="slip-empty">Timendaftar projek khas / program.</p>';
  } else {
    echo '<table class="slip-table">';
    echo '<thead><tr><th>Bil</th><th>Kategori</th><th>Program</th><th>Jawatan</th><th>Markah</th></tr></thead>';
    echo '<tbody>';
    $bil = 1;
    foreach ($s["projek"] as $p) {
      echo '<tr>';
      echo '<td>'.e($bil++).'</td>';
      echo '<td>'.e($p["kategori"]).'</td>';
      echo '<td><b>'.e($p["program"]).'</b><br><small>'.e(trim($p["tarikh"]." · ".$p["peringkat"]." · ".$p["unit"], " ·")).'</small></td>';
      echo '<td>'.e($p["jawatan"]).'</td>';
      echo '<td>'.e($p["markah"]).'</td>';
      echo '</tr>';
    }
    echo '</tbody></table>';
  }

  echo '<div class="slip-note">Slip ini dijana melalui sistem MY SMART KOKU berdasarkan data CSV yang diterbitkan.</div>';
  echo '</section>';
}

/* =========================
   PROSES DATA
========================= */

$students = [];
$errorLoad = false;

foreach ($CSV_KEHADIRAN as $type => $info) {
  $csvData = fetch_csv_rows($info["url"]);
  $headers = $csvData["headers"];
  $rows = $csvData["rows"];

  if (!$headers || !$rows) {
    $errorLoad = true;
    continue;
  }

  $namaKey  = find_col($headers, ["NAMA"]);
  $kelasKey = find_col($headers, ["KELAS"]);
  $kodKey   = find_col($headers, ["KOD KOKO", "KOD"]);
  $unitKey  = find_col($headers, ["UNIT KOKURIKULUM", "UNIT"]);

  foreach ($rows as $row) {
    $nama  = $namaKey ? clean_text(isset($row[$namaKey]) ? $row[$namaKey] : "") : "";
    $kelas = $kelasKey ? clean_text(isset($row[$kelasKey]) ? $row[$kelasKey] : "") : "";
    $kod   = $kodKey ? norm(isset($row[$kodKey]) ? $row[$kodKey] : "") : "";
    $unit  = $unitKey ? clean_text(isset($row[$unitKey]) ? $row[$unitKey] : "") : $info["label"];

    if ($nama === "" && $kod === "") continue;

    $key = $kod !== "" ? $kod : norm($nama);

    if (!isset($students[$key])) {
      $students[$key] = [
        "nama" => "",
        "kelas" => "",
        "kod" => $kod,
        "kp" => "",
        "jantina" => "",
        "catatan" => "",
        "unit" => ["KPA" => "-", "KSP" => "-", "PBB" => "-"],
        "hadir" => ["KPA" => 0, "KSP" => 0, "PBB" => 0],
        "jumlahHadir" => 0,
        "projek" => [],
        "jumlahMarkah" => 0
      ];
    }

    if ($students[$key]["nama"] === "" && $nama !== "") $students[$key]["nama"] = $nama;
    if ($students[$key]["kelas"] === "" && $kelas !== "") $students[$key]["kelas"] = $kelas;
    if ($students[$key]["kod"] === "" && $kod !== "") $students[$key]["kod"] = $kod;
    if ($unit !== "") $students[$key]["unit"][$type] = $unit;

    $count = 0;
    foreach ($headers as $h) {
      if (is_identity_header($h)) continue;
      $v = isset($row[$h]) ? clean_text($row[$h]) : "";
      if ($v !== "") $count++;
    }

    $students[$key]["hadir"][$type] += $count;
    $students[$key]["jumlahHadir"] += $count;
  }
}

$senaraiData = fetch_csv_rows($CSV_SENARAI_NAMA);
foreach ($senaraiData["rows"] as $row) {
  $kod = norm(getv($row, ["KOD", "KOD KOKO", "Kod"]));
  if ($kod === "") continue;

  if (!isset($students[$kod])) {
    $students[$kod] = [
      "nama" => "",
      "kelas" => "",
      "kod" => $kod,
      "kp" => "",
      "jantina" => "",
      "catatan" => "",
      "unit" => ["KPA" => "-", "KSP" => "-", "PBB" => "-"],
      "hadir" => ["KPA" => 0, "KSP" => 0, "PBB" => 0],
      "jumlahHadir" => 0,
      "projek" => [],
      "jumlahMarkah" => 0
    ];
  }

  $students[$kod]["nama"] = getv($row, ["NAMA", "Nama"], $students[$kod]["nama"]);
  $students[$kod]["kelas"] = getv($row, ["KELAS", "Kelas"], $students[$kod]["kelas"]);
  $students[$kod]["kp"] = getv($row, ["KP", "NO KP", "NO KAD PENGENALAN", "NOMBOR KAD PENGENALAN"], $students[$kod]["kp"]);
  $students[$kod]["jantina"] = getv($row, ["JANTINA", "Jantina"], $students[$kod]["jantina"]);
  $students[$kod]["catatan"] = getv($row, ["CATATAN", "Catatan"], $students[$kod]["catatan"]);
}

$projekData = fetch_csv_rows($CSV_MAKLUMAT_KOKU);
if (!$projekData["headers"]) $errorLoad = true;

$kategoriCount = [
  "KELAB DAN PERSATUAN" => 0,
  "SUKAN DAN PERMAINAN" => 0,
  "BADAN BERUNIFORM" => 0,
  "LAIN-LAIN" => 0
];

foreach ($projekData["rows"] as $row) {
  $unit = getv($row, ["UNIT KOKURIKULUM"]);
  $program = getv($row, ["NAMA PROGRAM"]);
  $tarikh = getv($row, ["TARIKH PROGRAM"]);
  $peringkat = getv($row, ["PERINGKAT PENGLIBATAN"]);
  $semester = getv($row, ["STPM 2026"]);

  if ($unit === "" && $program === "") continue;

  $kategori = kategori_unit($unit);
  if (!isset($kategoriCount[$kategori])) $kategoriCount[$kategori] = 0;
  $kategoriCount[$kategori]++;

  foreach (jawatan_fields() as $jawatan) {
    $kodField = "KOD KOKO - " . $jawatan;
    $namaField = "NAMA " . $jawatan;
    $kelasField = "KELAS - " . $jawatan;
    $semField = "SEMESTER - " . $jawatan;

    $kod = norm(getv($row, [$kodField]));
    if ($kod === "") continue;

    if (!isset($students[$kod])) {
      $students[$kod] = [
        "nama" => "",
        "kelas" => "",
        "kod" => $kod,
        "kp" => "",
        "jantina" => "",
        "catatan" => "",
        "unit" => ["KPA" => "-", "KSP" => "-", "PBB" => "-"],
        "hadir" => ["KPA" => 0, "KSP" => 0, "PBB" => 0],
        "jumlahHadir" => 0,
        "projek" => [],
        "jumlahMarkah" => 0
      ];
    }

    $namaP = getv($row, [$namaField]);
    $kelasP = getv($row, [$kelasField]);
    if ($students[$kod]["nama"] === "" && $namaP !== "") $students[$kod]["nama"] = $namaP;
    if ($students[$kod]["kelas"] === "" && $kelasP !== "") $students[$kod]["kelas"] = $kelasP;

    $markah = markah_jawatan($jawatan);
    $students[$kod]["projek"][] = [
      "kategori" => $kategori,
      "unit" => $unit,
      "program" => $program,
      "tarikh" => $tarikh,
      "peringkat" => $peringkat,
      "semester" => getv($row, [$semField], $semester),
      "jawatan" => $jawatan,
      "markah" => $markah
    ];
    $students[$kod]["jumlahMarkah"] += $markah;
  }
}

foreach ($students as $k => $v) {
  sort_projek($students[$k]["projek"]);
}

/* Ringkasan */
$allKod = array_keys($students);
usort($allKod, "sort_kod");

$adaProjek = [];
$tiadaProjek = [];
$totalKPA = 0;
$totalKSP = 0;
$totalPBB = 0;
$totalHadir = 0;
$totalMarkah = 0;
$kelasCount = [];

foreach ($allKod as $kod) {
  $s = $students[$kod];

  if (count($s["projek"]) > 0) $adaProjek[] = $kod;
  else $tiadaProjek[] = $kod;

  $totalKPA += intval($s["hadir"]["KPA"]);
  $totalKSP += intval($s["hadir"]["KSP"]);
  $totalPBB += intval($s["hadir"]["PBB"]);
  $totalHadir += intval($s["jumlahHadir"]);
  $totalMarkah += intval($s["jumlahMarkah"]);

  $kelas = clean_text($s["kelas"]);
  if ($kelas === "") $kelas = "TIADA KELAS";
  if (!isset($kelasCount[$kelas])) $kelasCount[$kelas] = 0;
  $kelasCount[$kelas]++;
}

usort($adaProjek, "sort_kod");
usort($tiadaProjek, "sort_kod");
ksort($kelasCount);

$page = isset($_GET["page"]) ? $_GET["page"] : "utama";
$kodCari = isset($_GET["kod"]) ? norm($_GET["kod"]) : "";
$kelasCari = isset($_GET["kelas"]) ? upper_clean($_GET["kelas"]) : "";

$selected = ($kodCari !== "" && isset($students[$kodCari])) ? $students[$kodCari] : null;

$totalPelajar = count($allKod);
$totalAda = count($adaProjek);
$totalTiada = count($tiadaProjek);

$kelasOptions = array_keys($kelasCount);
$pieKehadiran = pie_style($totalKPA, $totalKSP, $totalPBB);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MY SMART KOKU</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#f5f8fd;
  --card:#ffffff;
  --text:#172033;
  --muted:#667085;
  --line:#e5edf6;
  --blue:#2563eb;
  --green:#16a34a;
  --orange:#f59e0b;
  --purple:#7c3aed;
  --red:#dc2626;
  --shadow:0 18px 50px rgba(15,23,42,.075);
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{
  margin:0;
  font-family:Poppins,Arial,sans-serif;
  background:
    radial-gradient(circle at top left, rgba(37,99,235,.10), transparent 30%),
    linear-gradient(180deg,#f8fbff,#f3f7fc);
  color:var(--text);
}
a{text-decoration:none;color:inherit}
.wrap{width:min(1180px,94%);margin:0 auto;padding:18px 0 46px}

/* TOP */
.header{
  background:rgba(255,255,255,.92);
  border:1px solid var(--line);
  border-radius:28px;
  padding:16px 20px;
  box-shadow:var(--shadow);
  backdrop-filter:blur(10px);
  margin-bottom:16px;
}
.header-row{
  display:flex;
  justify-content:space-between;
  gap:20px;
  align-items:center;
}
.brand{
  display:flex;
  align-items:center;
  gap:13px;
  min-width:330px;
}
.brand img{
  width:46px;
  height:46px;
  object-fit:contain;
}
.brand small{
  display:block;
  color:var(--blue);
  letter-spacing:.12em;
  text-transform:uppercase;
  font-size:11px;
  font-weight:700;
}
.brand h1{
  margin:2px 0 0;
  font-size:28px;
  line-height:1;
  letter-spacing:-.045em;
}
.menu{
  display:flex;
  gap:2px;
  align-items:center;
  justify-content:flex-end;
  border-bottom:1px solid var(--line);
}
.menu a,.drop-btn{
  border:0;
  background:transparent;
  color:#344054;
  font:500 13px Poppins,Arial;
  padding:14px 13px;
  border-bottom:2px solid transparent;
  cursor:pointer;
  border-radius:0;
}
.menu a:hover,.drop:hover .drop-btn{
  color:var(--blue);
  border-bottom-color:var(--blue);
}
.menu a.active{
  color:var(--blue);
  border-bottom-color:var(--blue);
}
.drop{
  position:relative;
}
.drop-menu{
  display:none;
  position:absolute;
  right:0;
  top:46px;
  min-width:220px;
  background:#fff;
  border:1px solid var(--line);
  border-radius:16px;
  box-shadow:0 20px 46px rgba(15,23,42,.13);
  padding:8px;
  z-index:50;
}
.drop:hover .drop-menu{display:block}
.drop-menu a{
  display:block;
  border:0;
  border-radius:12px;
  padding:10px 12px;
}
.drop-menu a:hover{
  background:#f8fbff;
}

/* SEARCH */
.search-panel{
  margin-top:16px;
  background:#f8fbff;
  border:1px solid var(--line);
  border-radius:22px;
  padding:11px;
}
.search-row{
  display:grid;
  grid-template-columns:1fr auto;
  gap:10px;
}
input,select,button,.btn{font-family:Poppins,Arial,sans-serif}
input,select{
  width:100%;
  border:1px solid var(--line);
  border-radius:16px;
  padding:13px 14px;
  font-size:14px;
  outline:none;
  background:#fff;
  text-transform:uppercase;
}
input:focus,select:focus{
  border-color:var(--blue);
  box-shadow:0 0 0 4px rgba(37,99,235,.09);
}
button,.btn{
  border:0;
  border-radius:16px;
  padding:13px 15px;
  font-size:14px;
  font-weight:500;
  cursor:pointer;
  color:#fff;
  background:var(--blue);
  display:inline-flex;
  align-items:center;
  justify-content:center;
  white-space:nowrap;
}
.btn.light,button.light{
  color:#172033;
  background:#fff;
  border:1px solid var(--line);
}
.btn.small,button.small{padding:8px 11px;border-radius:12px;font-size:12px}

/* CARDS */
.alert{background:#fff;border:1px solid #fecaca;color:#991b1b;border-radius:16px;padding:13px;margin-bottom:16px;font-size:14px}
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.stat,.card,.menu-card{
  background:#fff;
  border:1px solid var(--line);
  box-shadow:0 12px 34px rgba(15,23,42,.045);
}
.stat{border-radius:22px;padding:16px}
.stat span{display:block;color:var(--muted);font-size:12px}
.stat b{display:block;margin-top:6px;font-size:27px;font-weight:600;letter-spacing:-.035em;color:var(--blue)}
.grid-main{display:grid;grid-template-columns:1.1fr .9fr;gap:16px;margin-bottom:16px}
.grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.menu-card{display:block;border-radius:24px;padding:20px;transition:.15s}
.menu-card:hover{transform:translateY(-2px);border-color:rgba(37,99,235,.42)}
.menu-card h2{margin:0 0 8px;font-size:20px;font-weight:600;letter-spacing:-.02em}
.menu-card p{margin:0;color:var(--muted);font-size:14px;line-height:1.6}
.menu-card b{display:block;margin-top:12px;font-size:32px;font-weight:600;color:var(--blue)}
.card{border-radius:24px;padding:18px;margin-bottom:16px}
.section-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:14px}
.section-head h2{margin:0;font-size:20px;font-weight:600;letter-spacing:-.02em}
.section-head p{margin:4px 0 0;color:var(--muted);font-size:13px}
.head-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}

/* PIE */
.chart-card{display:grid;grid-template-columns:170px 1fr;gap:18px;align-items:center}
.pie{
  width:156px;height:156px;border-radius:50%;
  box-shadow:inset 0 0 0 16px rgba(255,255,255,.65), 0 18px 36px rgba(15,23,42,.08);
  position:relative;
}
.pie:after{
  content:"";
  position:absolute;
  inset:44px;
  background:#fff;
  border-radius:50%;
}
.legend{display:grid;gap:9px}
.legend-row{display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:13px;color:#344054}
.legend-left{display:flex;align-items:center;gap:8px}
.dot{width:10px;height:10px;border-radius:999px}
.dot.blue{background:#2563eb}.dot.green{background:#16a34a}.dot.orange{background:#f59e0b}.dot.purple{background:#7c3aed}

/* PROFILE */
.info-grid{display:grid;grid-template-columns:1.18fr .82fr;gap:16px}
.info-list{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
.info{border:1px solid var(--line);border-radius:16px;padding:12px;background:#fff}
.info span{display:block;color:var(--muted);font-size:12px;margin-bottom:4px}
.info b{font-size:14px;font-weight:500}
.score-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.score{border:1px solid var(--line);border-radius:18px;padding:15px}
.score span{color:var(--muted);font-size:12px}
.score b{display:block;font-size:30px;font-weight:600;color:var(--blue);margin-top:5px}
.pill{display:inline-flex;align-items:center;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:600;width:max-content}
.pill.ok{background:#ecfdf5;color:#15803d}.pill.no{background:#fff1f2;color:#be123c}.pill.blue{background:#eff6ff;color:#1d4ed8}.pill.orange{background:#fff7ed;color:#c2410c}

/* TABLE */
.empty{color:var(--muted);font-size:14px;margin:0}
.kod-grid{display:flex;flex-wrap:wrap;gap:8px}
.kod-grid a{color:var(--blue);border:1px solid var(--line);border-radius:13px;padding:8px 10px;min-width:54px;text-align:center;font-size:14px;background:#fff}
.kod-grid.tiada a{color:#334155}
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px}
table{width:100%;border-collapse:collapse;min-width:980px}
th,td{border-bottom:1px solid var(--line);padding:12px 13px;text-align:left;vertical-align:top;font-size:13px}
th{color:#475569;font-weight:500;background:#fbfcfe}
.badge{display:inline-block;padding:5px 9px;border-radius:999px;font-size:12px;margin:2px 2px 2px 0}
.badge.red{background:#fff1f2;color:#be123c}.badge.green{background:#ecfdf5;color:#15803d}.badge.gray{background:#f1f5f9;color:#475569}
.badge.cat-kpa{background:#f5f3ff;color:#6d28d9}
.badge.cat-ksp{background:#eff6ff;color:#1d4ed8}
.badge.cat-pbb{background:#fff7ed;color:#c2410c}
.badge.cat-other{background:#f1f5f9;color:#475569}
.program{display:block;font-weight:500}
td small{display:block;color:var(--muted);margin-top:4px}
.total{font-weight:600;color:var(--blue)}
.footer{text-align:center;color:var(--muted);font-size:12px;margin-top:20px}
.float-top{position:fixed;right:16px;bottom:16px;z-index:30;border-radius:999px;width:50px;height:50px;box-shadow:0 12px 30px rgba(37,99,235,.25)}


.grid-2-premium{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.premium-action{display:grid;grid-template-columns:56px 1fr;gap:16px;align-items:start}
.card-icon{width:50px;height:50px;border-radius:18px;background:linear-gradient(135deg,#ecfdf5,#d1fae5);color:#15803d;display:grid;place-items:center;font-size:22px;font-weight:700}
.card-icon.warn{background:linear-gradient(135deg,#fff7ed,#ffedd5);color:#c2410c}
.mini-icon{font-size:22px;margin-right:10px;vertical-align:2px}
.stat{position:relative;overflow:hidden}
.stat:after{content:"";position:absolute;right:-18px;top:-22px;width:86px;height:86px;border-radius:999px;background:rgba(37,99,235,.07)}
.stat:nth-child(1) b:before{content:"👥 ";font-size:22px}
.stat:nth-child(2) b:before{content:"📊 ";font-size:22px}
.stat:nth-child(3) b:before{content:"✅ ";font-size:22px}
.stat:nth-child(4) b:before{content:"⚠️ ";font-size:22px}
.menu-card h2{display:inline;background:linear-gradient(transparent 64%,rgba(37,99,235,.14) 0)}
.header{padding:18px 22px}
.search-panel{margin-top:18px}
.simple-search input{font-size:15px;padding:15px 18px}
.simple-search button{padding-inline:24px}

/* SLIP */
.slip{background:#fff;border:1px solid var(--line);border-radius:24px;padding:20px;margin-bottom:16px;box-shadow:0 12px 34px rgba(15,23,42,.045)}
.slip-top{display:flex;justify-content:space-between;gap:14px;border-bottom:2px solid #eaf1fb;padding-bottom:12px;margin-bottom:14px}
.slip-brand{display:flex;align-items:center;gap:10px}
.slip-brand img{width:42px;height:42px;object-fit:contain}
.slip-kicker{font-size:11px;letter-spacing:.14em;color:var(--blue);font-weight:700}
.slip h2{margin:3px 0;font-size:25px;letter-spacing:-.03em}
.slip p{margin:0;color:#5b6678;font-size:12px}
.slip-code{min-width:90px;height:54px;border-radius:18px;background:#eff6ff;color:var(--blue);display:flex;align-items:center;justify-content:center;font-size:23px;font-weight:700}
.slip-profile,.slip-status{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:12px}
.slip-profile div,.slip-status div{border:1px solid #e6edf5;border-radius:14px;padding:9px}
.slip-profile span,.slip-status span{display:block;font-size:10px;color:#667085;margin-bottom:3px}
.slip-profile b,.slip-status b{font-size:12px;font-weight:600}
.slip h3{font-size:14px;margin:12px 0 7px}
.slip-table{min-width:0;border:1px solid #e6edf5;border-radius:12px;overflow:hidden}
.slip-table th,.slip-table td{font-size:11px;padding:7px 8px}
.slip-table th{background:#f8fbff}
.slip-table small{font-size:10px}
.slip-empty{background:#f8fafc;border:1px solid #e6edf5;border-radius:12px;padding:10px;font-size:12px!important}
.slip-note{margin-top:12px;font-size:10px;color:#667085;border-top:1px solid #e6edf5;padding-top:8px}
.print-only{display:none}

@media(max-width:900px){
  .wrap{width:94%;padding-top:12px}
  .header{border-radius:22px;padding:15px}
  .header-row{display:block}
  .brand{min-width:0}
  .menu{margin-top:14px;justify-content:flex-start;overflow:auto}
  .drop-menu{left:0;right:auto}
  .search-row{grid-template-columns:1fr}
  button,.btn{width:100%}
  .stats{grid-template-columns:repeat(2,1fr)}
  .grid-main,.grid-3,.grid-2-premium,.info-grid{grid-template-columns:1fr}
  .chart-card{grid-template-columns:1fr}
  .info-list,.score-grid,.slip-profile,.slip-status{grid-template-columns:1fr}
  .section-head{display:block}
  .head-actions{justify-content:flex-start;margin-top:12px}
  .card,.menu-card,.slip{border-radius:20px;padding:15px}
  .pie{margin:auto}
  .slip-top{display:block}
  .slip-code{margin-top:10px}
}

@media print{
  @page{size:A4 portrait;margin:10mm}
  body{background:#fff;color:#111827}
  .no-print,.header,.footer,.float-top,.screen-only{display:none!important}
  .print-only{display:block!important}
  .wrap{width:100%;padding:0}
  .card,.stat,.slip{box-shadow:none!important}
  .slip{width:100%;min-height:270mm;border:0;border-radius:0;padding:0;margin:0;page-break-after:always;break-after:page}
  .slip:last-child{page-break-after:auto;break-after:auto}
  .slip h2{font-size:22px}
  .slip-profile,.slip-status{grid-template-columns:repeat(4,1fr)}
  .slip-table th,.slip-table td{font-size:10.5px;padding:6px 7px}
}
</style>
</head>
<body>

<div class="wrap">

  <header class="header no-print">
    <div class="header-row">
      <div class="brand">
        <img src="<?= e($LOGO_KOLEJ) ?>" alt="Logo KISTARP">
        <div>
          <small>Kolej Tingkatan Enam Tunku Abdul Rahman Putra</small>
          <h1>MY SMART KOKU</h1>
        </div>
      </div>

      <nav class="menu">
        <a class="<?= $page === "utama" ? "active" : "" ?>" href="?page=utama">Dashboard</a>
        <div class="drop">
          <button type="button" class="drop-btn">Projek Khas ▾</button>
          <div class="drop-menu">
            <a href="?page=ada">Mendaftar Projek Khas</a>
            <a href="?page=tiada">Tiada Projek Khas</a>
          </div>
        </div>

        <div class="drop">
          <button type="button" class="drop-btn">Cetakan ▾</button>
          <div class="drop-menu">
            <a href="?page=kelas">Print Slip Kelas</a>
            <a href="javascript:window.print()">Print Paparan Ini</a>
          </div>
        </div>
      </nav>
    </div>

    <form class="search-panel" method="get" action="">
      <input type="hidden" name="page" value="semak">
      <div class="search-row simple-search">
        <input type="text" name="kod" placeholder="Cari kod koko. Contoh L29 / P64" value="<?= e($kodCari) ?>">
        <button type="submit">Cari Kod</button>
      </div>
    </form>
  </header>

  <?php if ($errorLoad): ?>
    <div class="alert no-print">Sebahagian CSV tidak dapat dibaca. Semak pautan publish CSV atau tetapan hosting.</div>
  <?php endif; ?>

  <?php if ($page === "utama"): ?>

    <div class="grid-main">
      <section class="card chart-card">
        <div class="pie" style="<?= e($pieKehadiran) ?>"></div>
        <div>
          <div class="section-head" style="margin-bottom:10px">
            <div>
              <h2>Ringkasan Kehadiran</h2>
              <p>KPA, KSP dan PBB</p>
            </div>
          </div>
          <div class="legend">
            <div class="legend-row"><span class="legend-left"><i class="dot blue"></i>KPA</span><b><?= e($totalKPA) ?></b></div>
            <div class="legend-row"><span class="legend-left"><i class="dot green"></i>KSP</span><b><?= e($totalKSP) ?></b></div>
            <div class="legend-row"><span class="legend-left"><i class="dot orange"></i>PBB</span><b><?= e($totalPBB) ?></b></div>
          </div>
        </div>
      </section>

      <section class="card chart-card">
        <?php
          $projekTotal = max(1, $totalAda + $totalTiada);
          $projekAdaPct = ($totalAda / $projekTotal) * 100;
          $projekPie = "background:conic-gradient(#16a34a 0 {$projekAdaPct}%, #dc2626 {$projekAdaPct}% 100%);";
        ?>
        <div class="pie" style="<?= e($projekPie) ?>"></div>
        <div>
          <div class="section-head" style="margin-bottom:10px">
            <div>
              <h2>Projek Khas</h2>
              <p>Status rekod pelajar</p>
            </div>
          </div>
          <div class="legend">
            <div class="legend-row"><span class="legend-left"><i class="dot green"></i>Mendaftar</span><b><?= e($totalAda) ?></b></div>
            <div class="legend-row"><span class="legend-left"><i class="dot" style="background:#dc2626"></i>Tiada Projek</span><b><?= e($totalTiada) ?></b></div>
          </div>
        </div>
      </section>
    </div>

    <div class="stats">
      <div class="stat"><span>Jumlah Kod / Pelajar</span><b><?= e($totalPelajar) ?></b></div>
      <div class="stat"><span>Jumlah Kehadiran</span><b><?= e($totalHadir) ?></b></div>
      <div class="stat"><span>Mendaftar Projek Khas</span><b><?= e($totalAda) ?></b></div>
      <div class="stat"><span>Tiada Projek Khas</span><b><?= e($totalTiada) ?></b></div>
    </div>

    <div class="grid-2-premium">
      <a class="menu-card premium-action" href="?page=ada">
        <div class="card-icon">✓</div>
        <div>
          <h2>Mendaftar Projek Khas</h2>
          <p>Senarai kod koko pelajar yang telah mendaftar projek khas.</p>
          <b><span class="mini-icon">👥</span><?= e($totalAda) ?></b>
        </div>
      </a>
      <a class="menu-card premium-action" href="?page=tiada">
        <div class="card-icon warn">!</div>
        <div>
          <h2>Tiada Projek Khas</h2>
          <p>Senarai kod koko pelajar yang belum mendaftar projek khas.</p>
          <b><span class="mini-icon">👤</span><?= e($totalTiada) ?></b>
        </div>
      </a>
    </div>

  <?php elseif ($page === "semak"): ?>

    <?php if ($kodCari === ""): ?>
      <section class="card">
        <div class="section-head">
          <div>
            <h2>Carian Kod Koko</h2>
            <p>Masukkan kod koko di bahagian carian atas.</p>
          </div>
        </div>
        <p class="empty">Contoh: L29, L128, P64, P159.</p>
      </section>
    <?php elseif (!$selected): ?>
      <section class="card">
        <div class="section-head">
          <div>
            <h2>Tiada Rekod</h2>
            <p>Kod dicari: <?= e($kodCari) ?></p>
          </div>
        </div>
        <p class="empty">Kod ini tiada dalam data kehadiran atau projek khas.</p>
      </section>
    <?php else: ?>

      <div class="screen-only">
        <div class="info-grid">
          <section class="card">
            <div class="section-head">
              <div>
                <h2><?= e($selected["nama"] ?: "Maklumat Pelajar") ?></h2>
                <p>KOD KOKO: <?= e($selected["kod"] ?: $kodCari) ?></p>
              </div>
              <div class="head-actions">
                <span class="pill <?= count($selected["projek"]) ? "ok" : "no" ?>"><?= e(status_projek($selected)) ?></span>
                <span class="pill <?= intval($selected["jumlahHadir"]) ? "blue" : "orange" ?>"><?= e(status_kehadiran($selected)) ?></span>
              </div>
            </div>

            <div class="info-list">
              <div class="info"><span>Kelas</span><b><?= e($selected["kelas"] ?: "-") ?></b></div>
              <div class="info"><span>No. KP</span><b><?= e($selected["kp"] ?: "-") ?></b></div>
              <div class="info"><span>Jantina</span><b><?= e($selected["jantina"] ?: "-") ?></b></div>
              <div class="info"><span>Catatan</span><b><?= e($selected["catatan"] ?: "-") ?></b></div>
              <div class="info"><span>Unit KPA</span><b><?= e($selected["unit"]["KPA"]) ?></b></div>
              <div class="info"><span>Unit KSP</span><b><?= e($selected["unit"]["KSP"]) ?></b></div>
              <div class="info"><span>Unit PBB</span><b><?= e($selected["unit"]["PBB"]) ?></b></div>
              <div class="info"><span>Status</span><b><?= e(status_projek($selected)) ?></b></div>
            </div>
          </section>

          <section class="card">
            <div class="score-grid">
              <div class="score"><span>KPA</span><b><?= e($selected["hadir"]["KPA"]) ?></b></div>
              <div class="score"><span>KSP</span><b><?= e($selected["hadir"]["KSP"]) ?></b></div>
              <div class="score"><span>PBB</span><b><?= e($selected["hadir"]["PBB"]) ?></b></div>
              <div class="score"><span>Jumlah Hadir</span><b><?= e($selected["jumlahHadir"]) ?></b></div>
              <div class="score"><span>Bil. Projek</span><b><?= e(count($selected["projek"])) ?></b></div>
              <div class="score"><span>Markah</span><b><?= e($selected["jumlahMarkah"]) ?></b></div>
            </div>
          </section>
        </div>

        <section class="card">
          <div class="section-head">
            <div>
              <h2>Data Projek Khas / Program</h2>
              <p><?= e(count($selected["projek"])) ?> rekod · disusun ikut kategori</p>
            </div>
            <button class="btn small light" type="button" onclick="window.print()">Print Slip A4</button>
          </div>

          <?php if (!count($selected["projek"])): ?>
            <p class="empty">Timendaftar projek khas / program.</p>
          <?php else: ?>
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Bil</th>
                    <th>Kategori</th>
                    <th>Program</th>
                    <th>Jawatan</th>
                    <th>Markah</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $bil=1; foreach ($selected["projek"] as $p): ?>
                    <tr>
                      <td><?= e($bil++) ?></td>
                      <td><span class="badge <?= e(kategori_class($p["kategori"])) ?>"><?= e($p["kategori"]) ?></span></td>
                      <td>
                        <span class="program"><?= e($p["program"]) ?></span>
                        <small><?= e(trim($p["tarikh"]." · ".$p["peringkat"]." · ".$p["unit"], " ·")) ?></small>
                      </td>
                      <td><?= e($p["jawatan"]) ?></td>
                      <td class="total"><?= e($p["markah"]) ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </section>
      </div>

      <div class="print-only">
        <?php render_slip($selected, $kodCari); ?>
      </div>

    <?php endif; ?>

  <?php elseif ($page === "ada" || $page === "tiada"): ?>

    <?php
      $list = $page === "ada" ? $adaProjek : $tiadaProjek;
      $title = $page === "ada" ? "Senarai Mendaftar Projek Khas" : "Senarai Tiada Projek Khas";
      $cls = $page === "ada" ? "ada" : "tiada";
    ?>

    <section class="card">
      <div class="section-head">
        <div>
          <h2><?= e($title) ?></h2>
          <p><?= e(count($list)) ?> kod koko · tekan kod untuk lihat slip individu</p>
        </div>
        <div class="head-actions">
          <a class="btn small light" href="?page=utama">Kembali</a>
          <button class="btn small light" type="button" onclick="window.print()">Cetak Senarai</button>
        </div>
      </div>

      <?php if (!count($list)): ?>
        <p class="empty">Tiada rekod.</p>
      <?php else: ?>
        <div class="kod-grid <?= e($cls) ?>">
          <?php foreach ($list as $kod): ?>
            <a href="?page=semak&kod=<?= urlencode($kod) ?>"><?= e($kod) ?></a>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>

  <?php elseif ($page === "kelas"): ?>

    <section class="card no-print">
      <div class="section-head">
        <div>
          <h2>Print Slip Mengikut Kelas</h2>
          <p>Pilih kelas, kemudian setiap pelajar akan dicetak sebagai satu slip A4.</p>
        </div>
      </div>

      <form method="get" action="">
        <input type="hidden" name="page" value="kelas">
        <div class="search-row">
          <select name="kelas">
            <option value="">Pilih kelas</option>
            <?php foreach ($kelasOptions as $kelas): ?>
              <option value="<?= e($kelas) ?>" <?= $kelasCari === upper_clean($kelas) ? "selected" : "" ?>><?= e($kelas) ?></option>
            <?php endforeach; ?>
          </select>
          <span></span>
          <button type="submit">Papar Kelas</button>
          <?php if ($kelasCari !== ""): ?>
            <button type="button" class="light" onclick="window.print()">Print Semua Slip</button>
          <?php endif; ?>
        </div>
      </form>
    </section>

    <?php if ($kelasCari === ""): ?>
      <section class="card">
        <p class="empty">Sila pilih kelas terlebih dahulu.</p>
      </section>
    <?php else: ?>
      <?php
        $kelasList = [];
        foreach ($allKod as $kod) {
          $s = $students[$kod];
          if (upper_clean($s["kelas"]) === $kelasCari) $kelasList[$kod] = $s;
        }
      ?>

      <section class="card no-print">
        <div class="section-head">
          <div>
            <h2>Kelas <?= e($kelasCari) ?></h2>
            <p><?= e(count($kelasList)) ?> pelajar / kod koko</p>
          </div>
          <button type="button" class="btn small light" onclick="window.print()">Print Semua Slip</button>
        </div>

        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Bil</th>
                <th>Kod</th>
                <th>Nama</th>
                <th>Kehadiran</th>
                <th>Projek Khas</th>
                <th>Markah</th>
              </tr>
            </thead>
            <tbody>
              <?php $bil=1; foreach ($kelasList as $kod => $s): ?>
                <tr>
                  <td><?= e($bil++) ?></td>
                  <td><a class="badge cat-ksp" href="?page=semak&kod=<?= urlencode($kod) ?>"><?= e($s["kod"] ?: $kod) ?></a></td>
                  <td><?= e($s["nama"]) ?></td>
                  <td class="total"><?= e($s["jumlahHadir"]) ?></td>
                  <td><span class="badge <?= count($s["projek"]) ? "green" : "red" ?>"><?= e(status_projek($s)) ?></span></td>
                  <td class="total"><?= e($s["jumlahMarkah"]) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

      <div class="print-only">
        <?php foreach ($kelasList as $kod => $s) render_slip($s, $kod, true); ?>
      </div>
    <?php endif; ?>

  <?php else: ?>

    <section class="card">
      <h2>Halaman tidak dijumpai</h2>
      <p class="empty">Sila kembali ke dashboard.</p>
    </section>

  <?php endif; ?>

  <div class="footer no-print">MY SMART KOKU · Sistem Bersepadu Kokurikulum · KTE Tunku Abdul Rahman Putra</div>
</div>

<button class="float-top no-print" onclick="window.scrollTo({top:0,behavior:'smooth'})">↑</button>

</body>
</html>
