<?php
/* ════════════════════════════════════════════════════════════════
   kelas.php  —  Manajemen Data Kelas
   Semua dropdown kelas/jurusan di siswa.php mengambil data dari
   tabel `kelas` yang dikelola di halaman ini.
   ════════════════════════════════════════════════════════════════ */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['action'] ?? '';

    /* ── Tambah kelas ── */
    if ($act === 'tambah') {
        $tingkat     = trim($_POST['tingkat']      ?? '');
        $nama_kelas  = trim($_POST['nama_kelas']   ?? '');
        $wali_kelas  = trim($_POST['wali_kelas']   ?? '');
        $tahun       = trim($_POST['tahun_ajaran'] ?? '');
        $kapasitas   = (int)($_POST['kapasitas']   ?? 0);
        $keterangan  = trim($_POST['keterangan']   ?? '');

        if (!$tingkat || !$nama_kelas || !$tahun) {
            $_SESSION['toast'] = '❌ Tingkat, nama kelas, dan tahun ajaran wajib diisi';
            redirect('index.php?page=kelas');
        }

        /* Cek duplikat: tingkat + nama_kelas + tahun_ajaran */
        $cek = $pdo->prepare("SELECT id FROM kelas WHERE tingkat=? AND nama_kelas=? AND tahun_ajaran=? LIMIT 1");
        $cek->execute([$tingkat, $nama_kelas, $tahun]);
        if ($cek->fetch()) {
            $_SESSION['toast'] = "⚠️ Kelas {$tingkat} {$nama_kelas} tahun {$tahun} sudah ada";
            redirect('index.php?page=kelas');
        }

        $pdo->prepare(
            "INSERT INTO kelas (tingkat, nama_kelas, wali_kelas, tahun_ajaran, kapasitas, keterangan, status)
             VALUES (?, ?, ?, ?, ?, ?, 'aktif')"
        )->execute([$tingkat, $nama_kelas, $wali_kelas, $tahun, $kapasitas ?: null, $keterangan]);

        $_SESSION['toast'] = "✅ Kelas {$tingkat} {$nama_kelas} berhasil ditambahkan";
        redirect('index.php?page=kelas');
    }

    /* ══════════════════════════════════════════════════════════
       EDIT KELAS — dengan opsi sinkronisasi tahun ajaran siswa
    ══════════════════════════════════════════════════════════ */
    if ($act === 'edit') {
        $id          = (int)($_POST['id']          ?? 0);
        $tingkat     = trim($_POST['tingkat']      ?? '');
        $nama_kelas  = trim($_POST['nama_kelas']   ?? '');
        $wali_kelas  = trim($_POST['wali_kelas']   ?? '');
        $tahun       = trim($_POST['tahun_ajaran'] ?? '');
        $kapasitas   = (int)($_POST['kapasitas']   ?? 0);
        $keterangan  = trim($_POST['keterangan']   ?? '');
        $status      = in_array($_POST['status'] ?? '', ['aktif','nonaktif']) ? $_POST['status'] : 'aktif';
        $sinkron     = ($_POST['sinkron_siswa'] ?? '0') === '1';

        /* Ambil data lama untuk mendeteksi perubahan tahun ajaran */
        $lama = $pdo->prepare("SELECT tingkat, nama_kelas, tahun_ajaran FROM kelas WHERE id=? LIMIT 1");
        $lama->execute([$id]);
        $kelasLama = $lama->fetch();

        /* Cek duplikat kecuali diri sendiri */
        $cek = $pdo->prepare("SELECT id FROM kelas WHERE tingkat=? AND nama_kelas=? AND tahun_ajaran=? AND id!=? LIMIT 1");
        $cek->execute([$tingkat, $nama_kelas, $tahun, $id]);
        if ($cek->fetch()) {
            $_SESSION['toast'] = "⚠️ Kelas {$tingkat} {$nama_kelas} tahun {$tahun} sudah ada";
            redirect('index.php?page=kelas');
        }

        $pdo->prepare(
            "UPDATE kelas SET tingkat=?, nama_kelas=?, wali_kelas=?, tahun_ajaran=?,
             kapasitas=?, keterangan=?, status=? WHERE id=?"
        )->execute([$tingkat, $nama_kelas, $wali_kelas, $tahun, $kapasitas ?: null, $keterangan, $status, $id]);

        /* ── Sinkronisasi tahun ajaran ke siswa ── */
        $jumlahSinkron = 0;
        if ($sinkron && $kelasLama && $tahun !== $kelasLama['tahun_ajaran']) {
            /* Gunakan tingkat+nama_kelas LAMA sebagai kunci pencarian siswa
               (karena tingkat/nama_kelas mungkin juga ikut berubah) */
            $stmtSinkron = $pdo->prepare(
                "UPDATE siswa
                 SET tahun_ajaran = ?
                 WHERE kelas   COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
                   AND jurusan COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
                   AND status  = 'aktif'"
            );
            $stmtSinkron->execute([$tahun, $kelasLama['tingkat'], $kelasLama['nama_kelas']]);
            $jumlahSinkron = $stmtSinkron->rowCount();
        }

        $msgSinkron = $jumlahSinkron > 0 ? " — {$jumlahSinkron} siswa ikut diperbarui" : '';
        $_SESSION['toast'] = "✅ Kelas {$tingkat} {$nama_kelas} berhasil diperbarui{$msgSinkron}";
        redirect('index.php?page=kelas');
    }

    /* ══════════════════════════════════════════════════════════
       SINKRON MASSAL — perbarui tahun ajaran SEMUA siswa
       berdasarkan kelas yang mereka tempati saat ini,
       dan update pengaturan.tahun_ajaran ke nilai terbaru
    ══════════════════════════════════════════════════════════ */
    if ($act === 'sinkron_massal') {
        $filterTkt  = trim($_POST['filter_tingkat']      ?? '');
        $filterThn  = trim($_POST['filter_tahun_sumber'] ?? '');

        /* Ambil semua kelas aktif sesuai filter */
        $sqlKelas = "SELECT tingkat, nama_kelas, tahun_ajaran FROM kelas WHERE status='aktif'";
        $paramsK  = [];
        if ($filterTkt) { $sqlKelas .= " AND tingkat=?";       $paramsK[] = $filterTkt; }
        if ($filterThn) { $sqlKelas .= " AND tahun_ajaran=?";  $paramsK[] = $filterThn; }
        $stmtK = $pdo->prepare($sqlKelas);
        $stmtK->execute($paramsK);
        $kelasSinkron = $stmtK->fetchAll();

        $totalUpdate    = 0;
        $tahunTerbaru   = '';

        $stmtUp = $pdo->prepare(
            "UPDATE siswa
             SET tahun_ajaran = ?
             WHERE kelas   COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
               AND jurusan COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
               AND status  = 'aktif'
               AND tahun_ajaran != ?"
        );
        foreach ($kelasSinkron as $kr) {
            $stmtUp->execute([$kr['tahun_ajaran'], $kr['tingkat'], $kr['nama_kelas'], $kr['tahun_ajaran']]);
            $totalUpdate += $stmtUp->rowCount();
            /* Catat tahun terbaru (nilai terbesar secara string, misal 2025/2026 > 2024/2025) */
            if ($kr['tahun_ajaran'] > $tahunTerbaru) {
                $tahunTerbaru = $kr['tahun_ajaran'];
            }
        }

        /* Update pengaturan.tahun_ajaran ke tahun terbaru dari kelas
           — hanya jika tidak ada filter khusus (sinkron semua) */
        if (!$filterTkt && !$filterThn && $tahunTerbaru) {
            try {
                $cekPg = $pdo->prepare("SELECT id FROM pengaturan WHERE kunci='tahun_ajaran' LIMIT 1");
                $cekPg->execute();
                if ($cekPg->fetch()) {
                    $pdo->prepare("UPDATE pengaturan SET nilai=? WHERE kunci='tahun_ajaran'")->execute([$tahunTerbaru]);
                } else {
                    $pdo->prepare("INSERT INTO pengaturan (kunci,nilai,keterangan) VALUES ('tahun_ajaran',?,'Tahun ajaran aktif')")->execute([$tahunTerbaru]);
                }
            } catch (Exception $e) { /* abaikan jika tabel pengaturan belum ada */ }
        }

        $_SESSION['toast'] = $totalUpdate > 0
            ? "🔄 Sinkronisasi selesai: {$totalUpdate} data siswa berhasil diperbarui"
            : "✅ Semua data siswa sudah sinkron, tidak ada yang perlu diperbarui";
        redirect('index.php?page=kelas');
    }

    /* ── Hapus kelas ── */
    if ($act === 'hapus') {
        $id = (int)($_POST['id'] ?? 0);
        /* Cek apakah masih ada siswa di kelas ini */
        $k = $pdo->prepare("SELECT tingkat, nama_kelas FROM kelas WHERE id=? LIMIT 1");
        $k->execute([$id]);
        $kRow = $k->fetch();
        if ($kRow) {
            $cekSiswa = $pdo->prepare(
                "SELECT COUNT(*) FROM siswa
                 WHERE kelas   COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
                   AND jurusan COLLATE utf8mb4_general_ci = ? COLLATE utf8mb4_general_ci
                   AND status = 'aktif'"
            );
            $cekSiswa->execute([$kRow['tingkat'], $kRow['nama_kelas']]);
            if ($cekSiswa->fetchColumn() > 0) {
                $_SESSION['toast'] = '❌ Tidak dapat dihapus — masih ada siswa aktif di kelas ini';
                redirect('index.php?page=kelas');
            }
        }
        $pdo->prepare("DELETE FROM kelas WHERE id=?")->execute([$id]);
        $_SESSION['toast'] = '🗑️ Kelas berhasil dihapus';
        redirect('index.php?page=kelas');
    }

    /* ── Toggle status aktif/nonaktif ── */
    if ($act === 'toggle_status') {
        $id  = (int)($_POST['id']         ?? 0);
        $now = trim($_POST['status_now']  ?? 'aktif');
        $new = $now === 'aktif' ? 'nonaktif' : 'aktif';
        $pdo->prepare("UPDATE kelas SET status=? WHERE id=?")->execute([$new, $id]);
        $_SESSION['toast'] = $new === 'aktif' ? '✅ Kelas diaktifkan' : '⛔ Kelas dinonaktifkan';
        redirect('index.php?page=kelas');
    }

    redirect('index.php?page=kelas');
}

/* ════ Pastikan tabel kelas ada — buat otomatis jika belum ════ */
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `kelas` (
        `id`           INT          NOT NULL AUTO_INCREMENT,
        `tingkat`      VARCHAR(5)   CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'X / XI / XII',
        `nama_kelas`   VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        `wali_kelas`   VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `tahun_ajaran` VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        `kapasitas`    TINYINT UNSIGNED DEFAULT NULL,
        `keterangan`   TEXT         CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        `status`       VARCHAR(10)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'aktif',
        `created_at`   TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at`   TIMESTAMP    NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        UNIQUE KEY `uq_kelas` (`tingkat`, `nama_kelas`, `tahun_ajaran`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
} catch (Exception $e) { /* abaikan jika sudah ada */ }

/* Jika tabel sudah ada tapi pakai collation lama (unicode_ci), perbaiki otomatis */
try {
    $pdo->exec("ALTER TABLE `kelas`
        MODIFY `tingkat`      VARCHAR(5)   CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        MODIFY `nama_kelas`   VARCHAR(30)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        MODIFY `wali_kelas`   VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        MODIFY `tahun_ajaran` VARCHAR(20)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
        MODIFY `keterangan`   TEXT         CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
        MODIFY `status`       VARCHAR(10)  CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'aktif'
    ");
} catch (Exception $e) { /* abaikan — kolom mungkin sudah benar */ }

require_once 'layout/header.php';

/* ════ Query data ════ */
$filterTingkat = trim($_GET['tingkat']       ?? '');
$filterTahun   = trim($_GET['tahun_ajaran']  ?? '');
$filterStatus  = trim($_GET['status']        ?? 'aktif');
$search        = trim($_GET['q']             ?? '');

$kelasList     = [];
$statByTingkat = [];
$tahunList     = [];
$totalAktif    = 0;
$totalNonaktif = 0;
$totalSiswaAktif    = 0;
$totalTidakSinkron  = 0;
$_tabelError   = false;

try {
    $sql    = "SELECT k.*,
               (SELECT COUNT(*) FROM siswa s
                WHERE s.kelas   COLLATE utf8mb4_general_ci = k.tingkat    COLLATE utf8mb4_general_ci
                  AND s.jurusan COLLATE utf8mb4_general_ci = k.nama_kelas COLLATE utf8mb4_general_ci
                  AND s.status = 'aktif') AS jml_siswa
               FROM kelas k WHERE k.status=?";
    $params = [$filterStatus];
    if ($filterTingkat) { $sql .= " AND k.tingkat=?";       $params[] = $filterTingkat; }
    if ($filterTahun)   { $sql .= " AND k.tahun_ajaran=?";  $params[] = $filterTahun; }
    if ($search)        { $sql .= " AND (k.nama_kelas LIKE ? OR k.wali_kelas LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
    $sql .= " ORDER BY FIELD(k.tingkat,'X','XI','XII'), k.nama_kelas";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $kelasList = $stmt->fetchAll();

    /* Statistik per tingkat */
    $statRaw = $pdo->query(
        "SELECT tingkat, status, COUNT(*) as total FROM kelas GROUP BY tingkat, status"
    )->fetchAll();
    foreach ($statRaw as $r) {
        $statByTingkat[$r['tingkat']][$r['status']] = (int)$r['total'];
    }

    $tahunList     = $pdo->query("SELECT DISTINCT tahun_ajaran FROM kelas ORDER BY tahun_ajaran DESC")->fetchAll(PDO::FETCH_COLUMN);
    $totalAktif    = (int)$pdo->query("SELECT COUNT(*) FROM kelas WHERE status='aktif'")->fetchColumn();
    $totalNonaktif = (int)$pdo->query("SELECT COUNT(*) FROM kelas WHERE status='nonaktif'")->fetchColumn();

    try {
        $totalSiswaAktif = (int)$pdo->query("SELECT COUNT(*) FROM siswa WHERE status='aktif'")->fetchColumn();
    } catch (Exception $e) { $totalSiswaAktif = 0; }

    /* Hitung siswa yang tahun ajarannya BELUM SINKRON dengan kelasnya */
    try {
        $stmtNotSync = $pdo->query(
            "SELECT COUNT(*) FROM siswa s
             INNER JOIN kelas k
               ON k.tingkat    COLLATE utf8mb4_general_ci = s.kelas   COLLATE utf8mb4_general_ci
              AND k.nama_kelas COLLATE utf8mb4_general_ci = s.jurusan COLLATE utf8mb4_general_ci
              AND k.status = 'aktif'
             WHERE s.status = 'aktif'
               AND s.tahun_ajaran COLLATE utf8mb4_general_ci != k.tahun_ajaran COLLATE utf8mb4_general_ci"
        );
        $totalTidakSinkron = (int)$stmtNotSync->fetchColumn();
    } catch (Exception $e) { $totalTidakSinkron = 0; }

} catch (Exception $e) {
    $_tabelError = $e->getMessage();
}

$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
$tingkatList = ['X', 'XI', 'XII'];

/* Warna per tingkat */
$tingkatColor = ['X' => '#7C3AED', 'XI' => '#0369A1', 'XII' => '#059669'];
$tingkatBg    = ['X' => '#F5F3FF', 'XI' => '#E0F2FE', 'XII' => '#ECFDF5'];
$tingkatPill  = ['X' => 'pill-purple', 'XI' => 'pill-blue', 'XII' => 'pill-green'];
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
/* ══ Kelas Card Grid ══ */
.kelas-grid {
  display:grid;
  grid-template-columns:repeat(auto-fill, minmax(300px, 1fr));
  gap:14px;
  padding:16px;
}

.kelas-card {
  background:var(--surface,#fff);
  border:1.5px solid var(--border);
  border-radius:16px;
  overflow:hidden;
  display:flex;
  flex-direction:column;
  transition:box-shadow .18s, transform .18s;
  animation:kelasCardIn .22s ease both;
}
.kelas-card:hover {
  box-shadow:0 6px 24px rgba(0,0,0,.09);
  transform:translateY(-3px);
}
@keyframes kelasCardIn {
  from { opacity:0; transform:translateY(12px) }
  to   { opacity:1; transform:translateY(0) }
}

.kelas-card-head {
  padding:14px 16px 12px;
  display:flex;
  align-items:flex-start;
  gap:12px;
  border-bottom:1px solid var(--border);
}
.kelas-card-badge {
  width:46px; height:46px;
  border-radius:12px;
  display:flex; flex-direction:column;
  align-items:center; justify-content:center;
  flex-shrink:0;
  font-weight:800; line-height:1;
}
.kelas-card-badge-tingkat { font-size:15px; }
.kelas-card-badge-nama    { font-size:10px; opacity:.75; margin-top:1px; }

.kelas-card-info    { flex:1; min-width:0; }
.kelas-card-title   { font-weight:700; font-size:15px; color:var(--text); line-height:1.2; }
.kelas-card-sub     { font-size:12px; color:var(--text3); margin-top:3px; }
.kelas-card-status  { flex-shrink:0; }

.kelas-card-body  { padding:12px 16px; display:flex; flex-direction:column; gap:8px; flex:1; }
.kelas-card-row   { display:flex; align-items:center; justify-content:space-between; font-size:12.5px; }
.kelas-card-label { color:var(--text3); display:flex; align-items:center; gap:5px; font-size:12px; }

.kelas-card-footer {
  padding:10px 16px 13px;
  border-top:1px solid var(--border);
  background:var(--surface2,#f8fafc);
  display:flex; gap:6px; flex-wrap:wrap;
}
.kelas-card-footer .btn { flex:1; justify-content:center; font-size:12px; }

/* ══ Kapasitas bar ══ */
.kelas-kapasitas-wrap {
  display:flex; align-items:center; gap:8px; font-size:12px;
}
.kelas-kapasitas-bar {
  flex:1; height:6px; background:var(--border);
  border-radius:99px; overflow:hidden;
}
.kelas-kapasitas-fill {
  height:100%; border-radius:99px;
  transition:width .4s ease;
}

/* ══ Tingkat filter tabs ══ */
.tingkat-tabs {
  display:flex; gap:4px; flex-wrap:wrap;
  background:var(--surface2); border:1.5px solid var(--border);
  border-radius:12px; padding:5px 8px; width:100%;
}
.tingkat-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;
}
.tingkat-tab:hover {
  background:var(--surface); color:var(--candy-purple,#7C3AED);
  box-shadow:0 1px 4px rgba(0,0,0,.07);
}
.tingkat-tab.active {
  background:var(--candy-purple,#7C3AED); color:#fff;
  box-shadow:0 2px 8px rgba(124,58,237,.2);
}
.tingkat-tab-count {
  background:rgba(255,255,255,.25); color:inherit;
  border-radius:99px; font-size:10px; font-weight:700;
  padding:0 6px; min-width:16px; text-align:center; line-height:1.6;
}
.tingkat-tab:not(.active) .tingkat-tab-count {
  background:var(--surface); color:var(--candy-purple,#7C3AED);
}

/* ══ Stats bar ══ */
.kelas-stats-bar {
  display:grid;
  grid-template-columns:repeat(auto-fill, minmax(130px, 1fr));
  gap:10px; margin-bottom:16px;
}
.kelas-stat-card {
  background:var(--surface); border:1.5px solid var(--border);
  border-radius:12px; padding:12px 14px;
  display:flex; flex-direction:column; gap:4px;
}
.kelas-stat-num   { font-size:22px; font-weight:800; line-height:1; }
.kelas-stat-label { font-size:11px; color:var(--text2); font-weight:500; }

/* ══ Table view ══ */
.kelas-tbl-scroll {
  overflow-x:auto; overflow-y:auto; max-height:520px;
  scrollbar-width:thin; scrollbar-color:var(--border) transparent;
}
.kelas-tbl-scroll::-webkit-scrollbar { width:5px; height:5px; }
.kelas-tbl-scroll::-webkit-scrollbar-thumb { background:var(--border); border-radius:99px; }
.kelas-tbl-scroll thead { position:sticky; top:0; z-index:2; }
.kelas-tbl-scroll thead th { box-shadow:0 1.5px 0 var(--border); }

/* ══ View toggle ══ */
.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; white-space:nowrap; font-family:inherit;
}
.view-toggle button.active {
  background:var(--surface); color:var(--candy-purple,#7C3AED);
  box-shadow:0 1px 4px rgba(0,0,0,.08);
}

/* ══ Pagination ══ */
.kelas-pager {
  display:flex; align-items:center; justify-content:space-between;
  flex-wrap:wrap; gap:8px;
  padding:12px 16px;
  border-top:1px solid var(--border);
  background:var(--surface2,#f8fafc);
}
.kelas-pager-info { font-size:12.5px; color:var(--text2); }
.kelas-pager-btns { display:flex; gap:4px; align-items:center; flex-wrap:wrap; }
.kelas-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:inherit; transition:all .15s;
  display:inline-flex; align-items:center; justify-content:center;
}
.kelas-pager-btn:hover:not(.disabled):not(.active) {
  background:var(--surface2); border-color:var(--candy-purple,#7C3AED); color:var(--candy-purple,#7C3AED);
}
.kelas-pager-btn.active {
  background:var(--candy-purple,#7C3AED); color:#fff;
  border-color:var(--candy-purple,#7C3AED); font-weight:700;
  box-shadow:0 2px 8px rgba(124,58,237,.25);
}
.kelas-pager-btn.disabled { opacity:.38; cursor:not-allowed; }
.kelas-pager-ellipsis { font-size:13px; color:var(--text3); padding:0 3px; user-select:none; }
</style>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title">🏫 Manajemen Kelas</div>
    <div class="page-header-sub"><?= count($kelasList) ?> kelas ditemukan</div>
  </div>
  <button class="btn btn-primary" onclick="openModal('modalTambah')">➕ Tambah Kelas</button>
</div>

<?php if($_tabelError): ?>
<div style="background:#FEF3C7;border:1.5px solid #FCD34D;border-radius:12px;padding:14px 18px;margin-bottom:16px;font-size:13px;color:#92400E">
  ⚠️ <strong>Tabel kelas belum siap.</strong> Jalankan file <code>kelas_schema.sql</code> di database Anda, lalu muat ulang halaman ini.<br>
  <span style="font-size:11px;opacity:.7;margin-top:4px;display:block">Detail: <?= htmlspecialchars($_tabelError) ?></span>
</div>
<?php endif ?>

<!-- Stats Bar -->
<div class="kelas-stats-bar">
  <?php
  $totalKelasAktif = (int)$totalAktif;
  foreach (['X','XI','XII'] as $tkt):
    $jml = ($statByTingkat[$tkt]['aktif'] ?? 0);
    $clr = $tingkatColor[$tkt];
  ?>
  <div class="kelas-stat-card">
    <div class="kelas-stat-num" style="color:<?= $clr ?>"><?= $jml ?></div>
    <div class="kelas-stat-label">Kelas <?= $tkt ?> aktif</div>
  </div>
  <?php endforeach ?>
  <div class="kelas-stat-card">
    <div class="kelas-stat-num" style="color:#7C3AED"><?= $totalKelasAktif ?></div>
    <div class="kelas-stat-label">Total kelas aktif</div>
  </div>
  <div class="kelas-stat-card">
    <div class="kelas-stat-num" style="color:#059669"><?= $totalSiswaAktif ?></div>
    <div class="kelas-stat-label">Siswa terdaftar</div>
  </div>
</div>

<!-- ══ Banner Sinkronisasi ══ -->
<?php if($totalTidakSinkron > 0): ?>
<div style="background:linear-gradient(135deg,#FEF3C7,#FDE68A);border:1.5px solid #FCD34D;border-radius:14px;padding:16px 20px;margin-bottom:16px;display:flex;align-items:center;gap:14px;flex-wrap:wrap;box-shadow:0 2px 12px rgba(245,158,11,.15)">
  <div style="font-size:28px;flex-shrink:0">⚠️</div>
  <div style="flex:1;min-width:0">
    <div style="font-weight:700;font-size:14px;color:#92400E;margin-bottom:3px">
      <?= $totalTidakSinkron ?> siswa belum sinkron tahun ajaran
    </div>
    <div style="font-size:12.5px;color:#B45309">
      Tahun ajaran siswa tersebut berbeda dengan kelas yang mereka tempati sekarang.
      Klik tombol untuk menyinkronkan sekaligus.
    </div>
  </div>
  <button class="btn" onclick="openModal('modalSinkronMassal')"
          style="background:#D97706;color:#fff;font-weight:700;font-size:13px;border:none;box-shadow:0 2px 8px rgba(217,119,6,.3);white-space:nowrap;flex-shrink:0">
    🔄 Sinkronkan Sekarang
  </button>
</div>
<?php else: ?>
<div style="background:linear-gradient(135deg,#ECFDF5,#D1FAE5);border:1.5px solid #6EE7B7;border-radius:14px;padding:13px 18px;margin-bottom:16px;display:flex;align-items:center;gap:10px">
  <span style="font-size:20px">✅</span>
  <div style="font-size:13px;color:#065F46;font-weight:500">
    Semua data siswa sudah sinkron dengan tahun ajaran kelasnya.
  </div>
  <button class="btn btn-outline btn-sm" onclick="openModal('modalSinkronMassal')"
          style="margin-left:auto;font-size:12px;border-color:#059669;color:#059669;flex-shrink:0">
    🔄 Sinkronkan Ulang
  </button>
</div>
<?php endif ?>

<!-- Toolbar -->
<div class="toolbar" style="margin-bottom:10px;flex-wrap:wrap;gap:10px">
  <div class="search-box" style="flex:1;min-width:180px">
    <form method="GET" action="index.php" style="margin:0">
      <input type="hidden" name="page" value="kelas">
      <input type="hidden" name="tingkat"      value="<?= e($filterTingkat) ?>">
      <input type="hidden" name="tahun_ajaran" value="<?= e($filterTahun) ?>">
      <input type="hidden" name="status"       value="<?= e($filterStatus) ?>">
      <input type="text" name="q" value="<?= e($search) ?>" placeholder="Cari nama kelas atau wali kelas...">
    </form>
  </div>

  <!-- Filter tahun ajaran -->
  <?php if($tahunList): ?>
  <form method="GET" action="index.php" style="margin:0;display:flex;gap:6px;align-items:center">
    <input type="hidden" name="page"    value="kelas">
    <input type="hidden" name="tingkat" value="<?= e($filterTingkat) ?>">
    <input type="hidden" name="status"  value="<?= e($filterStatus) ?>">
    <input type="hidden" name="q"       value="<?= e($search) ?>">
    <select name="tahun_ajaran" onchange="this.form.submit()"
            style="padding:7px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);font-family:inherit;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>
  </form>
  <?php endif ?>

  <!-- Status toggle -->
  <div style="display:flex;gap:4px;background:var(--surface2);border-radius:10px;padding:4px">
    <?php
    $baseQ = '?page=kelas&tingkat='.rawurlencode($filterTingkat).'&tahun_ajaran='.rawurlencode($filterTahun).'&q='.rawurlencode($search);
    foreach (['aktif'=>'✅ Aktif','nonaktif'=>'⛔ Nonaktif'] as $sv=>$sl):
      $cnt = $sv === 'aktif' ? $totalAktif : $totalNonaktif;
      $isActive = $filterStatus === $sv;
    ?>
    <a href="index.php<?= $baseQ ?>&status=<?= $sv ?>"
       style="padding:6px 13px;border-radius:7px;font-size:12.5px;font-weight:700;text-decoration:none;transition:.15s;
              <?= $isActive ? 'background:#fff;color:var(--candy-purple);box-shadow:0 1px 6px rgba(0,0,0,.10)' : 'color:var(--text2)' ?>">
      <?= $sl ?> <span style="background:var(--surface2);border-radius:99px;padding:1px 7px;font-size:11px;margin-left:2px"><?= $cnt ?></span>
    </a>
    <?php endforeach ?>
  </div>

  <!-- View toggle -->
  <div class="view-toggle">
    <button id="kelas-btn-cards" class="active" onclick="kelasSwitchView('cards')">
      <svg width="14" height="14" 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="kelas-btn-table" onclick="kelasSwitchView('table')">
      <svg width="14" height="14" 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>

<!-- Tingkat Tabs -->
<div style="margin-bottom:14px">
  <div class="tingkat-tabs">
    <?php
    $baseQT = 'index.php?page=kelas&status='.rawurlencode($filterStatus).'&tahun_ajaran='.rawurlencode($filterTahun).'&q='.rawurlencode($search);
    $totalAllTingkat = array_sum(array_column(array_map(fn($t) => ['n' => ($statByTingkat[$t]['aktif'] ?? 0) + ($statByTingkat[$t]['nonaktif'] ?? 0)], $tingkatList), 'n'));
    ?>
    <a href="<?= $baseQT ?>&tingkat=" class="tingkat-tab <?= !$filterTingkat ? 'active' : '' ?>">
      🏫 Semua
      <span class="tingkat-tab-count"><?= $totalAktif + $totalNonaktif ?></span>
    </a>
    <?php foreach ($tingkatList as $tkt):
      $cnt = ($statByTingkat[$tkt]['aktif'] ?? 0) + ($statByTingkat[$tkt]['nonaktif'] ?? 0);
    ?>
    <a href="<?= $baseQT ?>&tingkat=<?= rawurlencode($tkt) ?>" class="tingkat-tab <?= $filterTingkat===$tkt?'active':'' ?>">
      Kelas <?= $tkt ?>
      <span class="tingkat-tab-count"><?= $cnt ?></span>
    </a>
    <?php endforeach ?>
  </div>
</div>

<!-- ══════════ CARD WRAPPER ══════════ -->
<div class="card" style="padding:0;overflow:visible">
  <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 Kelas
      <?php if(count($kelasList)): ?>
        <span class="pill pill-purple"><?= count($kelasList) ?> kelas</span>
      <?php endif ?>
    </div>
    <div style="display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--text2)">
      Tampil
      <select id="kelasPerPage" onchange="kelasOnPerPage(this.value)"
              style="padding:4px 8px;border:1.5px solid var(--border);border-radius:7px;font-size:12px;background:var(--surface);color:var(--text);font-family:inherit;cursor:pointer">
        <option value="10" selected>10</option>
        <option value="20">20</option>
        <option value="50">50</option>
        <option value="999">Semua</option>
      </select>
      / hal
    </div>
  </div>

  <?php if(empty($kelasList)): ?>
    <div style="padding:48px 24px">
      <div class="empty-state">
        <div class="empty-state-icon">🏫</div>
        <h4>Belum ada data kelas</h4>
        <p>Klik "Tambah Kelas" untuk mulai membuat kelas baru</p>
      </div>
    </div>

  <?php else: ?>

  <!-- ══ CARD VIEW ══ -->
  <div id="kelas-view-cards">
    <div class="kelas-grid" id="kelasCardsGrid">
      <?php foreach($kelasList as $i => $k):
        $clr    = $tingkatColor[$k['tingkat']] ?? '#7C3AED';
        $bg     = $tingkatBg[$k['tingkat']]    ?? '#F5F3FF';
        $pill   = $tingkatPill[$k['tingkat']]  ?? 'pill-purple';
        $pct    = $k['kapasitas'] ? min(100, round($k['jml_siswa'] / $k['kapasitas'] * 100)) : null;
        $pctClr = $pct === null ? '#7C3AED' : ($pct >= 90 ? '#DC2626' : ($pct >= 70 ? '#D97706' : '#059669'));
        $isAktif= $k['status'] === 'aktif';
      ?>
      <div class="kelas-card" data-card="<?= $i ?>" style="animation-delay:<?= $i * 30 ?>ms;border-top:3px solid <?= $clr ?>">
        <div class="kelas-card-head">
          <div class="kelas-card-badge" style="background:<?= $bg ?>;color:<?= $clr ?>">
            <div class="kelas-card-badge-tingkat"><?= e($k['tingkat']) ?></div>
            <div class="kelas-card-badge-nama"><?= e($k['nama_kelas']) ?></div>
          </div>
          <div class="kelas-card-info">
            <div class="kelas-card-title">Kelas <?= e($k['tingkat']) ?> <?= e($k['nama_kelas']) ?></div>
            <div class="kelas-card-sub">📅 <?= e($k['tahun_ajaran']) ?></div>
          </div>
          <div class="kelas-card-status">
            <?php if($isAktif): ?>
              <span class="badge badge-success" style="font-size:10.5px;padding:2px 7px">✅ Aktif</span>
            <?php else: ?>
              <span class="badge badge-danger" style="font-size:10.5px;padding:2px 7px">⛔ Nonaktif</span>
            <?php endif ?>
          </div>
        </div>

        <div class="kelas-card-body">
          <!-- Wali kelas -->
          <div class="kelas-card-row">
            <span class="kelas-card-label">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
              Wali Kelas
            </span>
            <span style="font-size:12.5px;color:var(--text);font-weight:500"><?= e($k['wali_kelas'] ?: '—') ?></span>
          </div>

          <!-- Jumlah siswa / kapasitas -->
          <div class="kelas-card-row" style="flex-direction:column;align-items:stretch;gap:5px">
            <div style="display:flex;justify-content:space-between;font-size:12px">
              <span class="kelas-card-label">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
                Siswa
              </span>
              <span style="font-weight:700;color:<?= $pctClr ?>">
                <?= $k['jml_siswa'] ?>
                <?php if($k['kapasitas']): ?> / <?= $k['kapasitas'] ?><?php endif ?>
              </span>
            </div>
            <?php if($k['kapasitas']): ?>
            <div class="kelas-kapasitas-bar">
              <div class="kelas-kapasitas-fill" style="width:<?= $pct ?>%;background:<?= $pctClr ?>"></div>
            </div>
            <?php endif ?>
          </div>

          <?php if($k['keterangan']): ?>
          <div style="font-size:11.5px;color:var(--text3);background:var(--surface2);border-radius:7px;padding:6px 10px;line-height:1.5">
            💬 <?= e($k['keterangan']) ?>
          </div>
          <?php endif ?>
        </div>

        <div class="kelas-card-footer">
          <button class="btn btn-outline btn-sm" onclick='isiFormEditKelas(<?= json_encode($k) ?>)' style="font-size:11.5px">✏️ Edit</button>
          <a href="index.php?page=siswa&kelas=<?= rawurlencode($k['tingkat']) ?>&jurusan=<?= rawurlencode($k['nama_kelas']) ?>"
             class="btn btn-outline btn-sm" style="font-size:11.5px;text-decoration:none;display:inline-flex;align-items:center;gap:4px">
            👥 Lihat Siswa
            <?php if($k['jml_siswa']): ?><span class="pill pill-purple" style="font-size:10px;padding:1px 6px"><?= $k['jml_siswa'] ?></span><?php endif ?>
          </a>
          <form method="POST" onsubmit="return confirm('<?= $isAktif ? 'Nonaktifkan' : 'Aktifkan' ?> kelas ini?')">
            <input type="hidden" name="action"     value="toggle_status">
            <input type="hidden" name="id"         value="<?= $k['id'] ?>">
            <input type="hidden" name="status_now" value="<?= $k['status'] ?>">
            <button class="btn btn-sm" type="submit"
                    style="font-size:11.5px;<?= $isAktif ? 'background:#FEF3C7;color:#92400E;border:none' : 'background:#D1FAE5;color:#065F46;border:none' ?>">
              <?= $isAktif ? '⛔' : '✅' ?>
            </button>
          </form>
          <form method="POST" onsubmit="return confirm('Hapus kelas ini? Data tidak dapat dikembalikan.')">
            <input type="hidden" name="action" value="hapus">
            <input type="hidden" name="id"     value="<?= $k['id'] ?>">
            <button class="btn btn-danger btn-sm" type="submit" style="font-size:11.5px">🗑️</button>
          </form>
        </div>
      </div>
      <?php endforeach ?>
    </div>
  <div id="pager-kelas-cards"></div>
  </div><!-- /kelas-view-cards -->

  <!-- ══ TABLE VIEW ══ -->
  <div id="kelas-view-table" style="display:none">
    <div class="kelas-tbl-scroll">
      <table>
        <thead>
          <tr>
            <th>#</th>
            <th>Tingkat</th>
            <th>Nama Kelas</th>
            <th>Wali Kelas</th>
            <th>Tahun Ajaran</th>
            <th>Siswa / Kapasitas</th>
            <th>Status</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($kelasList as $i => $k):
            $clr    = $tingkatColor[$k['tingkat']] ?? '#7C3AED';
            $pct    = $k['kapasitas'] ? min(100, round($k['jml_siswa'] / $k['kapasitas'] * 100)) : null;
            $pctClr = $pct === null ? '#7C3AED' : ($pct >= 90 ? '#DC2626' : ($pct >= 70 ? '#D97706' : '#059669'));
            $isAktif= $k['status'] === 'aktif';
          ?>
          <tr data-row="<?= $i ?>">
            <td><div style="width:26px;height:26px;border-radius:8px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--text2)"><?= $i+1 ?></div></td>
            <td><span class="pill <?= $tingkatPill[$k['tingkat']] ?? 'pill-purple' ?>"><?= e($k['tingkat']) ?></span></td>
            <td>
              <div style="font-weight:700;font-size:13.5px"><?= e($k['tingkat']) ?> <?= e($k['nama_kelas']) ?></div>
              <?php if($k['keterangan']): ?>
                <div style="font-size:11px;color:var(--text3);margin-top:2px"><?= e($k['keterangan']) ?></div>
              <?php endif ?>
            </td>
            <td style="font-size:13px;color:var(--text2)"><?= e($k['wali_kelas'] ?: '—') ?></td>
            <td style="font-size:13px;color:var(--text2)"><?= e($k['tahun_ajaran']) ?></td>
            <td>
              <div style="display:flex;align-items:center;gap:8px;min-width:100px">
                <span style="font-weight:700;color:<?= $pctClr ?>;font-size:13px">
                  <?= $k['jml_siswa'] ?><?php if($k['kapasitas']): ?>/<?= $k['kapasitas'] ?><?php endif ?>
                </span>
                <?php if($k['kapasitas']): ?>
                <div class="kelas-kapasitas-bar" style="flex:1;min-width:50px">
                  <div class="kelas-kapasitas-fill" style="width:<?= $pct ?>%;background:<?= $pctClr ?>"></div>
                </div>
                <?php endif ?>
              </div>
            </td>
            <td>
              <?php if($isAktif): ?>
                <span class="badge badge-success">✅ Aktif</span>
              <?php else: ?>
                <span class="badge badge-danger">⛔ Nonaktif</span>
              <?php endif ?>
            </td>
            <td>
              <div style="display:flex;gap:5px;align-items:center;flex-wrap:nowrap">
                <button class="btn btn-outline btn-sm" onclick='isiFormEditKelas(<?= json_encode($k) ?>)'>✏️</button>
                <a href="index.php?page=siswa&kelas=<?= rawurlencode($k['tingkat']) ?>&jurusan=<?= rawurlencode($k['nama_kelas']) ?>"
                   class="btn btn-outline btn-sm" style="text-decoration:none" title="Lihat siswa">👥</a>
                <form method="POST" style="display:inline" onsubmit="return confirm('<?= $isAktif ? 'Nonaktifkan' : 'Aktifkan' ?> kelas ini?')">
                  <input type="hidden" name="action"     value="toggle_status">
                  <input type="hidden" name="id"         value="<?= $k['id'] ?>">
                  <input type="hidden" name="status_now" value="<?= $k['status'] ?>">
                  <button class="btn btn-sm" type="submit"
                          style="<?= $isAktif ? 'background:#FEF3C7;color:#92400E;border:none' : 'background:#D1FAE5;color:#065F46;border:none' ?>">
                    <?= $isAktif ? '🚫' : '✅' ?>
                  </button>
                </form>
                <form method="POST" style="display:inline" onsubmit="return confirm('Hapus kelas ini?')">
                  <input type="hidden" name="action" value="hapus">
                  <input type="hidden" name="id"     value="<?= $k['id'] ?>">
                  <button class="btn btn-danger btn-sm" type="submit">🗑️</button>
                </form>
              </div>
            </td>
          </tr>
          <?php endforeach ?>
        </tbody>
      </table>
    </div>
  <div id="pager-kelas-table"></div>
  </div><!-- /kelas-view-table -->

  <?php endif ?>
</div><!-- /card -->


<!-- ════════════════════════════════════════
     MODAL TAMBAH KELAS
════════════════════════════════════════ -->
<div class="modal-overlay" id="modalTambah">
  <div class="modal" style="max-width:520px">
    <div class="modal-header">
      <h3>➕ Tambah Kelas Baru</h3>
      <button class="modal-close" onclick="closeModal('modalTambah')">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="tambah">
      <div class="modal-body">
        <div class="form-row">
          <div class="form-group">
            <label>Tingkat Kelas <span style="color:red">*</span></label>
            <select name="tingkat" id="tambahTingkat" required>
              <option value="">– Pilih –</option>
              <option value="X">X (Sepuluh)</option>
              <option value="XI">XI (Sebelas)</option>
              <option value="XII">XII (Dua Belas)</option>
            </select>
          </div>
          <div class="form-group">
            <label>Nama Rombel / Jurusan <span style="color:red">*</span></label>
            <input name="nama_kelas" id="tambahNamaKelas" required placeholder="Contoh: IPA 1, A-1, 1">
            <div style="font-size:11px;color:var(--text3);margin-top:3px">Nama rombel sesuai tingkat kelas</div>
          </div>
        </div>
        <div class="form-group">
          <label>Wali Kelas</label>
          <input name="wali_kelas" placeholder="Nama wali kelas (opsional)">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Tahun Ajaran <span style="color:red">*</span></label>
            <input name="tahun_ajaran" required placeholder="2024/2025" value="<?= e($tahunList[0] ?? '2024/2025') ?>">
          </div>
          <div class="form-group">
            <label>Kapasitas Siswa</label>
            <input name="kapasitas" type="number" min="0" max="60" placeholder="Contoh: 36 (opsional)">
          </div>
        </div>
        <div class="form-group">
          <label>Keterangan</label>
          <textarea name="keterangan" rows="2" placeholder="Keterangan tambahan (opsional)"></textarea>
        </div>

        <!-- Preview nama kelas -->
        <div id="tambahPreview" style="display:none;background:#F5F3FF;border-radius:10px;padding:10px 14px;border-left:4px solid #7C3AED;font-size:13px;color:#4C1D95;font-weight:600"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalTambah')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan Kelas</button>
      </div>
    </form>
  </div>
</div>


<!-- ════════════════════════════════════════
     MODAL EDIT KELAS
════════════════════════════════════════ -->
<div class="modal-overlay" id="modalEdit">
  <div class="modal" style="max-width:520px">
    <div class="modal-header">
      <h3>✏️ Edit Data Kelas</h3>
      <button class="modal-close" onclick="closeModal('modalEdit')">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id"     id="editKelasId">
      <input type="hidden" name="_tahun_lama" id="editTahunLama">
      <div class="modal-body">
        <div class="form-row">
          <div class="form-group">
            <label>Tingkat Kelas <span style="color:red">*</span></label>
            <select name="tingkat" id="editTingkat" required>
              <option value="X">X (Sepuluh)</option>
              <option value="XI">XI (Sebelas)</option>
              <option value="XII">XII (Dua Belas)</option>
            </select>
          </div>
          <div class="form-group">
            <label>Nama Rombel / Jurusan <span style="color:red">*</span></label>
            <input name="nama_kelas" id="editNamaKelas" required>
          </div>
        </div>
        <div class="form-group">
          <label>Wali Kelas</label>
          <input name="wali_kelas" id="editWaliKelas">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Tahun Ajaran <span style="color:red">*</span></label>
            <input name="tahun_ajaran" id="editTahunAjaran" required
                   oninput="cekPerubahanTahun()">
          </div>
          <div class="form-group">
            <label>Kapasitas Siswa</label>
            <input name="kapasitas" id="editKapasitas" type="number" min="0" max="60">
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Status</label>
            <select name="status" id="editStatusKelas">
              <option value="aktif">✅ Aktif</option>
              <option value="nonaktif">⛔ Nonaktif</option>
            </select>
          </div>
          <div class="form-group">
            <label>Keterangan</label>
            <input name="keterangan" id="editKeterangan" placeholder="(opsional)">
          </div>
        </div>

        <!-- Info jumlah siswa -->
        <div id="editInfoSiswa" style="background:var(--surface2);border-radius:8px;padding:10px 14px;font-size:12.5px;color:var(--text2);margin-bottom:10px"></div>

        <!-- Panel sinkronisasi — muncul saat tahun ajaran berubah -->
        <div id="sinkronPanel" style="display:none;background:linear-gradient(135deg,#EFF6FF,#DBEAFE);border:1.5px solid #93C5FD;border-radius:12px;padding:14px 16px">
          <div style="font-weight:700;font-size:13px;color:#1D4ED8;margin-bottom:10px;display:flex;align-items:center;gap:7px">
            🔄 Sinkronisasi Tahun Ajaran
          </div>
          <!-- Visualisasi perubahan -->
          <div style="display:flex;align-items:center;gap:10px;justify-content:center;padding:8px 0 12px;flex-wrap:wrap">
            <div style="text-align:center">
              <div style="font-size:10px;font-weight:700;color:#6B7280;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em">Tahun Lama</div>
              <span id="sinkronDari" style="background:#FEE2E2;color:#DC2626;border-radius:8px;padding:5px 14px;font-weight:700;font-size:13px;display:inline-block"></span>
            </div>
            <div style="font-size:20px;color:#2563EB;font-weight:900">→</div>
            <div style="text-align:center">
              <div style="font-size:10px;font-weight:700;color:#6B7280;margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em">Tahun Baru</div>
              <span id="sinkronKe" style="background:#D1FAE5;color:#065F46;border-radius:8px;padding:5px 14px;font-weight:700;font-size:13px;display:inline-block"></span>
            </div>
          </div>
          <!-- Checkbox sinkron -->
          <label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer;background:rgba(255,255,255,.6);border-radius:8px;padding:10px 12px;border:1.5px solid #BFDBFE">
            <input type="checkbox" name="sinkron_siswa" value="1" id="cbSinkron"
                   style="width:16px;height:16px;margin-top:1px;flex-shrink:0;accent-color:#2563EB">
            <span style="font-size:13px;color:#1E40AF;line-height:1.4">
              <strong>Sinkronkan tahun ajaran siswa di kelas ini</strong><br>
              <span id="sinkronJmlLabel" style="font-size:11.5px;font-weight:400;color:#3B82F6"></span>
            </span>
          </label>
          <div style="font-size:11.5px;color:#6B7280;margin-top:8px;padding-left:2px">
            ℹ️ Hanya siswa yang masih <strong>aktif</strong> di kelas ini yang akan ikut diperbarui.
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalEdit')">Batal</button>
        <button type="submit" class="btn btn-primary">💾 Simpan Perubahan</button>
      </div>
    </form>
  </div>
</div>


<!-- ════════════════════════════════════════
     MODAL SINKRON MASSAL
════════════════════════════════════════ -->
<div class="modal-overlay" id="modalSinkronMassal">
  <div class="modal" style="max-width:500px">
    <div class="modal-header" style="background:linear-gradient(135deg,#1D4ED8,#3B82F6);border-radius:16px 16px 0 0">
      <h3 style="color:#fff">🔄 Sinkronisasi Tahun Ajaran Massal</h3>
      <button class="modal-close" onclick="closeModal('modalSinkronMassal')" style="color:#fff;opacity:.8">×</button>
    </div>
    <form method="POST" onsubmit="return konfirmasiSinkronMassal(this)">
      <input type="hidden" name="action" value="sinkron_massal">
      <div class="modal-body">

        <!-- Penjelasan -->
        <div style="background:#EFF6FF;border-radius:10px;padding:13px 15px;margin-bottom:16px;border-left:4px solid #3B82F6;font-size:13px;color:#1E40AF;line-height:1.6">
          🔄 Fitur ini akan memperbarui <strong>tahun ajaran di data siswa</strong> agar sesuai
          dengan tahun ajaran kelas yang mereka tempati saat ini.
          Hanya siswa yang <strong>tahun ajarannya berbeda</strong> dengan kelasnya yang akan diubah.
        </div>

        <!-- Status saat ini -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:16px">
          <div style="background:<?= $totalTidakSinkron > 0 ? '#FEF3C7' : '#ECFDF5' ?>;border-radius:10px;padding:12px 14px;text-align:center;border:1.5px solid <?= $totalTidakSinkron > 0 ? '#FCD34D' : '#6EE7B7' ?>">
            <div style="font-size:24px;font-weight:800;color:<?= $totalTidakSinkron > 0 ? '#D97706' : '#059669' ?>"><?= $totalTidakSinkron ?></div>
            <div style="font-size:11px;font-weight:600;color:<?= $totalTidakSinkron > 0 ? '#92400E' : '#065F46' ?>">Siswa belum sinkron</div>
          </div>
          <div style="background:#EFF6FF;border-radius:10px;padding:12px 14px;text-align:center;border:1.5px solid #BFDBFE">
            <div style="font-size:24px;font-weight:800;color:#2563EB"><?= $totalSiswaAktif ?></div>
            <div style="font-size:11px;font-weight:600;color:#1E40AF">Total siswa aktif</div>
          </div>
        </div>

        <!-- Filter opsional -->
        <div style="background:var(--surface2,#f8fafc);border-radius:10px;padding:13px 15px;border:1.5px solid var(--border);margin-bottom:4px">
          <div style="font-weight:700;font-size:12px;color:var(--text2);margin-bottom:10px;text-transform:uppercase;letter-spacing:.05em">Filter Sinkronisasi (opsional)</div>
          <div class="form-row" style="margin:0">
            <div class="form-group" style="margin:0">
              <label>Tingkat Kelas</label>
              <select name="filter_tingkat">
                <option value="">— Semua Kelas —</option>
                <?php foreach(['X','XI','XII'] as $t): ?>
                <option value="<?= $t ?>">Kelas <?= $t ?></option>
                <?php endforeach ?>
              </select>
            </div>
            <div class="form-group" style="margin:0">
              <label>Tahun Ajaran Kelas</label>
              <select name="filter_tahun_sumber">
                <option value="">— Semua Tahun —</option>
                <?php foreach($tahunList as $ty): ?>
                <option value="<?= e($ty) ?>"><?= e($ty) ?></option>
                <?php endforeach ?>
              </select>
            </div>
          </div>
        </div>
        <div style="font-size:11.5px;color:var(--text3);padding:6px 2px">
          Kosongkan filter untuk menyinkronkan semua kelas sekaligus.
        </div>

        <div style="background:#FEF3C7;border-radius:8px;padding:10px 12px;margin-top:12px;font-size:12px;color:#92400E">
          ⚠️ Proses ini tidak dapat dibatalkan. Tahun ajaran siswa akan mengikuti tahun ajaran di data kelas.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalSinkronMassal')">Batal</button>
        <button type="submit" class="btn btn-primary" style="background:linear-gradient(135deg,#1D4ED8,#3B82F6)">
          🔄 Mulai Sinkronisasi
        </button>
      </div>
    </form>
  </div>
</div>

<script>
/* ════ View toggle ════ */
(function() {
  var saved = localStorage.getItem('kelas_view') || 'cards';
  applyKelasView(saved);
  function applyKelasView(mode) {
    var isCards = mode === 'cards';
    document.getElementById('kelas-view-cards').style.display = isCards ? '' : 'none';
    document.getElementById('kelas-view-table').style.display = isCards ? 'none' : '';
    document.getElementById('kelas-btn-cards').classList.toggle('active',  isCards);
    document.getElementById('kelas-btn-table').classList.toggle('active', !isCards);
  }
  window.kelasSwitchView = function(mode) {
    localStorage.setItem('kelas_view', mode);
    applyKelasView(mode);
  };
})();

/* ════ Preview nama kelas di form tambah ════ */
function updateTambahPreview() {
  var tingkat = document.getElementById('tambahTingkat').value;
  var nama    = document.getElementById('tambahNamaKelas').value.trim();
  var prev    = document.getElementById('tambahPreview');
  if (tingkat && nama) {
    prev.style.display = 'block';
    prev.textContent   = '🏫 Nama kelas akan menjadi: Kelas ' + tingkat + ' ' + nama;
  } else {
    prev.style.display = 'none';
  }
}
document.getElementById('tambahTingkat').addEventListener('change', updateTambahPreview);
document.getElementById('tambahNamaKelas').addEventListener('input', updateTambahPreview);

/* ════ PAGINATION ════ */
var kelasPerPage = parseInt(localStorage.getItem('kelas_per_page') || '10');
var kelasPageCards = 1;
var kelasPageTable = 1;

(function(){
  var sel = document.getElementById('kelasPerPage');
  if (sel) sel.value = String(kelasPerPage);
})();

window.kelasOnPerPage = function(v) {
  kelasPerPage = parseInt(v);
  localStorage.setItem('kelas_per_page', v);
  kelasPageCards = 1;
  kelasPageTable = 1;
  renderKelasCards(1);
  renderKelasTable(1);
};

function buildKelasPager(containerId, total, pp, cur, cbName) {
  var el = document.getElementById(containerId);
  if (!el) return;
  var tp = Math.ceil(total / pp);
  if (tp <= 1) { el.innerHTML = ''; return; }

  var from = (cur - 1) * pp + 1;
  var to   = Math.min(cur * pp, total);

  var h = '<div class="kelas-pager">';
  h += '<span class="kelas-pager-info">Menampilkan <b>' + from + '&ndash;' + to + '</b> dari <b>' + total + '</b> kelas</span>';
  h += '<div class="kelas-pager-btns">';

  // Prev
  h += '<button class="kelas-pager-btn' + (cur===1?' disabled':'') + '" data-p="' + (cur-1) + '"' + (cur===1?' disabled':'') + '>&#8249; Prev</button>';

  // Nomor halaman dengan ellipsis
  var pages = [];
  if (tp <= 7) {
    for (var i = 1; i <= tp; i++) pages.push(i);
  } else {
    pages.push(1);
    if (cur > 3) pages.push('...');
    for (var p = Math.max(2, cur-1); p <= Math.min(tp-1, cur+1); p++) pages.push(p);
    if (cur < tp-2) pages.push('...');
    pages.push(tp);
  }

  for (var j = 0; j < pages.length; j++) {
    var pg = pages[j];
    if (pg === '...') {
      h += '<span class="kelas-pager-ellipsis">&#8230;</span>';
    } else {
      h += '<button class="kelas-pager-btn' + (pg===cur?' active':'') + '" data-p="' + pg + '">' + pg + '</button>';
    }
  }

  // Next
  h += '<button class="kelas-pager-btn' + (cur===tp?' disabled':'') + '" data-p="' + (cur+1) + '"' + (cur===tp?' disabled':'') + '>Next &#8250;</button>';

  h += '</div></div>';

  el.innerHTML = h;
  el.querySelectorAll('.kelas-pager-btn:not(.disabled)').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var p = parseInt(this.dataset.p);
      if (cbName === 'cards') renderKelasCards(p);
      else renderKelasTable(p);
    });
  });
}

function renderKelasCards(page) {
  var cards = document.querySelectorAll('#kelasCardsGrid .kelas-card[data-card]');
  var total = cards.length;
  if (!total) return;
  var pp = kelasPerPage === 999 ? total : kelasPerPage;
  var tp = Math.ceil(total / pp);
  page = Math.min(Math.max(1, page), tp);
  kelasPageCards = page;
  var start = (page - 1) * pp;
  cards.forEach(function(c, i) {
    c.style.display = (i >= start && i < start + pp) ? '' : 'none';
  });
  buildKelasPager('pager-kelas-cards', total, pp, page, 'cards');
  // Scroll ke atas card grid
  var grid = document.getElementById('kelasCardsGrid');
  if (grid && page > 1) grid.scrollIntoView({behavior:'smooth', block:'start'});
}

function renderKelasTable(page) {
  var rows = document.querySelectorAll('#kelas-view-table tbody tr[data-row]');
  var total = rows.length;
  if (!total) return;
  var pp = kelasPerPage === 999 ? total : kelasPerPage;
  var tp = Math.ceil(total / pp);
  page = Math.min(Math.max(1, page), tp);
  kelasPageTable = page;
  var start = (page - 1) * pp;
  rows.forEach(function(r, i) {
    r.style.display = (i >= start && i < start + pp) ? '' : 'none';
  });
  buildKelasPager('pager-kelas-table', total, pp, page, 'table');
}

// Init pagination
renderKelasCards(1);
renderKelasTable(1);

/* Pastikan saat view switch, pagination ikut di-render ulang */
var _origSwitch = window.kelasSwitchView;
window.kelasSwitchView = function(mode) {
  _origSwitch(mode);
  if (mode === 'cards') renderKelasCards(kelasPageCards);
  else renderKelasTable(kelasPageTable);
};

/* ════ Isi form edit ════ */
function isiFormEditKelas(k) {
  _editKelasData = k;

  document.getElementById('editKelasId').value     = k.id;
  document.getElementById('editTahunLama').value   = k.tahun_ajaran || '';
  document.getElementById('editTingkat').value     = k.tingkat;
  document.getElementById('editNamaKelas').value   = k.nama_kelas;
  document.getElementById('editWaliKelas').value   = k.wali_kelas   || '';
  document.getElementById('editTahunAjaran').value = k.tahun_ajaran || '';
  document.getElementById('editKapasitas').value   = k.kapasitas    || '';
  document.getElementById('editStatusKelas').value = k.status       || 'aktif';
  document.getElementById('editKeterangan').value  = k.keterangan   || '';

  /* Reset sinkron panel */
  document.getElementById('sinkronPanel').style.display = 'none';
  document.getElementById('cbSinkron').checked = false;

  /* Info siswa */
  var info = document.getElementById('editInfoSiswa');
  var jml  = parseInt(k.jml_siswa) || 0;
  var kap  = parseInt(k.kapasitas) || 0;
  info.innerHTML = '👥 Saat ini terdapat <strong>' + jml + ' siswa aktif</strong> di kelas ini'
                 + (kap ? ' dari kapasitas <strong>' + kap + '</strong>' : '') + '.';

  openModal('modalEdit');
}

/* ════ Deteksi perubahan tahun ajaran — tampilkan panel sinkronisasi ════ */
function cekPerubahanTahun() {
  if (!_editKelasData) return;

  var tahunBaru  = document.getElementById('editTahunAjaran').value.trim();
  var tahunLama  = _editKelasData.tahun_ajaran || '';
  var panel      = document.getElementById('sinkronPanel');
  var jml        = parseInt(_editKelasData.jml_siswa) || 0;

  if (tahunBaru && tahunBaru !== tahunLama) {
    /* Tampilkan panel */
    document.getElementById('sinkronDari').textContent = tahunLama || '—';
    document.getElementById('sinkronKe').textContent   = tahunBaru;
    document.getElementById('sinkronJmlLabel').textContent =
      jml > 0
        ? jml + ' siswa aktif di kelas ini akan ikut diperbarui'
        : 'Tidak ada siswa aktif di kelas ini';
    panel.style.display = 'block';
    /* Auto-centang jika ada siswa */
    document.getElementById('cbSinkron').checked = jml > 0;
  } else {
    panel.style.display = 'none';
    document.getElementById('cbSinkron').checked = false;
  }
}

/* ════ Konfirmasi sinkron massal ════ */
function konfirmasiSinkronMassal(form) {
  var tingkat = form.filter_tingkat.value;
  var tahun   = form.filter_tahun_sumber.value;
  var scope   = (tingkat ? 'kelas ' + tingkat : 'semua kelas')
              + (tahun   ? ' tahun ' + tahun   : '');
  return confirm('Sinkronkan tahun ajaran siswa untuk ' + scope + '?\n\nProses ini tidak dapat dibatalkan.');
}
</script>

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