<?php
/* alumni.php — Data Alumni */

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `alumni` (
        `id`          INT NOT NULL AUTO_INCREMENT,
        `siswa_id`    INT DEFAULT NULL,
        `nis`         VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        `nama`        VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        `jurusan`     VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `tahun_lulus` VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `no_hp`       VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `alamat`      TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `foto`        VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `keterangan`  TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `tgl_lulus`   DATE DEFAULT NULL,
        `created_at`  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        UNIQUE KEY `uq_nis` (`nis`),
        KEY `idx_siswa_id`   (`siswa_id`),
        KEY `idx_tahun_lulus`(`tahun_lulus`),
        KEY `idx_jurusan`    (`jurusan`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
} catch (Exception $e) {}

try {
    $cols = $pdo->query("SHOW COLUMNS FROM alumni")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('foto',       $cols)) $pdo->exec("ALTER TABLE alumni ADD COLUMN foto VARCHAR(100) DEFAULT NULL AFTER alamat");
    if (!in_array('keterangan', $cols)) $pdo->exec("ALTER TABLE alumni ADD COLUMN keterangan TEXT DEFAULT NULL AFTER foto");
    if (!in_array('tgl_lulus',  $cols)) $pdo->exec("ALTER TABLE alumni ADD COLUMN tgl_lulus DATE DEFAULT NULL AFTER keterangan");
} catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';
    if ($act === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE alumni SET no_hp=?, alamat=?, keterangan=?, tgl_lulus=? WHERE id=?")
            ->execute([
                trim($_POST['no_hp']       ?? ''),
                trim($_POST['alamat']      ?? ''),
                trim($_POST['keterangan']  ?? '') ?: null,
                trim($_POST['tgl_lulus']   ?? '') ?: null,
                $id
            ]);
        $_SESSION['toast'] = '✅ Data alumni berhasil diperbarui';
        redirect('index.php?page=alumni');
    }
    if ($act === 'hapus') {
        $pdo->prepare("DELETE FROM alumni WHERE id=?")->execute([(int)($_POST['id'] ?? 0)]);
        $_SESSION['toast'] = '🗑️ Data alumni berhasil dihapus';
        redirect('index.php?page=alumni');
    }
    if ($act === 'ekspor_csv') {
        $rows = $pdo->query("SELECT nis,nama,jurusan,tahun_lulus,no_hp,alamat,keterangan,tgl_lulus FROM alumni ORDER BY tahun_lulus DESC, nama")->fetchAll();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="data_alumni_'.date('Ymd').'.csv"');
        header('Cache-Control: no-cache');
        $out = fopen('php://output','w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out, ['NIS','Nama','Jurusan','Tahun Lulus','No HP','Alamat','Keterangan','Tanggal Lulus']);
        foreach ($rows as $r) fputcsv($out, [$r['nis'],$r['nama'],$r['jurusan'],$r['tahun_lulus'],$r['no_hp'],$r['alamat'],$r['keterangan'],$r['tgl_lulus']]);
        fclose($out); exit;
    }
    redirect('index.php?page=alumni');
}

require_once 'layout/header.php';

$search      = trim($_GET['q']           ?? '');
$filterTahun = trim($_GET['tahun_lulus'] ?? '');
$filterJur   = trim($_GET['jurusan']     ?? '');
$page        = max(1, (int)($_GET['p']   ?? 1));
$perPage     = in_array((int)($_GET['per_page'] ?? 20), [10,20,25,50,100]) ? (int)$_GET['per_page'] : 20;

$alumni = []; $totalAlumni = 0; $totalHal = 1;
$tahunList = []; $jurusanList = []; $_tblError = false; $_tblErrMsg = '';

try {
    $tahunList   = $pdo->query("SELECT DISTINCT tahun_lulus FROM alumni WHERE tahun_lulus IS NOT NULL ORDER BY tahun_lulus DESC")->fetchAll(PDO::FETCH_COLUMN);
    $jurusanList = $pdo->query("SELECT DISTINCT jurusan FROM alumni WHERE jurusan IS NOT NULL ORDER BY jurusan")->fetchAll(PDO::FETCH_COLUMN);

    $sqlW = "FROM alumni WHERE 1=1"; $par = [];
    if ($search)      { $sqlW .= " AND (nama LIKE ? OR nis LIKE ?)"; $par[] = "%$search%"; $par[] = "%$search%"; }
    if ($filterTahun) { $sqlW .= " AND tahun_lulus=?"; $par[] = $filterTahun; }
    if ($filterJur)   { $sqlW .= " AND jurusan=?";     $par[] = $filterJur; }

    $stmtC = $pdo->prepare("SELECT COUNT(*) $sqlW");
    $stmtC->execute($par);
    $totalAlumni = (int)$stmtC->fetchColumn();
    $stmtC->closeCursor();
    $totalHal = max(1, (int)ceil($totalAlumni / $perPage));
    $page     = min($page, $totalHal);
    $offset   = ($page - 1) * $perPage;

    $stmtA = $pdo->prepare("SELECT * $sqlW ORDER BY tahun_lulus DESC, nama LIMIT ? OFFSET ?");
    // Bind WHERE params dulu (urutan 1, 2, ...)
    foreach ($par as $pi => $pv) {
        $stmtA->bindValue($pi + 1, $pv, PDO::PARAM_STR);
    }
    // Baru bind LIMIT dan OFFSET setelah WHERE params
    $stmtA->bindValue(count($par) + 1, (int)$perPage, PDO::PARAM_INT);
    $stmtA->bindValue(count($par) + 2, (int)$offset,  PDO::PARAM_INT);
    $stmtA->execute();
    $alumni = $stmtA->fetchAll(PDO::FETCH_ASSOC);
    $stmtA->closeCursor();
} catch (Exception $e) { $_tblError = true; $_tblErrMsg = $e->getMessage(); }

$statTahun = [];
try {
    $rows2 = $pdo->query("SELECT tahun_lulus, COUNT(*) as total FROM alumni WHERE tahun_lulus IS NOT NULL GROUP BY tahun_lulus ORDER BY tahun_lulus DESC")->fetchAll();
    foreach ($rows2 as $r) $statTahun[$r['tahun_lulus']] = (int)$r['total'];
} catch (Exception $e) {}
$totalSemua = array_sum($statTahun) ?: $totalAlumni;

$baseP = 'index.php?page=alumni'
       . '&q='.rawurlencode($search)
       . '&tahun_lulus='.rawurlencode($filterTahun)
       . '&jurusan='.rawurlencode($filterJur)
       . '&per_page='.$perPage;

$uploadUrl    = 'uploads/foto_siswa/';
$uploadAbs    = str_replace('\\', '/', dirname(__DIR__)).'/uploads/foto_siswa/';
$avatarColors = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];
$jurusanColors= ['IPA 1'=>'#059669','IPA 2'=>'#0D9488','IPS 1'=>'#2563EB','IPS 2'=>'#7C3AED','A-1'=>'#059669','A-2'=>'#0D9488','B-1'=>'#2563EB','B-2'=>'#7C3AED'];
$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
.alumni-hero{background:linear-gradient(135deg,#1E2D4E 0%,#2E4478 50%,#3B1E6B 100%);border-radius:16px;padding:24px 28px;margin-bottom:20px;display:flex;align-items:center;gap:20px;flex-wrap:wrap;position:relative;overflow:hidden;box-shadow:0 8px 32px rgba(30,45,78,.2)}
.alumni-hero::before{content:'';position:absolute;right:-40px;top:-40px;width:160px;height:160px;border-radius:50%;background:rgba(79,110,247,.15);pointer-events:none}
.alumni-hero-icon{font-size:48px;flex-shrink:0;position:relative;z-index:1}
.alumni-hero-text{flex:1;min-width:0;position:relative;z-index:1}
.alumni-hero-title{font-size:22px;font-weight:700;color:#fff;margin-bottom:5px}
.alumni-hero-sub{font-size:13px;color:rgba(255,255,255,.65)}
.alumni-hero-stats{display:flex;gap:10px;flex-wrap:wrap;position:relative;z-index:1}
.alumni-hero-stat{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);border-radius:12px;padding:10px 16px;text-align:center;min-width:80px}
.alumni-hero-stat-num{font-size:22px;font-weight:800;color:#fff;font-family:'DM Mono',monospace;line-height:1}
.alumni-hero-stat-label{font-size:10.5px;color:rgba(255,255,255,.6);margin-top:3px;font-weight:500}
.angkatan-tabs{display:flex;gap:4px;flex-wrap:wrap;background:var(--surface2);border:1.5px solid var(--border);border-radius:12px;padding:5px 8px;margin-bottom:16px}
.angkatan-tab{display:inline-flex;align-items:center;gap:5px;padding:5px 13px;border-radius:8px;font-size:12.5px;font-weight:600;text-decoration:none;color:var(--text2);transition:all .15s;white-space:nowrap}
.angkatan-tab:hover{background:var(--surface);color:#1E2D4E;box-shadow:0 1px 4px rgba(0,0,0,.07)}
.angkatan-tab.active{background:linear-gradient(135deg,#1E2D4E,#2E4478);color:#fff;box-shadow:0 2px 8px rgba(30,45,78,.25)}
.angkatan-tab-count{background:rgba(255,255,255,.2);color:#fff;border-radius:99px;font-size:10px;font-weight:700;padding:0 6px;min-width:16px;text-align:center;line-height:1.6}
.angkatan-tab:not(.active) .angkatan-tab-count{background:var(--surface);color:#1E2D4E}
.alumni-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:14px;padding:16px}
.alumni-card{background:var(--surface);border:1.5px solid var(--border);border-radius:16px;overflow:hidden;display:flex;flex-direction:column;transition:box-shadow .18s,transform .18s;animation:alumniCardIn .22s ease both}
.alumni-card:hover{box-shadow:0 6px 24px rgba(0,0,0,.09);transform:translateY(-3px)}
@keyframes alumniCardIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
.alumni-card-bar{height:4px;width:100%}
.alumni-card-body{padding:15px;display:flex;flex-direction:column;gap:10px;flex:1}
.alumni-card-top{display:flex;align-items:center;gap:11px}
.alumni-card-photo{width:46px;height:46px;border-radius:12px;object-fit:cover;flex-shrink:0;border:2px solid var(--border)}
.alumni-card-avatar{width:46px;height:46px;border-radius:12px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;color:#fff}
.alumni-card-name{font-weight:700;font-size:13.5px;color:var(--text);line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.alumni-card-nis{font-size:11px;color:var(--text3);font-family:monospace;background:var(--surface2);padding:1px 6px;border-radius:5px;display:inline-block;margin-top:2px}
.alumni-card-info{display:flex;flex-direction:column;gap:5px}
.alumni-card-row{display:flex;align-items:center;justify-content:space-between;font-size:12px}
.alumni-card-label{color:var(--text3);display:flex;align-items:center;gap:4px}
.alumni-card-footer{padding:10px 15px 13px;border-top:1px solid var(--border);background:var(--surface2);display:flex;gap:6px}
.alumni-card-footer .btn{flex:1;justify-content:center;font-size:12px}
.alumni-tbl-scroll{overflow-x:auto;overflow-y:auto;max-height:520px;scrollbar-width:thin}
.alumni-tbl-scroll::-webkit-scrollbar{width:5px;height:5px}
.alumni-tbl-scroll::-webkit-scrollbar-thumb{background:var(--border);border-radius:99px}
.alumni-tbl-scroll thead{position:sticky;top:0;z-index:2}
.alumni-tbl-scroll thead th{box-shadow:0 1.5px 0 var(--border)}
.view-toggle{display:flex;gap:4px;background:var(--surface2);border-radius:10px;padding:3px;flex-shrink:0}
.view-toggle button{display:flex;align-items:center;gap:5px;padding:5px 11px;border:none;border-radius:8px;background:transparent;color:var(--text3);font-size:12px;font-weight:500;cursor:pointer;transition:all .18s;font-family:inherit}
.view-toggle button.active{background:var(--surface);color:#1E2D4E;box-shadow:0 1px 4px rgba(0,0,0,.08)}
.alumni-pager{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;padding:12px 16px;border-top:1px solid var(--border);background:var(--surface2)}
.pager-left{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.pager-info{font-size:12.5px;color:var(--text2)}
.pager-btns{display:flex;gap:4px;flex-wrap:wrap;align-items:center}
.pager-btn{min-width:36px;height:36px;padding:0 10px;border:1.5px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text);font-size:12.5px;font-weight:500;cursor:pointer;font-family:'DM Sans',sans-serif;transition:all .15s;display:inline-flex;align-items:center;justify-content:center;text-decoration:none;white-space:nowrap}
.pager-btn:hover:not(.disabled):not(.active){border-color:#1E2D4E;color:#1E2D4E;background:var(--surface2)}
.pager-btn.active{background:linear-gradient(135deg,#1E2D4E,#2E4478);color:#fff;border-color:#1E2D4E;font-weight:700;box-shadow:0 2px 8px rgba(30,45,78,.3)}
.pager-btn.disabled{opacity:.38;cursor:not-allowed;pointer-events:none}
.pager-ellipsis{padding:0 4px;color:var(--text3);font-size:13px;display:inline-flex;align-items:center;height:36px}
.per-page-sel{padding:5px 9px;border:1.5px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text2);font-size:12px;font-family:inherit;cursor:pointer}
.per-page-sel:focus{outline:none;border-color:#1E2D4E}
@media(max-width:640px){
  .alumni-grid{grid-template-columns:1fr 1fr;gap:10px;padding:10px}
  .alumni-hero{flex-direction:column;align-items:flex-start}
  .alumni-hero-stats{width:100%}
  .alumni-hero-stat{flex:1}
  .view-toggle button span{display:none}
  .alumni-pager{flex-direction:column;align-items:flex-start}
  .pager-left{width:100%;justify-content:space-between}
  .pager-btns{width:100%;justify-content:center}
}
@media(max-width:420px){.alumni-grid{grid-template-columns:1fr}}
</style>

<!-- Hero -->
<div class="alumni-hero">
  <div class="alumni-hero-icon">🎓</div>
  <div class="alumni-hero-text">
    <div class="alumni-hero-title">Data Alumni</div>
    <div class="alumni-hero-sub">Siswa kelas XII yang telah menyelesaikan pendidikan &amp; dinyatakan lulus</div>
  </div>
  <div class="alumni-hero-stats">
    <div class="alumni-hero-stat">
      <div class="alumni-hero-stat-num"><?= number_format($totalSemua) ?></div>
      <div class="alumni-hero-stat-label">Total Alumni</div>
    </div>
    <?php foreach(array_slice($statTahun,0,3,true) as $thn=>$jml): ?>
    <div class="alumni-hero-stat">
      <div class="alumni-hero-stat-num"><?= $jml ?></div>
      <div class="alumni-hero-stat-label">Angkatan <?= e($thn) ?></div>
    </div>
    <?php endforeach ?>
  </div>
  <div style="position:relative;z-index:1">
    <form method="POST" style="margin:0">
      <input type="hidden" name="action" value="ekspor_csv">
      <button type="submit" class="btn" style="background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.25);font-size:12.5px;white-space:nowrap">
        📤 Ekspor CSV
      </button>
    </form>
  </div>
</div>

<!-- Page Header -->
<div class="page-header" style="margin-bottom:12px">
  <div>
    <div class="page-header-title">🎓 Daftar Alumni</div>
    <div class="page-header-sub"><?= number_format($totalAlumni) ?> alumni ditemukan</div>
  </div>
  <a href="index.php?page=siswa" class="btn btn-outline" style="font-size:13px">👥 Data Siswa</a>
</div>

<!-- Angkatan Tabs -->
<?php if(!empty($tahunList)): ?>
<div class="angkatan-tabs">
  <?php $baseQT='index.php?page=alumni&q='.rawurlencode($search).'&jurusan='.rawurlencode($filterJur).'&per_page='.$perPage; ?>
  <a href="<?= $baseQT ?>&tahun_lulus=" class="angkatan-tab <?= !$filterTahun?'active':'' ?>">
    🎓 Semua <span class="angkatan-tab-count"><?= number_format($totalSemua) ?></span>
  </a>
  <?php foreach($statTahun as $thn=>$jml): ?>
  <a href="<?= $baseQT ?>&tahun_lulus=<?= rawurlencode($thn) ?>" class="angkatan-tab <?= $filterTahun===$thn?'active':'' ?>">
    📅 <?= e($thn) ?> <span class="angkatan-tab-count"><?= $jml ?></span>
  </a>
  <?php endforeach ?>
</div>
<?php endif ?>

<!-- Toolbar -->
<div class="toolbar" style="margin-bottom:12px;flex-wrap:wrap;gap:10px">
  <div class="search-box" style="flex:1;min-width:200px">
    <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    <form method="GET" action="index.php" style="margin:0">
      <input type="hidden" name="page"        value="alumni">
      <input type="hidden" name="tahun_lulus" value="<?= e($filterTahun) ?>">
      <input type="hidden" name="jurusan"     value="<?= e($filterJur) ?>">
      <input type="hidden" name="per_page"    value="<?= $perPage ?>">
      <input type="text"   name="q"           value="<?= e($search) ?>" placeholder="Cari nama atau NIS alumni...">
    </form>
  </div>
  <?php if(!empty($jurusanList)): ?>
  <form method="GET" action="index.php" style="margin:0;display:flex;gap:6px">
    <input type="hidden" name="page"        value="alumni">
    <input type="hidden" name="q"           value="<?= e($search) ?>">
    <input type="hidden" name="tahun_lulus" value="<?= e($filterTahun) ?>">
    <input type="hidden" name="per_page"    value="<?= $perPage ?>">
    <select name="jurusan" onchange="this.form.submit()" style="padding:7px 10px;border:1.5px solid var(--border2);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);font-family:'DM Sans',sans-serif;cursor:pointer">
      <option value="">— Semua Jurusan —</option>
      <?php foreach($jurusanList as $j): ?>
      <option value="<?= e($j) ?>" <?= $filterJur===$j?'selected':'' ?>><?= e($j) ?></option>
      <?php endforeach ?>
    </select>
  </form>
  <?php endif ?>
  <?php if($search||$filterTahun||$filterJur): ?>
  <a href="index.php?page=alumni" class="btn btn-outline btn-sm">✕ Reset</a>
  <?php endif ?>
</div>

<!-- Card Wrapper -->
<div class="card" style="padding:0;overflow:visible">
  <!-- Header card -->
  <div style="padding:12px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px">
    <div style="font-size:14px;font-weight:600;color:var(--text);display:flex;align-items:center;gap:8px">
      🎓 Daftar Alumni
      <?php if($totalAlumni): ?><span class="pill" style="background:#E0E7FF;color:#1E2D4E;font-size:11.5px"><?= number_format($totalAlumni) ?></span><?php endif ?>
    </div>
    <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
      <!-- Selector tampil per halaman -->
      <div style="display:flex;align-items:center;gap:5px;font-size:12.5px;color:var(--text2)">
        Tampil
        <select class="per-page-sel" onchange="window.location='<?= $baseP ?>&p=1&per_page='+this.value">
          <?php foreach([10,20,25,50,100] as $opt): ?>
          <option value="<?= $opt ?>" <?= $perPage===$opt?'selected':'' ?>><?= $opt ?></option>
          <?php endforeach ?>
        </select>
        / hal
      </div>
      <!-- View toggle -->
      <div class="view-toggle">
        <button id="alumni-btn-cards" onclick="alumniView('cards')">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></svg>
          <span>Kartu</span>
        </button>
        <button id="alumni-btn-table" onclick="alumniView('table')">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18"/></svg>
          <span>Tabel</span>
        </button>
      </div>
    </div>
  </div>

  <?php if($_tblError): ?>
  <div style="padding:52px 24px">
    <div class="empty-state">
      <div class="empty-state-icon" style="background:#FEE2E2"><span style="font-size:26px">⚠️</span></div>
      <h4>Gagal memuat data alumni</h4>
      <p style="color:#DC2626;font-size:12px;font-family:monospace;max-width:500px;word-break:break-all"><?= e($_tblErrMsg) ?></p>
    </div>
  </div>
  <?php elseif(empty($alumni) && $totalAlumni === 0): ?>
  <div style="padding:52px 24px">
    <div class="empty-state">
      <div class="empty-state-icon" style="background:#E0E7FF"><span style="font-size:26px">🎓</span></div>
      <h4>Belum ada data alumni</h4>
      <p>Data alumni masuk otomatis saat siswa kelas XII diluluskan via fitur Naik Kelas Massal.</p>
    </div>
  </div>
  <?php elseif(empty($alumni) && $totalAlumni > 0): ?>
  <div style="padding:52px 24px">
    <div class="empty-state">
      <div class="empty-state-icon" style="background:#FEF3C7"><span style="font-size:26px">🔍</span></div>
      <h4>Tidak ada hasil untuk filter ini</h4>
      <p><a href="index.php?page=alumni" style="color:var(--indigo)">Reset filter</a> untuk melihat semua alumni.</p>
      <?php if($_tblErrMsg): ?><p style="color:#DC2626;font-size:11px;font-family:monospace;margin-top:8px"><?= e($_tblErrMsg) ?></p><?php endif ?>
    </div>
  </div>
  <?php else: ?>

  <!-- CARD VIEW -->
  <div id="alumni-view-cards" style="display:none">
    <div class="alumni-grid">
      <?php foreach($alumni as $i=>$a):
        $ac      = $avatarColors[$i % count($avatarColors)];
        $fotoAda = !empty($a['foto']) && file_exists($uploadAbs.$a['foto']);
        $jc      = $jurusanColors[$a['jurusan']] ?? '#7C3AED';
      ?>
      <div class="alumni-card" style="animation-delay:<?= $i*25 ?>ms">
        <div class="alumni-card-bar" style="background:linear-gradient(90deg,<?= $jc ?>,#7C3AED)"></div>
        <div class="alumni-card-body">
          <div class="alumni-card-top">
            <?php if($fotoAda): ?>
              <img src="<?= e($uploadUrl.$a['foto']) ?>" class="alumni-card-photo" alt="">
            <?php else: ?>
              <div class="alumni-card-avatar" style="background:<?= $ac ?>"><?= mb_strtoupper(mb_substr($a['nama'],0,1)) ?></div>
            <?php endif ?>
            <div style="min-width:0;flex:1">
              <div class="alumni-card-name"><?= e($a['nama']) ?></div>
              <span class="alumni-card-nis"><?= e($a['nis']) ?></span>
            </div>
          </div>
          <div class="alumni-card-info">
            <div class="alumni-card-row">
              <span class="alumni-card-label">🎓 Jurusan</span>
              <span class="pill" style="background:<?= $jc ?>22;color:<?= $jc ?>;font-size:11px;padding:2px 8px"><?= e($a['jurusan']?:'—') ?></span>
            </div>
            <div class="alumni-card-row">
              <span class="alumni-card-label">📅 Lulus</span>
              <span style="font-size:12px;font-weight:600;color:var(--text)"><?= e($a['tahun_lulus']?:'—') ?></span>
            </div>
            <?php if($a['no_hp']): ?>
            <div class="alumni-card-row">
              <span class="alumni-card-label">📱 HP</span>
              <span style="font-size:12px;color:var(--text2)"><?= e($a['no_hp']) ?></span>
            </div>
            <?php endif ?>
            <?php if(!empty($a['tgl_lulus'])): ?>
            <div class="alumni-card-row">
              <span class="alumni-card-label">🗓️ Tgl Lulus</span>
              <span style="font-size:11.5px;color:var(--text2)"><?= date('d M Y',strtotime($a['tgl_lulus'])) ?></span>
            </div>
            <?php endif ?>
          </div>
        </div>
        <div class="alumni-card-footer">
          <button class="btn btn-outline btn-sm" onclick='bukuAlumniEdit(<?= json_encode($a) ?>)' style="font-size:11.5px">✏️ Edit</button>
          <a href="index.php?page=riwayat_siswa&siswa_id=<?= (int)$a['siswa_id'] ?>" class="btn btn-outline btn-sm" style="font-size:11.5px;text-decoration:none">📋 Riwayat</a>
          <form method="POST" onsubmit="return confirm('Hapus data alumni ini?')">
            <input type="hidden" name="action" value="hapus">
            <input type="hidden" name="id"     value="<?= $a['id'] ?>">
            <button class="btn btn-danger btn-sm" style="font-size:11.5px" type="submit">🗑️</button>
          </form>
        </div>
      </div>
      <?php endforeach ?>
    </div>
  </div>

  <!-- TABLE VIEW -->
  <div id="alumni-view-table" style="display:none">
    <div class="alumni-tbl-scroll">
      <table>
        <thead>
          <tr>
            <th>#</th><th>Foto</th><th>Nama &amp; NIS</th><th>Jurusan</th>
            <th>Tahun Lulus</th><th>Tgl Lulus</th><th>No. HP</th><th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($alumni as $i=>$a):
            $ac      = $avatarColors[$i % count($avatarColors)];
            $fotoAda = !empty($a['foto']) && file_exists($uploadAbs.$a['foto']);
            $jc      = $jurusanColors[$a['jurusan']] ?? '#7C3AED';
            $noUrut  = ($page-1)*$perPage + $i + 1;
          ?>
          <tr>
            <td><div style="width:26px;height:26px;border-radius:7px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:10.5px;font-weight:700;color:var(--text2)"><?= $noUrut ?></div></td>
            <td>
              <?php if($fotoAda): ?>
                <img src="<?= e($uploadUrl.$a['foto']) ?>" style="width:36px;height:36px;border-radius:10px;object-fit:cover;border:2px solid var(--border)">
              <?php else: ?>
                <div class="avatar" style="background:<?= $ac ?>"><?= mb_strtoupper(mb_substr($a['nama'],0,1)) ?></div>
              <?php endif ?>
            </td>
            <td>
              <div style="font-weight:600;font-size:13.5px"><?= e($a['nama']) ?></div>
              <span style="font-family:monospace;font-size:11px;background:var(--surface2);padding:2px 7px;border-radius:5px;color:var(--text3)"><?= e($a['nis']) ?></span>
            </td>
            <td><span class="pill" style="background:<?= $jc ?>22;color:<?= $jc ?>"><?= e($a['jurusan']?:'—') ?></span></td>
            <td><span class="pill" style="background:#E0E7FF;color:#1E2D4E;font-weight:700"><?= e($a['tahun_lulus']?:'—') ?></span></td>
            <td style="font-size:12.5px;color:var(--text2)"><?= !empty($a['tgl_lulus'])?date('d M Y',strtotime($a['tgl_lulus'])):'—' ?></td>
            <td style="font-size:13px;color:var(--text2)"><?= e($a['no_hp']?:'—') ?></td>
            <td>
              <div style="display:flex;gap:5px;flex-wrap:nowrap">
                <button class="btn btn-outline btn-sm" onclick='bukuAlumniEdit(<?= json_encode($a) ?>)'>✏️</button>
                <a href="index.php?page=riwayat_siswa&siswa_id=<?= (int)$a['siswa_id'] ?>" class="btn btn-outline btn-sm" style="text-decoration:none">📋</a>
                <form method="POST" style="display:inline" onsubmit="return confirm('Hapus?')">
                  <input type="hidden" name="action" value="hapus">
                  <input type="hidden" name="id"     value="<?= $a['id'] ?>">
                  <button class="btn btn-danger btn-sm" type="submit">🗑️</button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- PAGINATION -->
  <?php if($totalHal > 1 || $totalAlumni > 0): ?>
  <div class="alumni-pager">
    <div class="pager-left">
      <span class="pager-info">
        Menampilkan
        <b><?= number_format(($page-1)*$perPage+1) ?>&ndash;<?= number_format(min($page*$perPage,$totalAlumni)) ?></b>
        dari <b><?= number_format($totalAlumni) ?></b> alumni
        &nbsp;&middot;&nbsp; Hal <?= $page ?> / <?= $totalHal ?>
      </span>
      <div style="display:flex;align-items:center;gap:5px;font-size:12.5px;color:var(--text2)">
        Tampil
        <select class="per-page-sel" onchange="window.location='<?= $baseP ?>&p=1&per_page='+this.value">
          <?php foreach([10,20,25,50,100] as $opt): ?>
          <option value="<?= $opt ?>" <?= $perPage===$opt?'selected':'' ?>><?= $opt ?></option>
          <?php endforeach ?>
        </select>
        / hal
      </div>
    </div>
    <?php if($totalHal > 1): ?>
    <div class="pager-btns">
      <?php if($page>1): ?>
      <a href="<?= $baseP ?>&p=<?= $page-1 ?>" class="pager-btn">&lsaquo; Prev</a>
      <?php else: ?><span class="pager-btn disabled">&lsaquo; Prev</span><?php endif ?>
      <?php $wS=max(1,$page-2); $wE=min($totalHal,$page+2); ?>
      <?php if($wS>1): ?><a href="<?= $baseP ?>&p=1" class="pager-btn">1</a><?php if($wS>2): ?><span class="pager-ellipsis">&hellip;</span><?php endif ?><?php endif ?>
      <?php for($pp=$wS;$pp<=$wE;$pp++): ?>
        <?php if($pp===$page): ?><span class="pager-btn active"><?= $pp ?></span>
        <?php else: ?><a href="<?= $baseP ?>&p=<?= $pp ?>" class="pager-btn"><?= $pp ?></a><?php endif ?>
      <?php endfor ?>
      <?php if($wE<$totalHal): ?><?php if($wE<$totalHal-1): ?><span class="pager-ellipsis">&hellip;</span><?php endif ?><a href="<?= $baseP ?>&p=<?= $totalHal ?>" class="pager-btn"><?= $totalHal ?></a><?php endif ?>
      <?php if($page<$totalHal): ?>
      <a href="<?= $baseP ?>&p=<?= $page+1 ?>" class="pager-btn">Next &rsaquo;</a>
      <?php else: ?><span class="pager-btn disabled">Next &rsaquo;</span><?php endif ?>
    </div>
    <?php endif ?>
  </div>
  <?php endif ?>

  <?php endif ?>
</div>

<!-- Modal Edit -->
<div class="modal-overlay" id="modalEditAlumni">
  <div class="modal" style="max-width:480px">
    <div class="modal-header" style="background:linear-gradient(135deg,#1E2D4E,#3B1E6B);border-radius:16px 16px 0 0">
      <h3 style="color:#fff">✏️ Edit Data Alumni</h3>
      <button class="modal-close" onclick="closeModal('modalEditAlumni')" style="color:#fff;opacity:.8">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id"     id="editAlumniId">
      <div class="modal-body">
        <div style="background:var(--surface2);border-radius:12px;padding:13px;margin-bottom:16px;display:flex;align-items:center;gap:12px">
          <div id="editAlumniAvatar" style="width:44px;height:44px;border-radius:11px;background:#1E2D4E;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;color:#fff;flex-shrink:0"></div>
          <div>
            <div id="editAlumniNama" style="font-weight:700;font-size:14px;color:var(--text)"></div>
            <div id="editAlumniMeta" style="font-size:11.5px;color:var(--text3);margin-top:3px"></div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>Tanggal Lulus</label><input type="date" name="tgl_lulus" id="editAlumniTgl"></div>
          <div class="form-group"><label>No. HP</label><input type="tel" name="no_hp" id="editAlumniHp" placeholder="08xxxxxxxxxx"></div>
        </div>
        <div class="form-group"><label>Alamat</label><textarea name="alamat" id="editAlumniAlamat" rows="2" placeholder="Alamat lengkap"></textarea></div>
        <div class="form-group"><label>Keterangan</label><textarea name="keterangan" id="editAlumniKet" rows="2" placeholder="Catatan tambahan (opsional)"></textarea></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalEditAlumni')">Batal</button>
        <button type="submit" class="btn btn-primary" style="background:linear-gradient(135deg,#1E2D4E,#3B1E6B)">💾 Simpan</button>
      </div>
    </form>
  </div>
</div>

<script>
function _alumniApplyView(m) {
  var isCards = (m === 'cards');
  var vc = document.getElementById('alumni-view-cards');
  var vt = document.getElementById('alumni-view-table');
  var bc = document.getElementById('alumni-btn-cards');
  var bt = document.getElementById('alumni-btn-table');
  if (vc) vc.style.display = isCards ? '' : 'none';
  if (vt) vt.style.display = isCards ? 'none' : '';
  if (bc) bc.classList.toggle('active',  isCards);
  if (bt) bt.classList.toggle('active', !isCards);
}
window.alumniView = function(m) {
  localStorage.setItem('alumni_view', m);
  _alumniApplyView(m);
};
_alumniApplyView(localStorage.getItem('alumni_view') || 'cards');

function bukuAlumniEdit(a){
  document.getElementById('editAlumniId').value     = a.id;
  document.getElementById('editAlumniTgl').value    = a.tgl_lulus    || '';
  document.getElementById('editAlumniHp').value     = a.no_hp        || '';
  document.getElementById('editAlumniAlamat').value = a.alamat       || '';
  document.getElementById('editAlumniKet').value    = a.keterangan   || '';
  document.getElementById('editAlumniAvatar').textContent = a.nama.charAt(0).toUpperCase();
  document.getElementById('editAlumniNama').textContent   = a.nama;
  document.getElementById('editAlumniMeta').textContent   =
    'NIS: '+a.nis+(a.jurusan?' · '+a.jurusan:'')+(a.tahun_lulus?' · Lulus '+a.tahun_lulus:'');
  openModal('modalEditAlumni');
}
</script>

<?php require_once 'layout/footer.php'; ?>