<?php
/* ════════════════════════════════════════════════════════════════
   riwayat_siswa.php — Riwayat Kelas & Aktivitas Siswa
   Mencatat: naik kelas, pindah kelas, kelulusan, perubahan status
   ════════════════════════════════════════════════════════════════ */

require_once 'layout/header.php';

/* ── Buat tabel riwayat jika belum ada ── */
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `riwayat_siswa` (
        `id`           INT          NOT NULL AUTO_INCREMENT,
        `siswa_id`     INT          NOT NULL,
        `jenis`        VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL
                       COMMENT 'naik_kelas|pindah_kelas|lulus|aktif|nonaktif|edit',
        `kelas_dari`   VARCHAR(10)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `jurusan_dari` VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `kelas_ke`     VARCHAR(10)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `jurusan_ke`   VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `tahun_ajaran` VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `keterangan`   TEXT         CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `oleh_user`    VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `tgl_kejadian` DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `idx_siswa_id`    (`siswa_id`),
        KEY `idx_jenis`       (`jenis`),
        KEY `idx_tgl_kejadian`(`tgl_kejadian`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
      COMMENT='Riwayat perubahan kelas dan status siswa'");

    /* Migrasi: pindahkan data dari riwayat_pindah_kelas jika ada */
    $cekLama = $pdo->query("SHOW TABLES LIKE 'riwayat_pindah_kelas'")->fetchColumn();
    if ($cekLama) {
        $cekMigrated = $pdo->query("SELECT COUNT(*) FROM riwayat_siswa WHERE jenis='pindah_kelas'")->fetchColumn();
        if ($cekMigrated == 0) {
            /* Cek apakah kolom oleh_user ada di tabel lama */
            $kolomLama = $pdo->query("SHOW COLUMNS FROM riwayat_pindah_kelas")->fetchAll(PDO::FETCH_COLUMN);
            $adaOlehUser = in_array('oleh_user', $kolomLama);

            $sqlMigrasi = "INSERT IGNORE INTO riwayat_siswa
                (siswa_id, jenis, kelas_dari, jurusan_dari, kelas_ke, jurusan_ke,
                 tahun_ajaran, keterangan, oleh_user, tgl_kejadian)
             SELECT siswa_id, 'pindah_kelas', kelas_dari, jurusan_dari, kelas_ke, jurusan_ke,
                    tahun_ajaran, alasan, "
                . ($adaOlehUser ? "oleh_user" : "NULL")
                . ", tgl_pindah FROM riwayat_pindah_kelas";

            $pdo->exec($sqlMigrasi);
        }
    }
} catch (Exception $e) { /* abaikan */ }

/* ── Parameter ── */
$search       = trim($_GET['q']            ?? '');
$filterJenis  = trim($_GET['jenis']        ?? '');
$filterKelas  = trim($_GET['kelas']        ?? '');
$filterTahun  = trim($_GET['tahun_ajaran'] ?? '');
$filterStatus = trim($_GET['status_siswa'] ?? '');
$siswaId      = (int)($_GET['siswa_id']    ?? 0);
$page         = max(1, (int)($_GET['p']    ?? 1));
$perPage      = 15;
$offset       = ($page - 1) * $perPage;

/* ── Daftar jenis riwayat ── */
$jenisMap = [
    'naik_kelas'   => ['label'=>'Naik Kelas',    'icon'=>'⬆️', 'color'=>'#059669', 'bg'=>'#D1FAE5', 'pill'=>'pill-green'],
    'pindah_kelas' => ['label'=>'Pindah Kelas',  'icon'=>'🔀', 'color'=>'#0369A1', 'bg'=>'#E0F2FE', 'pill'=>'pill-blue'],
    'lulus'        => ['label'=>'Lulus',          'icon'=>'🎓', 'color'=>'#7C3AED', 'bg'=>'#EDE9FE', 'pill'=>'pill-purple'],
    'aktif'        => ['label'=>'Diaktifkan',     'icon'=>'✅', 'color'=>'#16A34A', 'bg'=>'#DCFCE7', 'pill'=>'pill-green'],
    'nonaktif'     => ['label'=>'Dinonaktifkan',  'icon'=>'⛔', 'color'=>'#DC2626', 'bg'=>'#FEE2E2', 'pill'=>''],
    'edit'         => ['label'=>'Data Diperbarui','icon'=>'✏️', 'color'=>'#D97706', 'bg'=>'#FEF3C7', 'pill'=>'pill-orange'],
];

/* ── Data tahun ajaran untuk filter ── */
$tahunList = [];
try {
    $tahunList = $pdo->query(
        "SELECT DISTINCT tahun_ajaran FROM riwayat_siswa
         WHERE tahun_ajaran IS NOT NULL ORDER BY tahun_ajaran DESC"
    )->fetchAll(PDO::FETCH_COLUMN);
    if (empty($tahunList)) {
        $tahunList = $pdo->query(
            "SELECT DISTINCT tahun_ajaran FROM siswa ORDER BY tahun_ajaran DESC"
        )->fetchAll(PDO::FETCH_COLUMN);
    }
} catch (Exception $e) {}

/* ── Query utama: jika ada siswa_id → mode detail satu siswa ── */
$siswaPilih   = null;
$riwayatList  = [];
$totalRiwayat = 0;
$totalHalaman = 1;

/* ── Ambil data siswa yang dipilih ── */
if ($siswaId) {
    try {
        $s = $pdo->prepare("SELECT * FROM siswa WHERE id=? LIMIT 1");
        $s->execute([$siswaId]);
        $siswaPilih = $s->fetch();
    } catch (Exception $e) {}
}

/* ── Query riwayat ── */
try {
    $sqlW  = "FROM riwayat_siswa r
              LEFT JOIN siswa s ON s.id = r.siswa_id
              WHERE 1=1";
    $par   = [];

    if ($siswaId) {
        $sqlW .= " AND r.siswa_id=?"; $par[] = $siswaId;
    }
    if ($search) {
        $sqlW .= " AND (s.nama LIKE ? OR s.nis LIKE ?)";
        $par[] = "%$search%"; $par[] = "%$search%";
    }
    if ($filterJenis)  { $sqlW .= " AND r.jenis=?";        $par[] = $filterJenis; }
    if ($filterKelas)  { $sqlW .= " AND (r.kelas_dari=? OR r.kelas_ke=?)"; $par[] = $filterKelas; $par[] = $filterKelas; }
    if ($filterTahun)  { $sqlW .= " AND r.tahun_ajaran=?"; $par[] = $filterTahun; }
    if ($filterStatus) { $sqlW .= " AND s.status=?";       $par[] = $filterStatus; }

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

    /* Data */
    $stmtR = $pdo->prepare(
        "SELECT r.*, s.nama AS siswa_nama, s.nis AS siswa_nis,
                s.foto AS siswa_foto, s.kelas AS siswa_kelas,
                s.jurusan AS siswa_jurusan, s.status AS siswa_status
         $sqlW
         ORDER BY r.tgl_kejadian DESC
         LIMIT $perPage OFFSET $offset"
    );
    $stmtR->execute($par);
    $riwayatList = $stmtR->fetchAll();
} catch (Exception $e) {
    $riwayatList  = [];
    $totalRiwayat = 0;
}

/* ── Statistik ringkasan ── */
$statJenis = [];
try {
    $rows = $pdo->query(
        "SELECT jenis, COUNT(*) as total FROM riwayat_siswa GROUP BY jenis"
    )->fetchAll();
    foreach ($rows as $r) $statJenis[$r['jenis']] = (int)$r['total'];
} catch (Exception $e) {}

$totalSemuaRiwayat = array_sum($statJenis);

/* ── Daftar kelas untuk filter ── */
$kelasList = [];
try {
    $kelasList = $pdo->query(
        "SELECT DISTINCT tingkat FROM kelas WHERE status='aktif'
         ORDER BY FIELD(tingkat,'X','XI','XII')"
    )->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) { $kelasList = ['X','XI','XII']; }

$uploadUrl = 'uploads/foto_siswa/';
$uploadAbs = str_replace('\\','/',dirname(__DIR__)).'/uploads/foto_siswa/';
$avatarColors = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];

$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
/* ══ Timeline ══ */
.timeline { position:relative; padding-left:28px; }
.timeline::before {
  content:''; position:absolute; left:10px; top:0; bottom:0;
  width:2px; background:linear-gradient(to bottom, var(--indigo), transparent);
  border-radius:99px;
}
.timeline-item {
  position:relative; margin-bottom:20px;
  animation: tlIn .25s ease both;
}
@keyframes tlIn {
  from { opacity:0; transform:translateX(-8px); }
  to   { opacity:1; transform:translateX(0); }
}
.timeline-dot {
  position:absolute; left:-24px; top:14px;
  width:20px; height:20px; border-radius:50%;
  display:flex; align-items:center; justify-content:center;
  font-size:10px; border:2px solid var(--surface);
  box-shadow:0 0 0 2px var(--border2);
  z-index:1;
}
.timeline-card {
  background:var(--surface); border:1.5px solid var(--border);
  border-radius:12px; padding:13px 15px;
  transition:box-shadow .15s, border-color .15s;
}
.timeline-card:hover {
  border-color:var(--border2);
  box-shadow:0 4px 16px rgba(30,45,78,.08);
}
.timeline-header {
  display:flex; align-items:center; gap:8px; flex-wrap:wrap;
  margin-bottom:8px;
}
.timeline-jenis {
  display:inline-flex; align-items:center; gap:5px;
  padding:3px 10px; border-radius:99px;
  font-size:11.5px; font-weight:700;
}
.timeline-time {
  font-size:11px; color:var(--text3); margin-left:auto;
  display:flex; align-items:center; gap:4px;
}
.timeline-arrow {
  display:flex; align-items:center; gap:8px;
  background:var(--bg3); border-radius:8px;
  padding:7px 12px; flex-wrap:wrap;
}
.timeline-kelas-chip {
  display:inline-flex; align-items:center; gap:4px;
  padding:3px 10px; border-radius:7px;
  font-size:12px; font-weight:700;
}
.timeline-arrow-sep {
  font-size:16px; font-weight:900; color:var(--text3); flex-shrink:0;
}

/* ══ Stat mini ══ */
.riwayat-stat-grid {
  display:grid;
  grid-template-columns:repeat(auto-fill, minmax(130px,1fr));
  gap:10px; margin-bottom:20px;
}
.riwayat-stat {
  background:var(--surface); border:1.5px solid var(--border);
  border-radius:12px; padding:13px 15px;
  display:flex; align-items:center; gap:10px;
  transition:border-color .15s, box-shadow .15s;
}
.riwayat-stat:hover { border-color:var(--border2); box-shadow:0 2px 10px rgba(30,45,78,.07); }
.riwayat-stat-ico {
  font-size:22px; line-height:1; flex-shrink:0;
}
.riwayat-stat-num {
  font-size:20px; font-weight:800; line-height:1;
  font-family:'DM Mono',monospace;
}
.riwayat-stat-label { font-size:10.5px; color:var(--text2); margin-top:2px; }

/* ══ Siswa card (detail mode) ══ */
.siswa-detail-card {
  background:linear-gradient(135deg,#1E2D4E,#2E4478);
  border-radius:16px; padding:20px;
  display:flex; align-items:center; gap:16px;
  margin-bottom:20px; position:relative; overflow:hidden;
  flex-wrap:wrap;
}
.siswa-detail-card::before {
  content:''; position:absolute; right:-30px; top:-30px;
  width:120px; height:120px; border-radius:50%;
  background:rgba(79,110,247,.2); pointer-events:none;
}
.siswa-detail-avatar {
  width:56px; height:56px; border-radius:14px; flex-shrink:0;
  border:2px solid rgba(255,255,255,.2); overflow:hidden;
  display:flex; align-items:center; justify-content:center;
  font-size:22px; font-weight:800; color:#fff;
}
.siswa-detail-name  { font-size:16px; font-weight:700; color:#fff; }
.siswa-detail-nis   { font-size:12px; color:rgba(255,255,255,.6); font-family:'DM Mono',monospace; margin-top:3px; }
.siswa-detail-pills { display:flex; gap:6px; flex-wrap:wrap; margin-top:8px; }
.siswa-detail-pill  {
  background:rgba(255,255,255,.15); border:1px solid rgba(255,255,255,.2);
  color:#fff; border-radius:99px; padding:3px 10px;
  font-size:11px; font-weight:600;
}

/* ══ Pencarian siswa live ══ */
.siswa-search-result {
  position:absolute; top:100%; left:0; right:0; z-index:50;
  background:var(--surface); border:1.5px solid var(--border2);
  border-radius:10px; box-shadow:var(--shadow-md);
  max-height:260px; overflow-y:auto; margin-top:4px;
  display:none;
}
.siswa-search-result.show { display:block; }
.siswa-search-item {
  display:flex; align-items:center; gap:10px;
  padding:10px 14px; cursor:pointer; transition:background .12s;
  border-bottom:1px solid var(--border);
}
.siswa-search-item:last-child { border-bottom:none; }
.siswa-search-item:hover { background:var(--surface2); }
.siswa-search-avatar {
  width:34px; height:34px; border-radius:9px; flex-shrink:0;
  display:flex; align-items:center; justify-content:center;
  font-weight:700; font-size:13px; color:#fff;
}

/* ══ Filter bar ══ */
.filter-chips {
  display:flex; gap:6px; flex-wrap:wrap; align-items:center;
}
.filter-chip {
  display:inline-flex; align-items:center; gap:5px;
  padding:5px 12px; border-radius:99px; font-size:12px; font-weight:600;
  text-decoration:none; transition:all .15s; white-space:nowrap;
  border:1.5px solid var(--border2); color:var(--text2);
  background:var(--surface);
}
.filter-chip:hover { border-color:var(--indigo); color:var(--indigo); background:var(--indigo-light); }
.filter-chip.active { background:var(--indigo); color:#fff; border-color:var(--indigo); box-shadow:0 2px 8px rgba(79,110,247,.3); }

/* ══ Pager ══ */
.riwayat-pager {
  display:flex; align-items:center; justify-content:space-between;
  flex-wrap:wrap; gap:8px; padding:14px 0; margin-top:8px;
}
.pager-info { font-size:12.5px; color:var(--text2); }
.pager-btns { display:flex; gap:4px; flex-wrap:wrap; }
.pager-btn  {
  min-width:34px; height:34px; 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;
}
.pager-btn:hover:not(.disabled):not(.active) {
  border-color:var(--indigo); color:var(--indigo); background:var(--indigo-light);
}
.pager-btn.active  { background:var(--indigo); color:#fff; border-color:var(--indigo); font-weight:700; }
.pager-btn.disabled{ opacity:.35; cursor:not-allowed; }

@media (max-width:640px) {
  .riwayat-stat-grid { grid-template-columns:1fr 1fr; }
  .siswa-detail-card { flex-direction:column; align-items:flex-start; }
  .timeline { padding-left:20px; }
}
</style>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title">📋 Riwayat Siswa</div>
    <div class="page-header-sub">
      <?php if($siswaPilih): ?>
        Menampilkan riwayat untuk <strong><?= e($siswaPilih['nama']) ?></strong>
        — <a href="index.php?page=riwayat_siswa" style="color:var(--indigo);font-size:12px">← Lihat semua</a>
      <?php else: ?>
        Riwayat naik kelas, pindah kelas, dan perubahan status semua siswa
      <?php endif ?>
    </div>
  </div>
  <?php if(!$siswaPilih): ?>
  <div style="display:flex;gap:8px">
    <a href="index.php?page=siswa" class="btn btn-outline" style="font-size:13px">👥 Data Siswa</a>
    <a href="index.php?page=kelas" class="btn btn-outline" style="font-size:13px">🏫 Kelas</a>
  </div>
  <?php endif ?>
</div>

<!-- ══ Mode: tampilkan detail satu siswa ══ -->
<?php if($siswaPilih): ?>
<?php
  $fotoAda = !empty($siswaPilih['foto']) && file_exists($uploadAbs.$siswaPilih['foto']);
  $ac = $avatarColors[crc32($siswaPilih['nama']) % count($avatarColors)];
  $isAktif = $siswaPilih['status'] === 'aktif';
?>
<div class="siswa-detail-card">
  <div class="siswa-detail-avatar" style="<?= $fotoAda ? '' : 'background:'.$ac ?>">
    <?php if($fotoAda): ?>
      <img src="<?= e($uploadUrl.$siswaPilih['foto']) ?>" style="width:100%;height:100%;object-fit:cover">
    <?php else: ?>
      <?= mb_strtoupper(mb_substr($siswaPilih['nama'],0,1)) ?>
    <?php endif ?>
  </div>
  <div style="flex:1;min-width:0;position:relative;z-index:1">
    <div class="siswa-detail-name"><?= e($siswaPilih['nama']) ?></div>
    <div class="siswa-detail-nis">NIS: <?= e($siswaPilih['nis']) ?></div>
    <div class="siswa-detail-pills">
      <span class="siswa-detail-pill">📚 <?= e($siswaPilih['kelas']) ?> <?= e($siswaPilih['jurusan']) ?></span>
      <span class="siswa-detail-pill">📅 <?= e($siswaPilih['tahun_ajaran']) ?></span>
      <span class="siswa-detail-pill" style="background:<?= $isAktif?'rgba(74,222,128,.25)':'rgba(239,68,68,.25)' ?>">
        <?= $isAktif ? '✅ Aktif' : '⛔ Nonaktif' ?>
      </span>
      <?php if($siswaPilih['no_hp']): ?>
      <span class="siswa-detail-pill">📱 <?= e($siswaPilih['no_hp']) ?></span>
      <?php endif ?>
    </div>
  </div>
  <div style="position:relative;z-index:1;display:flex;flex-direction:column;gap:6px;align-items:flex-end">
    <a href="index.php?page=siswa" class="btn btn-sm"
       style="background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.2);font-size:12px">
      ✏️ Edit Siswa
    </a>
    <span style="font-size:11px;color:rgba(255,255,255,.5)">
      <?= $totalRiwayat ?> catatan riwayat
    </span>
  </div>
</div>
<?php endif ?>

<!-- ══ Statistik ══ -->
<?php if(!$siswaPilih): ?>
<div class="riwayat-stat-grid">
  <div class="riwayat-stat">
    <div class="riwayat-stat-ico">📋</div>
    <div>
      <div class="riwayat-stat-num" style="color:var(--indigo)"><?= number_format($totalSemuaRiwayat) ?></div>
      <div class="riwayat-stat-label">Total riwayat</div>
    </div>
  </div>
  <?php foreach($jenisMap as $jk => $jv): ?>
  <?php if(isset($statJenis[$jk]) && $statJenis[$jk] > 0): ?>
  <div class="riwayat-stat" style="border-left:3px solid <?= $jv['color'] ?>">
    <div class="riwayat-stat-ico"><?= $jv['icon'] ?></div>
    <div>
      <div class="riwayat-stat-num" style="color:<?= $jv['color'] ?>"><?= number_format($statJenis[$jk]) ?></div>
      <div class="riwayat-stat-label"><?= $jv['label'] ?></div>
    </div>
  </div>
  <?php endif ?>
  <?php endforeach ?>
</div>
<?php endif ?>

<!-- ══ Pencarian siswa + filter ══ -->
<div class="card" style="padding:16px 20px;margin-bottom:16px">
  <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-start">

    <!-- Cari siswa (live search) -->
    <div style="flex:1;min-width:220px;position:relative" id="searchWrap">
      <div style="position:relative">
        <svg style="position:absolute;left:11px;top:50%;transform:translateY(-50%);width:14px;height:14px;color:var(--text3);pointer-events:none" 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>
        <input type="text" id="searchInput" placeholder="Cari nama atau NIS siswa..."
               value="<?= e($search) ?>"
               style="padding-left:36px;width:100%"
               autocomplete="off"
               oninput="liveSearchSiswa(this.value)"
               onkeydown="if(event.key==='Enter'){goSearch(this.value)}">
      </div>
      <!-- Dropdown hasil pencarian -->
      <div class="siswa-search-result" id="searchResult"></div>
    </div>

    <!-- Filter Jenis -->
    <select id="filterJenis" onchange="applyFilter()"
            style="padding:9px 12px;border:1.5px solid var(--border2);border-radius:var(--r-xs);font-size:13px;background:var(--surface);color:var(--text);font-family:'DM Sans',sans-serif;cursor:pointer">
      <option value="">— Semua Jenis —</option>
      <?php foreach($jenisMap as $jk=>$jv): ?>
      <option value="<?= $jk ?>" <?= $filterJenis===$jk?'selected':'' ?>><?= $jv['icon'] ?> <?= $jv['label'] ?></option>
      <?php endforeach ?>
    </select>

    <!-- Filter Kelas -->
    <select id="filterKelas" onchange="applyFilter()"
            style="padding:9px 12px;border:1.5px solid var(--border2);border-radius:var(--r-xs);font-size:13px;background:var(--surface);color:var(--text);font-family:'DM Sans',sans-serif;cursor:pointer">
      <option value="">— Semua Kelas —</option>
      <?php foreach($kelasList as $k): ?>
      <option value="<?= e($k) ?>" <?= $filterKelas===$k?'selected':'' ?>>Kelas <?= e($k) ?></option>
      <?php endforeach ?>
    </select>

    <!-- Filter Tahun -->
    <?php if($tahunList): ?>
    <select id="filterTahun" onchange="applyFilter()"
            style="padding:9px 12px;border:1.5px solid var(--border2);border-radius:var(--r-xs);font-size:13px;background:var(--surface);color:var(--text);font-family:'DM Sans',sans-serif;cursor:pointer">
      <option value="">— Semua Tahun —</option>
      <?php foreach($tahunList as $ty): ?>
      <option value="<?= e($ty) ?>" <?= $filterTahun===$ty?'selected':'' ?>><?= e($ty) ?></option>
      <?php endforeach ?>
    </select>
    <?php endif ?>

    <!-- Reset filter -->
    <?php if($search||$filterJenis||$filterKelas||$filterTahun||$filterStatus): ?>
    <a href="index.php?page=riwayat_siswa<?= $siswaId?'&siswa_id='.$siswaId:'' ?>"
       class="btn btn-outline btn-sm" style="align-self:center;white-space:nowrap">
       ✕ Reset Filter
    </a>
    <?php endif ?>
  </div>

  <!-- Filter chips jenis cepat -->
  <?php if(!$siswaPilih): ?>
  <div class="filter-chips" style="margin-top:12px">
    <?php
    $baseUrl = 'index.php?page=riwayat_siswa&q='.rawurlencode($search)
             .'&kelas='.rawurlencode($filterKelas)
             .'&tahun_ajaran='.rawurlencode($filterTahun);
    ?>
    <a href="<?= $baseUrl ?>&jenis=" class="filter-chip <?= !$filterJenis?'active':'' ?>">🗒️ Semua</a>
    <?php foreach($jenisMap as $jk=>$jv): ?>
    <a href="<?= $baseUrl ?>&jenis=<?= $jk ?>"
       class="filter-chip <?= $filterJenis===$jk?'active':'' ?>"
       style="<?= $filterJenis===$jk?'background:'.$jv['color'].';border-color:'.$jv['color']:'' ?>">
      <?= $jv['icon'] ?> <?= $jv['label'] ?>
      <?php if(isset($statJenis[$jk])): ?>
        <span style="background:rgba(255,255,255,.25);border-radius:99px;padding:0 6px;font-size:10px"><?= $statJenis[$jk] ?></span>
      <?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php endif ?>
</div>

<!-- ══ Konten riwayat ══ -->
<div class="card" style="padding:0;overflow:hidden">
  <div style="padding:14px 18px;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 Riwayat
      <?php if($totalRiwayat > 0): ?>
        <span class="pill pill-purple"><?= number_format($totalRiwayat) ?> entri</span>
      <?php endif ?>
    </div>
    <?php if($totalHalaman > 1): ?>
    <div style="font-size:12px;color:var(--text3)">
      Halaman <?= $page ?> / <?= $totalHalaman ?>
    </div>
    <?php endif ?>
  </div>

  <?php if(empty($riwayatList)): ?>
  <div style="padding:56px 24px">
    <div class="empty-state">
      <div class="empty-state-icon">
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
      </div>
      <h4>Belum ada riwayat</h4>
      <p>Riwayat akan tercatat otomatis saat ada aktivitas naik kelas, pindah kelas, atau perubahan status siswa.</p>
    </div>
  </div>

  <?php else: ?>
  <div style="padding:20px 22px">

    <?php if($siswaPilih): ?>
    <!-- ══ Mode timeline (detail satu siswa) ══ -->
    <div class="timeline">
      <?php foreach($riwayatList as $i=>$r):
        $jinfo = $jenisMap[$r['jenis']] ?? ['label'=>$r['jenis'],'icon'=>'📌','color'=>'#9CA3AF','bg'=>'#F3F4F6'];
        $animDelay = $i * 40;
      ?>
      <div class="timeline-item" style="animation-delay:<?= $animDelay ?>ms">
        <div class="timeline-dot" style="background:<?= $jinfo['bg'] ?>;color:<?= $jinfo['color'] ?>">
          <?= $jinfo['icon'] ?>
        </div>
        <div class="timeline-card">
          <div class="timeline-header">
            <span class="timeline-jenis" style="background:<?= $jinfo['bg'] ?>;color:<?= $jinfo['color'] ?>">
              <?= $jinfo['icon'] ?> <?= $jinfo['label'] ?>
            </span>
            <?php if($r['tahun_ajaran']): ?>
            <span class="pill pill-blue" style="font-size:11px">📅 <?= e($r['tahun_ajaran']) ?></span>
            <?php endif ?>
            <span class="timeline-time">
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
              <?= date('d M Y, H:i', strtotime($r['tgl_kejadian'])) ?>
            </span>
          </div>

          <!-- Tampilan arah kelas -->
          <?php if($r['kelas_dari'] || $r['kelas_ke']): ?>
          <div class="timeline-arrow">
            <?php if($r['kelas_dari']): ?>
            <span class="timeline-kelas-chip" style="background:#FEE2E2;color:#DC2626">
              <?= e($r['kelas_dari']) ?> <?= e($r['jurusan_dari']) ?>
            </span>
            <?php endif ?>
            <?php if($r['kelas_dari'] && $r['kelas_ke']): ?>
            <span class="timeline-arrow-sep">→</span>
            <?php endif ?>
            <?php if($r['kelas_ke']): ?>
            <span class="timeline-kelas-chip" style="background:#D1FAE5;color:#065F46">
              <?= e($r['kelas_ke']) ?> <?= e($r['jurusan_ke']) ?>
            </span>
            <?php endif ?>
          </div>
          <?php endif ?>

          <?php if($r['keterangan']): ?>
          <div style="margin-top:8px;font-size:12.5px;color:var(--text2);background:var(--surface2);border-radius:7px;padding:7px 11px;border-left:3px solid <?= $jinfo['color'] ?>">
            💬 <?= e($r['keterangan']) ?>
          </div>
          <?php endif ?>

          <?php if($r['oleh_user']): ?>
          <div style="margin-top:7px;font-size:11px;color:var(--text3)">
            👤 Oleh: <?= e($r['oleh_user']) ?>
          </div>
          <?php endif ?>
        </div>
      </div>
      <?php endforeach ?>
    </div>

    <?php else: ?>
    <!-- ══ Mode tabel (semua siswa) ══ -->
    <div style="overflow-x:auto">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Siswa</th>
            <th>Jenis</th>
            <th>Perubahan Kelas</th>
            <th>Tahun Ajaran</th>
            <th>Keterangan</th>
            <th>Tanggal</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($riwayatList as $i=>$r):
            $jinfo   = $jenisMap[$r['jenis']] ?? ['label'=>$r['jenis'],'icon'=>'📌','color'=>'#9CA3AF','bg'=>'#F3F4F6'];
            $noUrut  = ($page-1)*$perPage + $i + 1;
            $ac      = $avatarColors[crc32($r['siswa_nama']??'') % count($avatarColors)];
            $fotoAda = !empty($r['siswa_foto']) && file_exists($uploadAbs.$r['siswa_foto']);
          ?>
          <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>
              <div style="display:flex;align-items:center;gap:9px">
                <div style="width:34px;height:34px;border-radius:9px;flex-shrink:0;overflow:hidden;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:13px;color:#fff;<?= $fotoAda?'':'background:'.$ac ?>">
                  <?php if($fotoAda): ?>
                    <img src="<?= e($uploadUrl.$r['siswa_foto']) ?>" style="width:100%;height:100%;object-fit:cover">
                  <?php else: ?>
                    <?= mb_strtoupper(mb_substr($r['siswa_nama']??'?',0,1)) ?>
                  <?php endif ?>
                </div>
                <div>
                  <div style="font-weight:600;font-size:13px"><?= e($r['siswa_nama'] ?? '—') ?></div>
                  <span style="font-size:11px;font-family:monospace;background:var(--surface2);padding:1px 6px;border-radius:4px;color:var(--text3)"><?= e($r['siswa_nis'] ?? '') ?></span>
                </div>
              </div>
            </td>
            <td>
              <span class="timeline-jenis" style="background:<?= $jinfo['bg'] ?>;color:<?= $jinfo['color'] ?>">
                <?= $jinfo['icon'] ?> <?= $jinfo['label'] ?>
              </span>
            </td>
            <td>
              <?php if($r['kelas_dari'] || $r['kelas_ke']): ?>
              <div style="display:flex;align-items:center;gap:5px;flex-wrap:nowrap">
                <?php if($r['kelas_dari']): ?>
                <span style="background:#FEE2E2;color:#DC2626;border-radius:6px;padding:2px 8px;font-size:11.5px;font-weight:700;white-space:nowrap">
                  <?= e($r['kelas_dari']) ?> <?= e($r['jurusan_dari']) ?>
                </span>
                <?php endif ?>
                <?php if($r['kelas_dari'] && $r['kelas_ke']): ?>
                <span style="color:var(--text3);font-weight:900">→</span>
                <?php endif ?>
                <?php if($r['kelas_ke']): ?>
                <span style="background:#D1FAE5;color:#065F46;border-radius:6px;padding:2px 8px;font-size:11.5px;font-weight:700;white-space:nowrap">
                  <?= e($r['kelas_ke']) ?> <?= e($r['jurusan_ke']) ?>
                </span>
                <?php endif ?>
              </div>
              <?php else: ?>
              <span style="color:var(--text3);font-size:12px">—</span>
              <?php endif ?>
            </td>
            <td>
              <?php if($r['tahun_ajaran']): ?>
              <span class="pill pill-blue" style="font-size:11px"><?= e($r['tahun_ajaran']) ?></span>
              <?php else: ?><span style="color:var(--text3)">—</span>
              <?php endif ?>
            </td>
            <td style="max-width:180px">
              <?php if($r['keterangan']): ?>
              <span style="font-size:12px;color:var(--text2)" title="<?= e($r['keterangan']) ?>">
                <?= e(mb_substr($r['keterangan'],0,40)).(mb_strlen($r['keterangan'])>40?'…':'') ?>
              </span>
              <?php else: ?><span style="color:var(--text3)">—</span>
              <?php endif ?>
            </td>
            <td style="white-space:nowrap">
              <div style="font-size:12.5px;color:var(--text2)"><?= date('d M Y', strtotime($r['tgl_kejadian'])) ?></div>
              <div style="font-size:11px;color:var(--text3)"><?= date('H:i', strtotime($r['tgl_kejadian'])) ?></div>
            </td>
            <td>
              <a href="index.php?page=riwayat_siswa&siswa_id=<?= $r['siswa_id'] ?>"
                 class="btn btn-outline btn-sm" style="font-size:11.5px;text-decoration:none;white-space:nowrap">
                 📋 Detail
              </a>
            </td>
          </tr>
          <?php endforeach ?>
        </tbody>
      </table>
    </div>
    <?php endif ?>

    <!-- ══ Pagination ══ -->
    <?php if($totalHalaman > 1): ?>
    <div class="riwayat-pager">
      <?php
        $from = ($page-1)*$perPage + 1;
        $to   = min($page*$perPage, $totalRiwayat);
        $baseP = 'index.php?page=riwayat_siswa'
               .($siswaId?'&siswa_id='.$siswaId:'')
               .'&q='.rawurlencode($search)
               .'&jenis='.rawurlencode($filterJenis)
               .'&kelas='.rawurlencode($filterKelas)
               .'&tahun_ajaran='.rawurlencode($filterTahun);
      ?>
      <span class="pager-info">Menampilkan <b><?= $from ?>–<?= $to ?></b> dari <b><?= number_format($totalRiwayat) ?></b></span>
      <div class="pager-btns">
        <a href="<?= $baseP ?>&p=<?= max(1,$page-1) ?>" class="pager-btn <?= $page<=1?'disabled':'' ?>">‹ Prev</a>
        <?php
          $w = 2;
          $wS = max(1, $page-$w); $wE = min($totalHalaman, $page+$w);
          if($wS > 1) { echo '<a href="'.$baseP.'&p=1" class="pager-btn">1</a>'; if($wS>2) echo '<span class="pager-btn disabled">…</span>'; }
          for($pp=$wS;$pp<=$wE;$pp++):
        ?>
        <a href="<?= $baseP ?>&p=<?= $pp ?>" class="pager-btn <?= $pp===$page?'active':'' ?>"><?= $pp ?></a>
        <?php endfor;
          if($wE < $totalHalaman) { if($wE<$totalHalaman-1) echo '<span class="pager-btn disabled">…</span>'; echo '<a href="'.$baseP.'&p='.$totalHalaman.'" class="pager-btn">'.$totalHalaman.'</a>'; }
        ?>
        <a href="<?= $baseP ?>&p=<?= min($totalHalaman,$page+1) ?>" class="pager-btn <?= $page>=$totalHalaman?'disabled':'' ?>">Next ›</a>
      </div>
    </div>
    <?php endif ?>
  </div>
  <?php endif ?>
</div>

<script>
/* ════ Live search siswa ════ */
var _searchTimer = null;
var _avatarColors = <?= json_encode($avatarColors) ?>;

function liveSearchSiswa(q) {
  clearTimeout(_searchTimer);
  var box = document.getElementById('searchResult');
  if (q.length < 2) { box.classList.remove('show'); return; }
  _searchTimer = setTimeout(function() {
    fetch('index.php?page=riwayat_siswa&_ajax=search_siswa&q=' + encodeURIComponent(q))
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (!data.length) { box.classList.remove('show'); return; }
        var html = '';
        data.forEach(function(s, i) {
          var ac = _avatarColors[i % _avatarColors.length];
          html += '<div class="siswa-search-item" onclick="pilihSiswa('+s.id+',\''+s.nama.replace(/'/g,"\\'")+'\')">'
               + '<div class="siswa-search-avatar" style="background:'+ac+'">'+s.nama.charAt(0).toUpperCase()+'</div>'
               + '<div><div style="font-weight:600;font-size:13px">'+s.nama+'</div>'
               + '<div style="font-size:11px;color:#9CA3AF;font-family:monospace">'+s.nis
               + ' &nbsp;·&nbsp; <span class="pill pill-purple" style="font-size:10px;padding:1px 6px">'+s.kelas+' '+s.jurusan+'</span></div>'
               + '</div></div>';
        });
        box.innerHTML = html;
        box.classList.add('show');
      })
      .catch(function() { box.classList.remove('show'); });
  }, 280);
}

function pilihSiswa(id, nama) {
  document.getElementById('searchInput').value = nama;
  document.getElementById('searchResult').classList.remove('show');
  window.location = 'index.php?page=riwayat_siswa&siswa_id=' + id;
}

function goSearch(q) {
  document.getElementById('searchResult').classList.remove('show');
  window.location = 'index.php?page=riwayat_siswa&q=' + encodeURIComponent(q);
}

/* Tutup dropdown saat klik luar */
document.addEventListener('click', function(e) {
  if (!document.getElementById('searchWrap').contains(e.target)) {
    document.getElementById('searchResult').classList.remove('show');
  }
});

/* ════ Apply filter ════ */
function applyFilter() {
  var jenis = document.getElementById('filterJenis').value;
  var kelas = document.getElementById('filterKelas').value;
  var tahun = document.getElementById('filterTahun') ? document.getElementById('filterTahun').value : '';
  var q     = document.getElementById('searchInput').value;
  var url   = 'index.php?page=riwayat_siswa'
            + '&q='           + encodeURIComponent(q)
            + '&jenis='       + encodeURIComponent(jenis)
            + '&kelas='       + encodeURIComponent(kelas)
            + '&tahun_ajaran='+ encodeURIComponent(tahun);
  <?php if($siswaId): ?>
  url += '&siswa_id=<?= $siswaId ?>';
  <?php endif ?>
  window.location = url;
}
</script>

<?php
/* ════ AJAX handler untuk live search ════ */
if (isset($_GET['_ajax']) && $_GET['_ajax'] === 'search_siswa') {
    header('Content-Type: application/json');
    $q = trim($_GET['q'] ?? '');
    if (strlen($q) < 2) { echo '[]'; exit; }
    try {
        $st = $pdo->prepare(
            "SELECT id, nama, nis, kelas, jurusan, status FROM siswa
             WHERE (nama LIKE ? OR nis LIKE ?) AND status='aktif'
             ORDER BY nama LIMIT 10"
        );
        $st->execute(["%$q%", "%$q%"]);
        echo json_encode($st->fetchAll(PDO::FETCH_ASSOC));
    } catch (Exception $e) { echo '[]'; }
    exit;
}
?>

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