<?php
/*
  MY SMART KOKU V5 - Premium KPM / Universiti Style
  Simpan sebagai index.php

  Fungsi:
  - Dashboard premium dengan carta ringkas
  - Carian kod koko atau nama pelajar
  - Paparan details rasmi:
      Maklumat Pelajar
      Bahagian A: Kehadiran
      Bahagian B: Jawatan Tertinggi
      Bahagian C: Projek Khas
      Keputusan Markah Kokurikulum
  - Cetak slip individu 2 muka surat
  - Cetak slip kelas 2 muka surat setiap pelajar
  - Bahagian C pasti bermula di muka surat kedua
*/

/* =========================
   SETTINGS
========================= */

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

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

$CSV_PROJEK_KHAS = "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";

/*
  CSV baharu bila sudah ada nanti.
  Biarkan kosong sekarang. Sistem tetap jalan.
  Format:
  KOD KOKO,KATEGORI,JAWATAN,MARKAH
*/
$CSV_JAWATAN_TERTINGGI = "";

/* =========================
   HELPERS
========================= */

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 upper_clean($text){
  return strtoupper(clean_text($text));
}

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

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

function fetch_csv_rows($url){
  if (clean_text($url) === "") return ["headers" => [], "rows" => []];

  $context = stream_context_create([
    "http" => [
      "method" => "GET",
      "timeout" => 25,
      "header" => "User-Agent: MY-SMART-KOKU-V5\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-V5"
    ]);
    $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($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_col($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_key($text){
  $u = upper_clean($text);
  if ($u === "KPA" || has_text($u, "PERSATUAN") || has_text($u, "AKADEMIK")) return "KPA";
  if ($u === "KSP" || has_text($u, "SUKAN") || has_text($u, "PERMAINAN")) return "KSP";
  if ($u === "PBB" || has_text($u, "BADAN") || has_text($u, "BERUNIFORM")) return "PBB";
  return "LAIN";
}

function kategori_label($key){
  if ($key === "KPA") return "Kelab Persatuan / Akademik";
  if ($key === "KSP") return "Kelab Sukan dan Permainan";
  if ($key === "PBB") return "Persatuan Badan Beruniform";
  return "Lain-lain";
}

function kategori_order($key){
  $order = ["KPA" => 1, "KSP" => 2, "PBB" => 3, "LAIN" => 4];
  return $order[$key] ?? 9;
}

function kategori_class($key){
  if ($key === "KPA") return "kpa";
  if ($key === "KSP") return "ksp";
  if ($key === "PBB") return "pbb";
  return "other";
}

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

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 sort_kod($a, $b){
  preg_match('/^([A-Z]+)(\d+)/i', $a, $ma);
  preg_match('/^([A-Z]+)(\d+)/i', $b, $mb);

  $pa = strtoupper($ma[1] ?? $a);
  $pb = strtoupper($mb[1] ?? $b);
  $order = ["L" => 1, "P" => 2];

  $oa = $order[$pa] ?? 9;
  $ob = $order[$pb] ?? 9;

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

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

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

function percent($value, $total){
  if ($total <= 0) return 0;
  return round(($value / $total) * 100, 1);
}

function init_student($kod = ""){
  return [
    "nama" => "",
    "kelas" => "",
    "kod" => $kod,
    "kp" => "",
    "jantina" => "",
    "a" => [
      "KPA" => ["komponen" => "Kelab Persatuan / Akademik", "unit" => "-", "kehadiran" => 0],
      "KSP" => ["komponen" => "Kelab Sukan dan Permainan", "unit" => "-", "kehadiran" => 0],
      "PBB" => ["komponen" => "Persatuan Badan Beruniform", "unit" => "-", "kehadiran" => 0],
    ],
    "b" => [],
    "c" => []
  ];
}

function sort_projects(&$projects){
  usort($projects, function($a, $b){
    $oa = kategori_order($a["key"]);
    $ob = kategori_order($b["key"]);
    if ($oa !== $ob) return $oa - $ob;
    return strcmp($a["nama"], $b["nama"]);
  });
}

function jumlah_a($s){
  return intval($s["a"]["KPA"]["kehadiran"] ?? 0) + intval($s["a"]["KSP"]["kehadiran"] ?? 0) + intval($s["a"]["PBB"]["kehadiran"] ?? 0);
}

function jumlah_b($s){
  $sum = 0;
  foreach ($s["b"] as $r) $sum += intval($r["markah"]);
  return $sum;
}

function jumlah_c($s){
  $sum = 0;
  foreach ($s["c"] as $r) $sum += intval($r["markah"]);
  return $sum;
}

function jumlah_akhir($s){
  return jumlah_a($s) + jumlah_b($s) + jumlah_c($s);
}

function status_projek($s){
  return count($s["c"]) > 0 ? "MENDAFTAR PROJEK KHAS" : "BELUM MENDAFTAR";
}

/* =========================
   LOAD DATA
========================= */

$students = [];
$errorLoad = false;

/* Bahagian A - Kehadiran */
foreach ($CSV_KEHADIRAN as $type => $cfg) {
  $csv = fetch_csv_rows($cfg["url"]);
  if (!$csv["headers"] || !$csv["rows"]) {
    $errorLoad = true;
    continue;
  }

  $headers = $csv["headers"];
  $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 ($csv["rows"] as $row) {
    $nama = $namaKey ? clean_text($row[$namaKey] ?? "") : "";
    $kelas = $kelasKey ? clean_text($row[$kelasKey] ?? "") : "";
    $kod = $kodKey ? norm($row[$kodKey] ?? "") : "";
    $unit = $unitKey ? clean_text($row[$unitKey] ?? "") : $cfg["komponen"];

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

    if (!isset($students[$key])) $students[$key] = init_student($kod);

    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;

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

    $students[$key]["a"][$type]["unit"] = $unit ?: $cfg["komponen"];
    $students[$key]["a"][$type]["kehadiran"] += $count;
  }
}

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

  if (!isset($students[$kod])) $students[$kod] = init_student($kod);

  $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"]);
}

/* Bahagian B - CSV khas jika ada */
$csvJawatan = fetch_csv_rows($CSV_JAWATAN_TERTINGGI);
foreach ($csvJawatan["rows"] as $row) {
  $kod = norm(getv($row, ["KOD KOKO", "KOD"]));
  if ($kod === "") continue;
  if (!isset($students[$kod])) $students[$kod] = init_student($kod);

  $key = kategori_key(getv($row, ["KATEGORI", "KOMPONEN"]));

  $students[$kod]["b"][] = [
    "key" => $key,
    "komponen" => kategori_label($key),
    "jawatan" => getv($row, ["JAWATAN"], "-"),
    "markah" => intval(getv($row, ["MARKAH"], 0))
  ];
}

/* Bahagian C - Projek khas */
$csvProjek = fetch_csv_rows($CSV_PROJEK_KHAS);
if (!$csvProjek["headers"]) $errorLoad = true;

foreach ($csvProjek["rows"] as $row) {
  $unit = getv($row, ["UNIT KOKURIKULUM"]);
  $key = kategori_key($unit);
  $program = getv($row, ["NAMA PROGRAM"]);
  $tarikh = getv($row, ["TARIKH PROGRAM"]);
  $peringkat = getv($row, ["PERINGKAT PENGLIBATAN"]);

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

  foreach (jawatan_fields() as $jawatan) {
    $kod = norm(getv($row, ["KOD KOKO - " . $jawatan]));
    if ($kod === "") continue;

    if (!isset($students[$kod])) $students[$kod] = init_student($kod);

    $namaField = "NAMA " . $jawatan;
    $kelasField = "KELAS - " . $jawatan;

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

    $students[$kod]["c"][] = [
      "key" => $key,
      "komponen" => kategori_label($key),
      "nama" => $program,
      "tarikh" => $tarikh,
      "peringkat" => $peringkat,
      "jawatan" => $jawatan,
      "markah" => markah_jawatan($jawatan)
    ];
  }
}

foreach ($students as $kod => $s) {
  sort_projects($students[$kod]["c"]);
}

/* =========================
   SUMMARY & ROUTING
========================= */

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

$totalPelajar = count($allKod);
$totalKPA = $totalKSP = $totalPBB = 0;
$totalA = $totalB = $totalC = 0;
$totalRekodProjek = 0;
$totalMendaftar = $totalBelum = 0;
$kelasCount = [];

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

  $totalKPA += intval($s["a"]["KPA"]["kehadiran"] ?? 0);
  $totalKSP += intval($s["a"]["KSP"]["kehadiran"] ?? 0);
  $totalPBB += intval($s["a"]["PBB"]["kehadiran"] ?? 0);

  $totalA += jumlah_a($s);
  $totalB += jumlah_b($s);
  $totalC += jumlah_c($s);
  $totalRekodProjek += count($s["c"]);

  if (count($s["c"]) > 0) $totalMendaftar++;
  else $totalBelum++;

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

ksort($kelasCount);
$kelasOptions = array_keys($kelasCount);

$page = $_GET["page"] ?? "dashboard";
$q = clean_text($_GET["q"] ?? "");
$qNorm = norm($q);
$kodDirect = norm($_GET["kod"] ?? "");
$kelasCari = upper_clean($_GET["kelas"] ?? "");

$searchResults = [];
$selectedKod = "";

if ($kodDirect !== "" && isset($students[$kodDirect])) {
  $selectedKod = $kodDirect;
}

if ($q !== "") {
  foreach ($allKod as $kod) {
    $s = $students[$kod];

    if (
      strpos(norm($kod), $qNorm) !== false ||
      strpos(norm($s["nama"]), $qNorm) !== false ||
      strpos(norm($s["kelas"]), $qNorm) !== false
    ) {
      $searchResults[$kod] = $s;
    }
  }

  if (count($searchResults) === 1) {
    $keys = array_keys($searchResults);
    $selectedKod = $keys[0];
  }
}

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

$hadirTotal = max(1, $totalKPA + $totalKSP + $totalPBB);
$pKPA = percent($totalKPA, $hadirTotal);
$pKSP = percent($totalKSP, $hadirTotal);
$pPBB = percent($totalPBB, $hadirTotal);

$projekTotal = max(1, $totalMendaftar + $totalBelum);
$pMen = percent($totalMendaftar, $projekTotal);
$pBelum = percent($totalBelum, $projekTotal);

/* =========================
   RENDER PARTIALS
========================= */

function render_bahagian_a($s, $print = false){
  $class = $print ? "slip-table" : "";
  echo '<table class="'.$class.'">';
  echo '<thead><tr><th>Komponen</th><th>Nama Kelab / Unit</th><th>Kehadiran</th></tr></thead><tbody>';
  foreach (["KPA","KSP","PBB"] as $k) {
    $a = $s["a"][$k];
    echo '<tr>';
    echo '<td><span class="badge '.e(kategori_class($k)).'">'.e($a["komponen"]).'</span></td>';
    echo '<td>'.e($a["unit"]).'</td>';
    echo '<td class="total">'.e($a["kehadiran"]).'</td>';
    echo '</tr>';
  }
  echo '</tbody></table>';
}

function render_bahagian_b($s, $print = false){
  if (!count($s["b"])) {
    echo '<p class="empty">Belum ada data jawatan tertinggi.</p>';
    return;
  }

  $class = $print ? "slip-table" : "";
  echo '<table class="'.$class.'">';
  echo '<thead><tr><th>Komponen</th><th>Jawatan</th><th>Markah</th></tr></thead><tbody>';
  foreach ($s["b"] as $b) {
    echo '<tr>';
    echo '<td><span class="badge '.e(kategori_class($b["key"])).'">'.e($b["komponen"]).'</span></td>';
    echo '<td>'.e($b["jawatan"]).'</td>';
    echo '<td class="total">'.e($b["markah"]).'</td>';
    echo '</tr>';
  }
  echo '</tbody></table>';
}

function render_bahagian_c($s, $print = false){
  if (!count($s["c"])) {
    echo '<p class="empty">Tiada rekod projek khas.</p>';
    return;
  }

  $class = $print ? "slip-table c-table" : "c-table";
  echo '<table class="'.$class.'">';
  echo '<thead><tr><th class="col-bil">Bil</th><th class="col-date">Tarikh</th><th class="col-cat">Kategori</th><th>Aktiviti</th><th class="col-role">Jawatan</th><th class="col-mark">Markah</th></tr></thead><tbody>';
  $bil = 1;
  foreach ($s["c"] as $c) {
    echo '<tr>';
    echo '<td class="col-bil">'.e($bil++).'</td>';
    echo '<td class="col-date">'.e($c["tarikh"] ?: "-").'</td>';
    echo '<td class="col-cat"><span class="badge '.e(kategori_class($c["key"])).'">'.e($c["komponen"]).'</span></td>';
    echo '<td class="activity-cell">'.e($c["nama"]).'<small>'.e($c["peringkat"] ?: "").'</small></td>';
    echo '<td class="col-role">'.e($c["jawatan"]).'</td>';
    echo '<td class="col-mark total">'.e($c["markah"]).'</td>';
    echo '</tr>';
  }
  echo '</tbody></table>';
}

function render_result_grid($s){
  echo '<div class="result-grid">';
  echo '<div class="result-box"><span>Bahagian A</span><b>'.e(jumlah_a($s)).'</b></div>';
  echo '<div class="result-box"><span>Bahagian B</span><b>'.e(jumlah_b($s)).'</b></div>';
  echo '<div class="result-box"><span>Bahagian C</span><b>'.e(jumlah_c($s)).'</b></div>';
  echo '<div class="result-box accent"><span>Jumlah</span><b>'.e(jumlah_akhir($s)).'</b></div>';
  echo '</div>';
}

function render_slip_2_pages($s, $kod, $logo){
  echo '<section class="slip-rasmi">';
  echo '<div class="rasmi-head">';
  echo '<img src="'.e($logo).'" alt="Logo">';
  echo '<div>';
  echo '<h1>SLIP MARKAH KOKURIKULUM PELAJAR</h1>';
  echo '<p>Kolej Tingkatan Enam (Prauniversiti) Tunku Abdul Rahman Putra</p>';
  echo '</div>';
  echo '</div>';

  echo '<table class="rasmi-info">';
  echo '<tr><td>Nama</td><td>: '.e($s["nama"] ?: "-").'</td><td>Kelas</td><td>: '.e($s["kelas"] ?: "-").'</td></tr>';
  echo '<tr><td>Kod Koku</td><td>: '.e($s["kod"] ?: $kod).'</td><td>Jumlah Markah</td><td>: <b>'.e(jumlah_akhir($s)).'</b></td></tr>';
  echo '</table>';

  echo '<h2>BAHAGIAN A : KEHADIRAN</h2>';
  echo '<table class="rasmi-table">';
  echo '<thead><tr><th class="bil">Bil</th><th>Perkara</th><th class="catatan">Catatan</th><th class="markah">Markah</th></tr></thead>';
  echo '<tbody>';
  $bil = 1;
  foreach (["KPA","KSP","PBB"] as $k) {
    $a = $s["a"][$k];
    echo '<tr>';
    echo '<td class="bil">'.e($bil++).'.</td>';
    echo '<td>'.e($a["komponen"]).'<br><small>'.e($a["unit"]).'</small></td>';
    echo '<td class="catatan">Kehadiran</td>';
    echo '<td class="markah">'.e($a["kehadiran"]).'</td>';
    echo '</tr>';
  }
  echo '</tbody></table>';

  echo '<h2>BAHAGIAN B : JAWATAN TERTINGGI</h2>';
  echo '<table class="rasmi-table">';
  echo '<thead><tr><th class="bil">Bil</th><th>Perkara</th><th class="catatan">Jawatan</th><th class="markah">Markah</th></tr></thead>';
  echo '<tbody>';
  if (!count($s["b"])) {
    $komponen = ["KPA","KSP","PBB"];
    for ($i=0; $i<3; $i++) {
      echo '<tr><td class="bil">'.($i+1).'.</td><td>'.e(kategori_label($komponen[$i])).'</td><td class="catatan">-</td><td class="markah">0</td></tr>';
    }
  } else {
    $bil = 1;
    foreach ($s["b"] as $b) {
      echo '<tr>';
      echo '<td class="bil">'.e($bil++).'.</td>';
      echo '<td>'.e($b["komponen"]).'</td>';
      echo '<td class="catatan">'.e($b["jawatan"]).'</td>';
      echo '<td class="markah">'.e($b["markah"]).'</td>';
      echo '</tr>';
    }
  }
  echo '</tbody></table>';

  echo '<h2>BAHAGIAN C : PROJEK KHAS</h2>';
  echo '<table class="rasmi-table projek-rasmi">';
  echo '<thead><tr><th class="bil">Bil</th><th>Aktiviti / Program</th><th class="catatan">Jawatan</th><th class="markah">Markah</th></tr></thead>';
  echo '<tbody>';
  if (!count($s["c"])) {
    echo '<tr><td class="bil">1.</td><td>Tiada rekod projek khas.</td><td class="catatan">-</td><td class="markah">0</td></tr>';
  } else {
    $bil = 1;
    foreach ($s["c"] as $c) {
      $peringkat = clean_text($c["peringkat"] ?? "");
      echo '<tr>';
      echo '<td class="bil">'.e($bil++).'.</td>';
      echo '<td>'.e($c["nama"]);
      if ($peringkat !== "") echo ' <em>('.e($peringkat).')</em>';
      echo '<br><small>'.e($c["tarikh"] ?: "-").'</small></td>';
      echo '<td class="catatan">'.e($c["jawatan"]).'</td>';
      echo '<td class="markah">'.e($c["markah"]).'</td>';
      echo '</tr>';
    }
  }
  echo '</tbody></table>';

  echo '<table class="rasmi-total">';
  echo '<tr>';
  echo '<td>Bahagian A : <b>'.e(jumlah_a($s)).'</b></td>';
  echo '<td>Bahagian B : <b>'.e(jumlah_b($s)).'</b></td>';
  echo '<td>Bahagian C : <b>'.e(jumlah_c($s)).'</b></td>';
  echo '<td>Jumlah Markah Kokurikulum : <b>'.e(jumlah_akhir($s)).'</b></td>';
  echo '</tr>';
  echo '</table>';

  echo '<div class="rasmi-note">Slip ini dijana melalui sistem MY SMART KOKU berdasarkan data yang diterbitkan.</div>';
  echo '</section>';
}
?>
<!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 V5</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:#f6f8fc;
  --card:#fff;
  --text:#101828;
  --muted:#667085;
  --line:#e4eaf2;
  --blue:#2563eb;
  --green:#16a34a;
  --orange:#f59e0b;
  --red:#dc2626;
  --purple:#7c3aed;
  --blueSoft:#eff6ff;
  --greenSoft:#ecfdf5;
  --orangeSoft:#fff7ed;
  --redSoft:#fff1f2;
  --purpleSoft:#f5f3ff;
  --shadow:0 18px 48px rgba(16,24,40,.075);
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{
  margin:0;
  font-family:Poppins,Arial,sans-serif;
  background:linear-gradient(180deg,#f9fbff,#f3f6fb);
  color:var(--text);
}
a{text-decoration:none;color:inherit}
.wrap{width:min(1180px,94%);margin:0 auto;padding:18px 0 46px}
.header{
  background:rgba(255,255,255,.97);
  border:1px solid var(--line);
  border-radius:28px;
  padding:18px 20px;
  box-shadow:var(--shadow);
  margin-bottom:16px;
}
.top{display:flex;justify-content:space-between;gap:20px;align-items:center}
.brand{display:flex;align-items:center;gap:13px}
.brand img{width:48px;height:48px;object-fit:contain}
.brand small{display:block;color:var(--blue);font-size:11px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;margin-bottom:3px}
.brand h1{margin:0;font-size:30px;line-height:1;letter-spacing:-.045em}
.menu{display:flex;align-items:center;gap:2px;border-bottom:1px solid var(--line)}
.menu a,.drop-btn{
  border:0;background:transparent;color:#344054;font:500 13px Poppins,Arial;
  padding:14px 13px 13px;border-bottom:2px solid transparent;cursor:pointer
}
.menu a.active,.menu a:hover,.drop:hover .drop-btn{color:var(--blue);border-bottom-color:var(--blue)}
.drop{position:relative}
.drop-menu{
  display:none;position:absolute;right:0;top:46px;min-width:240px;background:#fff;border:1px solid var(--line);
  border-radius:16px;padding:8px;box-shadow:0 18px 45px rgba(16,24,40,.14);z-index:30
}
.drop:hover .drop-menu{display:block}
.drop-menu a{display:block;border:0;border-radius:12px;padding:10px 12px}
.drop-menu a:hover{background:#f8fafc}
.search-panel{margin-top:16px;border:1px solid var(--line);border-radius:22px;padding:10px;background:#f8fbff}
.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:14px 16px;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:14px 18px;background:var(--blue);color:#fff;font-size:14px;font-weight:500;
  cursor:pointer;display:inline-flex;align-items:center;justify-content:center;white-space:nowrap
}
.btn.light,button.light{background:#fff;color:var(--text);border:1px solid var(--line)}
.btn.small,button.small{padding:9px 12px;border-radius:12px;font-size:12px}
.alert{background:#fff;color:#991b1b;border:1px solid #fecaca;border-radius:16px;padding:13px;font-size:14px;margin-bottom:16px}
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px}
.card,.panel,.stat{
  background:#fff;border:1px solid var(--line);box-shadow:0 12px 32px rgba(16,24,40,.045)
}
.panel,.card{border-radius:24px;padding:18px}
.card{margin-bottom:16px}
.section-head{display:flex;justify-content:space-between;gap:14px;align-items:flex-start;margin-bottom:14px}
h2{margin:0;font-size:20px;font-weight:600;letter-spacing:-.02em}
p{margin:5px 0 0;color:var(--muted);font-size:13px;line-height:1.65}
.chart-row{display:grid;grid-template-columns:145px 1fr;gap:18px;align-items:center}
.donut{width:138px;height:138px;border-radius:50%;position:relative}
.donut:after{content:"";position:absolute;inset:35px;background:#fff;border-radius:50%;border:1px solid #edf2f7}
.legend{display:grid;gap:10px}
.legend-row{display:grid;grid-template-columns:auto 1fr auto;gap:9px;align-items:center;font-size:13px}
.dot{width:9px;height:9px;border-radius:50%}
.line{height:7px;background:#eef2f7;border-radius:999px;overflow:hidden}
.fill{height:100%;border-radius:999px}
.blue{background:var(--blue)}.green{background:var(--green)}.orange{background:var(--orange)}.red{background:var(--red)}
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px}
.stat{border-radius:22px;padding:17px}
.stat span{display:block;color:var(--muted);font-size:12px}
.stat b{display:block;font-size:30px;line-height:1.1;color:var(--blue);margin-top:8px;font-weight:700;letter-spacing:-.04em}
.info-list{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
.info{border:1px solid var(--line);border-radius:16px;padding:12px}
.info span{display:block;color:var(--muted);font-size:12px;margin-bottom:4px}
.info b{font-size:14px;font-weight:500}
.result-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
.result-box{border:1px solid var(--line);border-radius:18px;padding:14px;background:#fff}
.result-box.accent{background:linear-gradient(135deg,#eff6ff,#fff);border-color:#bfdbfe}
.result-box span{display:block;color:var(--muted);font-size:12px}
.result-box b{display:block;color:var(--blue);font-size:28px;font-weight:700;margin-top:5px}
.final-box{border-radius:20px;background:linear-gradient(135deg,#eff6ff,#fff);border:1px solid #bfdbfe;padding:18px;margin-top:10px}
.final-box span{display:block;color:#1d4ed8;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.08em}
.final-box b{display:block;color:var(--blue);font-size:42px;letter-spacing:-.05em;line-height:1.05;margin-top:5px}
.table-wrap{overflow:auto;border:1px solid var(--line);border-radius:18px}
table{width:100%;border-collapse:collapse;min-width:860px}
th,td{border-bottom:1px solid var(--line);padding:12px 13px;text-align:left;vertical-align:top;font-size:13px}
th{background:#fbfcfe;color:#475467;font-weight:500}
tr:last-child td{border-bottom:0}
.badge{display:inline-block;padding:5px 9px;border-radius:999px;font-size:12px;font-weight:500}
.badge.kpa{background:var(--purpleSoft);color:#6d28d9}
.badge.ksp{background:var(--blueSoft);color:#1d4ed8}
.badge.pbb{background:var(--orangeSoft);color:#c2410c}
.badge.other{background:#f1f5f9;color:#475569}
.badge.green{background:var(--greenSoft);color:#15803d}
.badge.red{background:var(--redSoft);color:#be123c}
.total{color:var(--blue);font-weight:700}
.empty{color:var(--muted);font-size:14px;margin:0}
.kod-grid{display:flex;flex-wrap:wrap;gap:8px}
.kod-grid a{border:1px solid var(--line);border-radius:13px;padding:8px 10px;min-width:54px;text-align:center;color:var(--blue);background:#fff;font-size:14px}
.kod-grid a:hover{border-color:rgba(37,99,235,.45);background:#f8fbff}
.footer{text-align:center;color:var(--muted);font-size:12px;margin-top:18px}
.float-top{position:fixed;right:16px;bottom:16px;z-index:30;border-radius:999px;width:48px;height:48px;box-shadow:0 12px 30px rgba(37,99,235,.25)}
.print-only{display:none}


.stats-3{grid-template-columns:repeat(3,1fr)}
.c-table{min-width:980px;table-layout:fixed}
.c-table .col-bil{width:58px;text-align:center}
.c-table .col-date{width:120px;white-space:nowrap}
.c-table .col-cat{width:210px}
.c-table .col-role{width:150px}
.c-table .col-mark{width:90px;text-align:center}
.c-table .activity-cell{word-break:normal;white-space:normal;line-height:1.45}
.c-table .activity-cell small{margin-top:3px}

/* PRINT SLIP */
.slip-page{background:#fff;color:#111827;min-height:270mm;page-break-after:always;break-after:page}
.slip-page:last-child{page-break-after:auto;break-after:auto}
.slip-head{display:flex;justify-content:space-between;gap:14px;border-bottom:2px solid #e5e7eb;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-page h1{margin:2px 0;font-size:23px;letter-spacing:-.03em}
.slip-page p{margin:0;color:#5b6678;font-size:12px}
.slip-kod{min-width:90px;height:54px;border-radius:16px;background:var(--blueSoft);color:var(--blue);display:flex;align-items:center;justify-content:center;font-size:22px;font-weight:700}
.slip-info{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:14px}
.slip-info div,.slip-result div{border:1px solid #e5e7eb;border-radius:12px;padding:9px}
.slip-info span,.slip-result span{display:block;color:#667085;font-size:10px;margin-bottom:3px}
.slip-info b,.slip-result b{font-size:12px;font-weight:600}
.slip-page h3{font-size:15px;margin:13px 0 7px}
.slip-table{width:100%;min-width:0;border:1px solid #e5e7eb;border-radius:12px;overflow:hidden}
.slip-table th,.slip-table td{font-size:11px;padding:7px 8px}
.slip-table th{background:#f8fafc}
.slip-table small{font-size:10px}
.slip-result{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-top:12px}
.slip-final{border:1px solid #bfdbfe;background:#eff6ff;border-radius:14px;padding:12px;margin-top:10px}
.slip-final span{font-size:10px;color:#1d4ed8;letter-spacing:.08em;text-transform:uppercase;font-weight:700}
.slip-final b{display:block;font-size:30px;color:var(--blue);line-height:1.05;margin-top:3px}
.slip-note{margin-top:12px;font-size:10px;color:#667085;border-top:1px solid #e5e7eb;padding-top:8px}


.slip-table.c-table{table-layout:fixed;min-width:0}
.slip-table.c-table .col-bil{width:38px}
.slip-table.c-table .col-date{width:78px}
.slip-table.c-table .col-cat{width:145px}
.slip-table.c-table .col-role{width:85px}
.slip-table.c-table .col-mark{width:52px}

@media(max-width:900px){
  .wrap{width:94%;padding-top:12px}
  .header{border-radius:22px;padding:15px}
  .top{display:block}
  .menu{margin-top:14px;justify-content:flex-start;overflow-x:auto}
  .drop-menu{left:0;right:auto}
  .search-row,.grid-2,.chart-row{grid-template-columns:1fr}
  button,.btn{width:100%}
  .stats,.stats-3,.info-list,.result-grid{grid-template-columns:1fr}
  .section-head{display:block}
  .donut{margin:auto}
  .brand h1{font-size:25px}
}

@media print{
  @page{size:A4 portrait;margin:10mm}
  body{background:#fff}
  .no-print,.header,.footer,.float-top,.screen-only{display:none!important}
  .print-only{display:block!important}
  .wrap{width:100%;padding:0}
  .card,.panel,.stat{box-shadow:none!important}
  .slip-page{min-height:270mm;page-break-after:always;break-after:page}
  .slip-page:last-child{page-break-after:auto;break-after:auto}
}

/* SLIP RASMI 1 MUKA SURAT - FINAL */
.slip-rasmi{display:none}

@media print{
  @page{size:A4 portrait;margin:8mm}
  html,body{
    background:#fff!important;
    color:#000!important;
  }
  .no-print,.header,.footer,.float-top,.screen-only{
    display:none!important;
  }
  .print-only{
    display:block!important;
  }
  .wrap{
    width:100%!important;
    padding:0!important;
    margin:0!important;
  }

  .slip-page{
    display:none!important;
  }

  .slip-rasmi{
    display:block!important;
    width:100%;
    page-break-after:always;
    break-after:page;
    font-family:Arial, sans-serif!important;
    color:#000!important;
    font-size:9px;
  }
  .slip-rasmi:last-child{
    page-break-after:auto;
    break-after:auto;
  }

  .rasmi-head{
    display:flex;
    align-items:center;
    gap:9px;
    border-bottom:1px solid #111;
    padding-bottom:5px;
    margin-bottom:6px;
  }
  .rasmi-head img{
    width:34px;
    height:34px;
    object-fit:contain;
  }
  .rasmi-head h1{
    margin:0;
    font-size:13px;
    line-height:1.1;
    font-weight:700;
    letter-spacing:.1px;
  }
  .rasmi-head p{
    margin:1px 0 0;
    color:#000!important;
    font-size:9px;
  }

  .rasmi-info{
    width:100%;
    border-collapse:collapse;
    margin-bottom:6px;
    font-size:9.5px;
  }
  .rasmi-info td{
    border:0!important;
    padding:1.5px 3px!important;
    vertical-align:top;
    color:#000!important;
  }
  .rasmi-info td:nth-child(1),
  .rasmi-info td:nth-child(3){
    width:78px;
    font-weight:700;
  }

  .slip-rasmi h2{
    margin:7px 0 3px;
    font-size:10.5px;
    line-height:1.1;
    font-weight:700;
    letter-spacing:.2px;
  }

  .rasmi-table{
    width:100%;
    border-collapse:collapse;
    table-layout:fixed;
    margin-bottom:6px;
    font-size:8.7px;
  }
  .rasmi-table th,
  .rasmi-table td{
    border-top:1px solid #111!important;
    border-bottom:1px solid #111!important;
    border-left:0!important;
    border-right:0!important;
    padding:2.7px 4px!important;
    vertical-align:top;
    line-height:1.16;
    color:#000!important;
    background:#fff!important;
    word-break:normal!important;
    overflow-wrap:break-word!important;
  }
  .rasmi-table th{
    font-size:8.6px;
    font-weight:700;
    text-transform:uppercase;
    text-align:left;
  }
  .rasmi-table small{
    display:block;
    margin-top:1px;
    color:#000!important;
    font-size:7.4px;
    line-height:1.08;
  }
  .rasmi-table em{
    font-style:normal;
    font-size:7.7px;
    color:#000;
  }

  .rasmi-table .bil{
    width:28px;
    text-align:left;
  }
  .rasmi-table .catatan{
    width:92px;
  }
  .rasmi-table .markah{
    width:43px;
    text-align:center;
  }

  .projek-rasmi{
    font-size:8.15px;
    margin-bottom:5px;
  }
  .projek-rasmi th,
  .projek-rasmi td{
    padding:2.2px 4px!important;
    line-height:1.1;
  }
  .projek-rasmi .bil{
    width:28px;
  }
  .projek-rasmi .catatan{
    width:85px;
  }
  .projek-rasmi .markah{
    width:40px;
  }

  .rasmi-total{
    width:100%;
    border-collapse:collapse;
    margin-top:6px;
    font-size:9px;
  }
  .rasmi-total td{
    border-top:1px solid #111!important;
    border-bottom:1px solid #111!important;
    border-left:0!important;
    border-right:0!important;
    padding:4px 5px!important;
    text-align:center;
    color:#000!important;
    line-height:1.15;
  }
  .rasmi-total b{
    font-size:10.5px;
  }

  .rasmi-note{
    margin-top:4px;
    border-top:1px solid #999;
    padding-top:3px;
    font-size:7.5px;
    color:#000!important;
  }
}

</style>
</head>
<body>

<div class="wrap">

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

      <nav class="menu">
        <a class="<?= $page === "dashboard" ? "active" : "" ?>" href="?page=dashboard">Dashboard</a>

        <div class="drop">
          <button type="button" class="drop-btn">Projek Khas</button>
          <div class="drop-menu">
            <a href="?page=mendaftar">Mendaftar Projek Khas</a>
            <a href="?page=belum">Belum Mendaftar</a>
          </div>
        </div>

        <div class="drop">
          <button type="button" class="drop-btn">Cetakan</button>
          <div class="drop-menu">
            <a href="?page=kelas">Slip Mengikut Kelas</a>
            <a href="javascript:window.print()">Cetak 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">
        <input type="text" name="q" placeholder="Cari kod koko atau nama pelajar..." value="<?= e($q) ?>">
        <button type="submit">Cari</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 === "dashboard"): ?>

    <div class="grid-2">
      <section class="panel">
        <div class="section-head">
          <div>
            <h2>Ringkasan Kehadiran</h2>
            <p>Kehadiran mengikut komponen kokurikulum.</p>
          </div>
        </div>

        <div class="chart-row">
          <div class="donut" style="background:conic-gradient(var(--blue) 0 <?= e($pKPA) ?>%, var(--green) <?= e($pKPA) ?>% <?= e($pKPA + $pKSP) ?>%, var(--orange) <?= e($pKPA + $pKSP) ?>% 100%);"></div>
          <div class="legend">
            <div class="legend-row"><span class="dot blue"></span><div class="line"><div class="fill blue" style="width:<?= e($pKPA) ?>%"></div></div><b><?= e($totalKPA) ?></b></div>
            <div class="legend-row"><span class="dot green"></span><div class="line"><div class="fill green" style="width:<?= e($pKSP) ?>%"></div></div><b><?= e($totalKSP) ?></b></div>
            <div class="legend-row"><span class="dot orange"></span><div class="line"><div class="fill orange" style="width:<?= e($pPBB) ?>%"></div></div><b><?= e($totalPBB) ?></b></div>
            <p>Biru KPA · Hijau KSP · Oren PBB</p>
          </div>
        </div>
      </section>

      <section class="panel">
        <div class="section-head">
          <div>
            <h2>Status Projek Khas</h2>
            <p>Perbandingan status pendaftaran projek khas.</p>
          </div>
        </div>

        <div class="chart-row">
          <div class="donut" style="background:conic-gradient(var(--green) 0 <?= e($pMen) ?>%, var(--red) <?= e($pMen) ?>% 100%);"></div>
          <div class="legend">
            <div class="legend-row"><span class="dot green"></span><div class="line"><div class="fill green" style="width:<?= e($pMen) ?>%"></div></div><b><?= e($totalMendaftar) ?></b></div>
            <div class="legend-row"><span class="dot red"></span><div class="line"><div class="fill red" style="width:<?= e($pBelum) ?>%"></div></div><b><?= e($totalBelum) ?></b></div>
            <p>Hijau mendaftar · Merah belum mendaftar</p>
          </div>
        </div>
      </section>
    </div>

    <div class="stats stats-3">
      <div class="stat"><span>Rekod Pelajar</span><b><?= e($totalPelajar) ?></b></div>
      <div class="stat"><span>Rekod Kehadiran</span><b><?= e($totalA) ?></b></div>
      <div class="stat"><span>Bilangan Projek Khas</span><b><?= e($totalRekodProjek) ?></b></div>
    </div>

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

    <?php if ($q === "" && !$selected): ?>
      <section class="card">
        <h2>Carian Pelajar</h2>
        <p>Masukkan kod koko atau nama pelajar di ruangan carian atas.</p>
      </section>

    <?php elseif ($selected): ?>

      <div class="screen-only">
        <section class="card">
          <div class="section-head">
            <div>
              <h2>Maklumat Peribadi Pelajar</h2>
              <p>Format paparan rasmi kokurikulum.</p>
            </div>
            <button class="btn small light" type="button" onclick="window.print()">Print Slip A4</button>
          </div>

          <div class="info-list">
            <div class="info"><span>Nama</span><b><?= e($selected["nama"] ?: "-") ?></b></div>
            <div class="info"><span>Kelas</span><b><?= e($selected["kelas"] ?: "-") ?></b></div>
            <div class="info"><span>Kod Koku</span><b><?= e($selected["kod"] ?: $selectedKod) ?></b></div>
          </div>
        </section>

        <section class="card">
          <div class="section-head">
            <div>
              <h2>Bahagian A : Kehadiran</h2>
              <p>Kehadiran mengikut tiga komponen kokurikulum.</p>
            </div>
          </div>
          <div class="table-wrap"><?php render_bahagian_a($selected); ?></div>
        </section>

        <section class="card">
          <div class="section-head">
            <div>
              <h2>Bahagian B : Jawatan Tertinggi</h2>
              <p>Data akan dipaparkan apabila CSV jawatan disediakan.</p>
            </div>
          </div>
          <div class="table-wrap"><?php render_bahagian_b($selected); ?></div>
        </section>

        <section class="card">
          <div class="section-head">
            <div>
              <h2>Bahagian C : Projek Khas</h2>
              <p>Bahagian ini akan bermula di muka surat kedua semasa cetakan.</p>
            </div>
          </div>
          <div class="table-wrap"><?php render_bahagian_c($selected); ?></div>
        </section>

        <section class="card">
          <div class="section-head">
            <div>
              <h2>Keputusan Markah Kokurikulum</h2>
              <p>Jumlah Bahagian A, B dan C.</p>
            </div>
          </div>

          <?php render_result_grid($selected); ?>

          <div class="final-box">
            <span>Keputusan Markah Kokurikulum</span>
            <b><?= e(jumlah_akhir($selected)) ?> Markah</b>
          </div>
        </section>
      </div>

      <div class="print-only">
        <?php render_slip_2_pages($selected, $selectedKod, $LOGO_KOLEJ); ?>
      </div>

    <?php else: ?>

      <section class="card">
        <div class="section-head">
          <div>
            <h2>Keputusan Carian</h2>
            <p><?= e(count($searchResults)) ?> rekod dijumpai untuk “<?= e($q) ?>”.</p>
          </div>
        </div>

        <?php if (!count($searchResults)): ?>
          <p class="empty">Tiada rekod dijumpai.</p>
        <?php else: ?>
          <div class="table-wrap">
            <table>
              <thead><tr><th>Bil</th><th>Kod</th><th>Nama</th><th>Kelas</th><th>Status</th><th>Markah</th></tr></thead>
              <tbody>
                <?php $bil=1; foreach ($searchResults as $kod => $s): ?>
                  <tr>
                    <td><?= e($bil++) ?></td>
                    <td><a class="badge ksp" href="?page=semak&kod=<?= urlencode($kod) ?>"><?= e($s["kod"] ?: $kod) ?></a></td>
                    <td><?= e($s["nama"] ?: "-") ?></td>
                    <td><?= e($s["kelas"] ?: "-") ?></td>
                    <td><span class="badge <?= count($s["c"]) ? "green" : "red" ?>"><?= e(status_projek($s)) ?></span></td>
                    <td class="total"><?= e(jumlah_akhir($s)) ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </section>

    <?php endif; ?>

  <?php elseif ($page === "mendaftar" || $page === "belum"): ?>

    <?php
      $list = [];
      foreach ($allKod as $kod) {
        $has = count($students[$kod]["c"]) > 0;
        if ($page === "mendaftar" && $has) $list[] = $kod;
        if ($page === "belum" && !$has) $list[] = $kod;
      }
      $title = $page === "mendaftar" ? "Senarai Mendaftar Projek Khas" : "Senarai Belum Mendaftar Projek Khas";
    ?>

    <section class="card">
      <div class="section-head">
        <div>
          <h2><?= e($title) ?></h2>
          <p><?= e(count($list)) ?> kod koko. Tekan kod untuk melihat slip individu.</p>
        </div>
        <button class="btn small light" type="button" onclick="window.print()">Cetak Senarai</button>
      </div>

      <div class="kod-grid">
        <?php foreach ($list as $kod): ?>
          <a href="?page=semak&kod=<?= urlencode($kod) ?>"><?= e($kod) ?></a>
        <?php endforeach; ?>
      </div>
    </section>

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

    <section class="card no-print">
      <div class="section-head">
        <div>
          <h2>Slip Mengikut Kelas</h2>
          <p>Pilih kelas dan cetak slip. Setiap pelajar akan dicetak dua muka surat.</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>
          <button type="submit">Papar</button>
        </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) {
          if (upper_clean($students[$kod]["kelas"]) === $kelasCari) $kelasList[$kod] = $students[$kod];
        }
      ?>

      <section class="card no-print">
        <div class="section-head">
          <div>
            <h2>Kelas <?= e($kelasCari) ?></h2>
            <p><?= e(count($kelasList)) ?> pelajar.</p>
          </div>
          <button class="btn small light" type="button" 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>Status</th><th>Markah</th></tr></thead>
            <tbody>
              <?php $bil=1; foreach ($kelasList as $kod => $s): ?>
                <tr>
                  <td><?= e($bil++) ?></td>
                  <td><a class="badge ksp" href="?page=semak&kod=<?= urlencode($kod) ?>"><?= e($s["kod"] ?: $kod) ?></a></td>
                  <td><?= e($s["nama"] ?: "-") ?></td>
                  <td><span class="badge <?= count($s["c"]) ? "green" : "red" ?>"><?= e(status_projek($s)) ?></span></td>
                  <td class="total"><?= e(jumlah_akhir($s)) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </section>

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

    <?php endif; ?>

  <?php endif; ?>

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

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

</body>
</html>
