<?php
$rootDir   = str_replace('\\', '/', dirname(__DIR__));
$uploadUrl = 'uploads/foto_siswa/';
$uploadAbs = $rootDir . '/uploads/foto_siswa/';

/* ════════════════════════════════════════════════════════════════
   Ambil struktur kelas DINAMIS dari tabel `kelas`
   Fallback ke array statis jika tabel belum ada (migrasi bertahap)
   ════════════════════════════════════════════════════════════════ */
$daftarJurusan = [];   // ['X' => ['1','2',...], 'XI' => [...], 'XII' => [...]]
$naikkKelasMap = [];   // ['X' => ['1' => ['kelas'=>'XI','jurusan'=>'A-1']], ...]

try {
    /* Ambil semua kelas aktif, urutkan sesuai urutan tingkat */
    $kelasDB = $pdo->query(
        "SELECT tingkat, nama_kelas
         FROM kelas
         WHERE status='aktif'
         ORDER BY FIELD(tingkat,'X','XI','XII'), nama_kelas"
    )->fetchAll(PDO::FETCH_ASSOC);

    foreach ($kelasDB as $row) {
        $daftarJurusan[$row['tingkat']][] = $row['nama_kelas'];
    }

    /* ── Bangun mapping naik kelas secara otomatis ──────────────
       Aturan: urutan rombel X ke-N → XI ke-N, XI ke-N → XII ke-N
       Contoh: X[0]='1' → XI[0]='A-1', XI[0]='A-1' → XII[0]='IPA 1'
    ─────────────────────────────────────────────────────────── */
    $tingkatUrut = ['X', 'XI', 'XII'];
    foreach ($tingkatUrut as $idx => $tkt) {
        if (!isset($tingkatUrut[$idx + 1])) break;  // XII tidak naik lagi
        $nextTkt  = $tingkatUrut[$idx + 1];
        $rombelSrc  = array_values($daftarJurusan[$tkt]      ?? []);
        $rombelDst  = array_values($daftarJurusan[$nextTkt]   ?? []);
        foreach ($rombelSrc as $no => $nama) {
            if (isset($rombelDst[$no])) {
                $naikkKelasMap[$tkt][$nama] = [
                    'kelas'   => $nextTkt,
                    'jurusan' => $rombelDst[$no],
                ];
            }
        }
    }

} catch (PDOException $e) {
    /* Tabel belum ada — gunakan fallback statis agar halaman tetap berjalan */
    $daftarJurusan = [
        'X'   => ['1','2','3','4'],
        'XI'  => ['A-1','A-2','B-1','B-2'],
        'XII' => ['IPA 1','IPA 2','IPS 1','IPS 2'],
    ];
    $naikkKelasMap = [
        'X'  => ['1'=>['kelas'=>'XI','jurusan'=>'A-1'],'2'=>['kelas'=>'XI','jurusan'=>'A-2'],
                 '3'=>['kelas'=>'XI','jurusan'=>'B-1'],'4'=>['kelas'=>'XI','jurusan'=>'B-2']],
        'XI' => ['A-1'=>['kelas'=>'XII','jurusan'=>'IPA 1'],'A-2'=>['kelas'=>'XII','jurusan'=>'IPA 2'],
                 'B-1'=>['kelas'=>'XII','jurusan'=>'IPS 1'],'B-2'=>['kelas'=>'XII','jurusan'=>'IPS 2']],
    ];
}

/* ════════════════════════════════════════════════════════════════
   Helper: catat riwayat siswa ke tabel riwayat_siswa
   ════════════════════════════════════════════════════════════════ */
function catatRiwayatSiswa(PDO $pdo, int $siswaId, string $jenis, array $data = []): void {
    try {
        $pdo->prepare(
            "INSERT INTO riwayat_siswa
             (siswa_id, jenis, kelas_dari, jurusan_dari, kelas_ke, jurusan_ke,
              tahun_ajaran, keterangan, oleh_user, tgl_kejadian)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())"
        )->execute([
            $siswaId,
            $jenis,
            $data['kelas_dari']   ?? null,
            $data['jurusan_dari'] ?? null,
            $data['kelas_ke']     ?? null,
            $data['jurusan_ke']   ?? null,
            $data['tahun_ajaran'] ?? null,
            $data['keterangan']   ?? null,
            $_SESSION['admin_nama'] ?? 'Sistem',
        ]);
    } catch (Exception $e) { /* abaikan jika tabel belum ada */ }
}

/* ════════════════════════════════════════════════════════════════
   Helper: simpan siswa ke tabel alumni saat diluluskan
   ════════════════════════════════════════════════════════════════ */
function catatAlumni(PDO $pdo, array $s, string $tahunLulus): void {
    try {
        /* Pastikan tabel ada */
        $pdo->exec("CREATE TABLE IF NOT EXISTS `alumni` (
            `id` INT NOT NULL AUTO_INCREMENT,
            `siswa_id` INT DEFAULT NULL,
            `nis` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
            `nama` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
            `jurusan` VARCHAR(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `tahun_lulus` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `no_hp` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `alamat` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `foto` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `keterangan` TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
            `tgl_lulus` DATE DEFAULT NULL,
            `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `uq_nis` (`nis`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

        /* INSERT OR IGNORE jika NIS sudah ada */
        $pdo->prepare(
            "INSERT IGNORE INTO alumni
             (siswa_id, nis, nama, jurusan, tahun_lulus, no_hp, alamat, foto, tgl_lulus)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURDATE())"
        )->execute([
            $s['id'],
            $s['nis'],
            $s['nama'],
            $s['jurusan'],
            $tahunLulus,
            $s['no_hp']    ?? null,
            $s['alamat']   ?? null,
            $s['foto']     ?? null,
        ]);
    } catch (Exception $e) { /* abaikan */ }
}

function simpanFotoSiswa(string $absDir): ?string {
    if (!isset($_FILES['foto']) || $_FILES['foto']['error'] !== UPLOAD_ERR_OK) return null;
    if (empty($_FILES['foto']['name'])) return null;
    $ext     = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'webp'];
    if (!in_array($ext, $allowed)) return null;
    if ($_FILES['foto']['size'] > 2 * 1024 * 1024) return null;
    if (!is_dir($absDir)) mkdir($absDir, 0755, true);
    $namaFile = 'siswa_' . time() . '_' . rand(1000, 9999) . '.' . $ext;
    if (move_uploaded_file($_FILES['foto']['tmp_name'], $absDir . $namaFile)) return $namaFile;
    return null;
}

function autoCreateUserSiswa(PDO $pdo, int $siswaId, string $nis, string $nama): array {
    $username = $nis;
    $password = $nis;
    $cek = $pdo->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
    $cek->execute([$username]);
    if ($cek->fetch()) {
        $pdo->prepare("UPDATE users SET siswa_id=? WHERE username=? AND (siswa_id IS NULL OR siswa_id=0)")
            ->execute([$siswaId, $username]);
        return ['created' => false, 'username' => $username, 'password' => $password];
    }
    $hash = password_hash($password, PASSWORD_BCRYPT);
    $pdo->prepare(
        "INSERT INTO users (username, password, nama, role, siswa_id, is_active) VALUES (?, ?, ?, 'siswa', ?, 1)"
    )->execute([$username, $hash, $nama, $siswaId]);
    return ['created' => true, 'username' => $username, 'password' => $password];
}

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

    /* ══════════════════════════════════
       NAIK KELAS — satu siswa
    ══════════════════════════════════ */
    if ($act === 'naik_kelas') {
        $id = (int)($_POST['id'] ?? 0);
        $tahunBaru = trim($_POST['tahun_baru'] ?? '');
        $siswa = $pdo->prepare("SELECT * FROM siswa WHERE id=? LIMIT 1");
        $siswa->execute([$id]);
        $s = $siswa->fetch();
        if ($s) {
            $kelasSkrg   = $s['kelas'];
            $jurusanSkrg = $s['jurusan'];
            if ($kelasSkrg === 'XII') {
                $_SESSION['toast'] = '⚠️ Siswa kelas XII sudah lulus, tidak dapat naik kelas';
            } elseif (isset($naikkKelasMap[$kelasSkrg][$jurusanSkrg])) {
                $target = $naikkKelasMap[$kelasSkrg][$jurusanSkrg];
                $pdo->prepare("UPDATE siswa SET kelas=?, jurusan=?, tahun_ajaran=? WHERE id=?")
                    ->execute([$target['kelas'], $target['jurusan'], $tahunBaru ?: $s['tahun_ajaran'], $id]);
                catatRiwayatSiswa($pdo, $id, 'naik_kelas', [
                    'kelas_dari'   => $kelasSkrg,
                    'jurusan_dari' => $jurusanSkrg,
                    'kelas_ke'     => $target['kelas'],
                    'jurusan_ke'   => $target['jurusan'],
                    'tahun_ajaran' => $tahunBaru ?: $s['tahun_ajaran'],
                    'keterangan'   => "Naik kelas dari {$kelasSkrg} {$jurusanSkrg} ke {$target['kelas']} {$target['jurusan']}",
                ]);
                $_SESSION['toast'] = "✅ {$s['nama']} naik kelas: {$kelasSkrg} {$jurusanSkrg} → {$target['kelas']} {$target['jurusan']}";
            } else {
                $_SESSION['toast'] = '❌ Mapping kelas tidak ditemukan';
            }
        } else {
            $_SESSION['toast'] = '❌ Siswa tidak ditemukan';
        }
        redirect('index.php?page=siswa');
    }

    /* ══════════════════════════════════
       NAIK KELAS — massal per kelas/rombel
    ══════════════════════════════════ */
    if ($act === 'naik_kelas_massal') {
        $kelasTarget  = trim($_POST['kelas_massal']   ?? '');
        $jurusanTarget= trim($_POST['jurusan_massal'] ?? '');
        $tahunBaru    = trim($_POST['tahun_baru_massal'] ?? '');
        $luluskan     = ($_POST['luluskan_xii'] ?? '0') === '1';

        if (empty($kelasTarget)) {
            $_SESSION['toast'] = '❌ Pilih kelas yang akan dinaikkan';
            redirect('index.php?page=siswa');
        }

        // Ambil siswa sesuai filter
        $sqlFilter = "SELECT * FROM siswa WHERE status='aktif' AND kelas=?";
        $paramsFilter = [$kelasTarget];
        if ($jurusanTarget) {
            $sqlFilter    .= " AND jurusan=?";
            $paramsFilter[] = $jurusanTarget;
        }
        $stmtAll = $pdo->prepare($sqlFilter);
        $stmtAll->execute($paramsFilter);
        $siswaMassal = $stmtAll->fetchAll();

        $berhasil = 0; $lulus = 0; $gagal = 0;

        foreach ($siswaMassal as $s) {
            $kls = $s['kelas'];
            $jur = $s['jurusan'];
            if ($kls === 'XII') {
                if ($luluskan) {
                    $tahunFinal = $tahunBaru ?: $s['tahun_ajaran'];
                    $pdo->prepare("UPDATE siswa SET status='nonaktif', tahun_ajaran=? WHERE id=?")
                        ->execute([$tahunFinal, $s['id']]);
                    /* Masukkan ke tabel alumni */
                    catatAlumni($pdo, $s, $tahunFinal);
                    /* Catat riwayat kelulusan */
                    catatRiwayatSiswa($pdo, $s['id'], 'lulus', [
                        'kelas_dari'   => 'XII',
                        'jurusan_dari' => $s['jurusan'],
                        'tahun_ajaran' => $tahunFinal,
                        'keterangan'   => 'Siswa dinyatakan lulus — data masuk ke alumni',
                    ]);
                    $lulus++;
                }
                continue;
            }
            if (isset($naikkKelasMap[$kls][$jur])) {
                $target = $naikkKelasMap[$kls][$jur];
                $pdo->prepare("UPDATE siswa SET kelas=?, jurusan=?, tahun_ajaran=? WHERE id=?")
                    ->execute([$target['kelas'], $target['jurusan'], $tahunBaru ?: $s['tahun_ajaran'], $s['id']]);
                catatRiwayatSiswa($pdo, $s['id'], 'naik_kelas', [
                    'kelas_dari'   => $kls,
                    'jurusan_dari' => $jur,
                    'kelas_ke'     => $target['kelas'],
                    'jurusan_ke'   => $target['jurusan'],
                    'tahun_ajaran' => $tahunBaru ?: $s['tahun_ajaran'],
                    'keterangan'   => 'Naik kelas massal',
                ]);
                $berhasil++;
            } else {
                $gagal++;
            }
        }

        $msg = "✅ Kenaikan kelas selesai: {$berhasil} siswa berhasil naik kelas";
        if ($lulus)  $msg .= ", {$lulus} siswa XII diluluskan (nonaktif)";
        if ($gagal)  $msg .= ", {$gagal} gagal (mapping tidak ada)";
        $_SESSION['toast'] = $msg;
        redirect('index.php?page=siswa');
    }

    /* ══════════════════════════════════════
       PINDAH KELAS — satu siswa
    ══════════════════════════════════════ */
    if ($act === 'pindah_kelas') {
        $id          = (int)($_POST['id']              ?? 0);
        $kelasTarget = trim($_POST['kelas_pindah']     ?? '');
        $jurTarget   = trim($_POST['jurusan_pindah']   ?? '');
        $tahunBaru   = trim($_POST['tahun_baru_pindah']?? '');
        $alasan      = trim($_POST['alasan_pindah']    ?? '');

        if (!$id || !$kelasTarget || !$jurTarget) {
            $_SESSION['toast'] = '❌ Kelas dan rombel tujuan wajib diisi';
            redirect('index.php?page=siswa');
        }

        $siswa = $pdo->prepare("SELECT * FROM siswa WHERE id=? LIMIT 1");
        $siswa->execute([$id]);
        $s = $siswa->fetch();

        if (!$s) {
            $_SESSION['toast'] = '❌ Siswa tidak ditemukan';
            redirect('index.php?page=siswa');
        }

        if ($s['kelas'] === $kelasTarget && $s['jurusan'] === $jurTarget) {
            $_SESSION['toast'] = '⚠️ Siswa sudah berada di kelas tersebut';
            redirect('index.php?page=siswa');
        }

        $kelasLama   = $s['kelas'];
        $jurusanLama = $s['jurusan'];
        $tahunFinal  = $tahunBaru ?: $s['tahun_ajaran'];

        $pdo->prepare("UPDATE siswa SET kelas=?, jurusan=?, tahun_ajaran=? WHERE id=?")
            ->execute([$kelasTarget, $jurTarget, $tahunFinal, $id]);

        catatRiwayatSiswa($pdo, $id, 'pindah_kelas', [
            'kelas_dari'   => $kelasLama,
            'jurusan_dari' => $jurusanLama,
            'kelas_ke'     => $kelasTarget,
            'jurusan_ke'   => $jurTarget,
            'tahun_ajaran' => $tahunFinal,
            'keterangan'   => $alasan ?: "Pindah dari {$kelasLama} {$jurusanLama} ke {$kelasTarget} {$jurTarget}",
        ]);

        /* Catat riwayat pindah jika tabel tersedia */
        try {
            $pdo->prepare(
                "INSERT INTO riwayat_pindah_kelas
                 (siswa_id, kelas_dari, jurusan_dari, kelas_ke, jurusan_ke, tahun_ajaran, alasan, tgl_pindah)
                 VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
            )->execute([$id, $kelasLama, $jurusanLama, $kelasTarget, $jurTarget, $tahunFinal, $alasan]);
        } catch (Exception $e) { /* tabel opsional, abaikan jika belum ada */ }

        $_SESSION['toast'] = "🔀 {$s['nama']} berhasil dipindah: {$kelasLama} {$jurusanLama} → {$kelasTarget} {$jurTarget}";
        redirect('index.php?page=siswa');
    }

    if ($act === 'ekspor_csv') {
        $siswas = $pdo->query("SELECT nis,nama,kelas,jurusan,tahun_ajaran,no_hp,alamat,status FROM siswa ORDER BY kelas,nama")->fetchAll();
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="data_siswa_'.date('Ymd').'.csv"');
        header('Cache-Control: no-cache');
        $out = fopen('php://output', 'w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($out, ['NIS','Nama','Kelas','Jurusan','Tahun Ajaran','No HP','Alamat','Status']);
        foreach ($siswas as $s) {
            fputcsv($out, [$s['nis'],$s['nama'],$s['kelas'],$s['jurusan'],$s['tahun_ajaran'],$s['no_hp'],$s['alamat'],$s['status']]);
        }
        fclose($out); exit;
    }

    if ($act === 'impor_csv') {
        if (
            !isset($_FILES['file_csv']) ||
            $_FILES['file_csv']['error'] !== UPLOAD_ERR_OK ||
            empty($_FILES['file_csv']['tmp_name'])
        ) {
            $_SESSION['toast'] = '❌ File CSV tidak valid atau gagal diupload';
            redirect('index.php?page=siswa');
        }
        $handle = fopen($_FILES['file_csv']['tmp_name'], 'r');
        if (!$handle) {
            $_SESSION['toast'] = '❌ Gagal membuka file CSV';
            redirect('index.php?page=siswa');
        }
        $bom = fread($handle, 3);
        if ($bom !== chr(0xEF).chr(0xBB).chr(0xBF)) rewind($handle);
        $header   = fgetcsv($handle);
        $berhasil = 0; $gagal = 0; $duplikat = 0;
        $stmt = $pdo->prepare(
            "INSERT INTO siswa (nis, nama, kelas, jurusan, tahun_ajaran, no_hp, alamat, status)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
        );
        while (($row = fgetcsv($handle)) !== false) {
            if (empty(array_filter($row))) continue;
            if (count($row) < 4) { $gagal++; continue; }
            $nis     = trim($row[0] ?? '');
            $nama    = trim($row[1] ?? '');
            $kelas   = trim($row[2] ?? '');
            $jurusan = trim($row[3] ?? '');
            $tahun   = trim($row[4] ?? '2024/2025');
            $hp      = trim($row[5] ?? '');
            $alamat  = trim($row[6] ?? '');
            $status  = trim($row[7] ?? 'aktif');
            if (empty($nis) || empty($nama) || empty($kelas) || empty($jurusan)) { $gagal++; continue; }
            if (!in_array($status, ['aktif', 'nonaktif'])) $status = 'aktif';
            $cek = $pdo->prepare("SELECT id FROM siswa WHERE nis = ? LIMIT 1");
            $cek->execute([$nis]);
            if ($cek->fetch()) { $duplikat++; continue; }
            try {
                $ok = $stmt->execute([$nis, $nama, $kelas, $jurusan, $tahun, $hp, $alamat, $status]);
                if ($ok) { $berhasil++; $newSiswaId = (int)$pdo->lastInsertId(); autoCreateUserSiswa($pdo, $newSiswaId, $nis, $nama); }
                else $gagal++;
            } catch (Exception $e) { $gagal++; }
        }
        fclose($handle);
        $_SESSION['toast'] = "✅ Impor selesai: {$berhasil} siswa berhasil, {$duplikat} duplikat dilewati, {$gagal} gagal";
        redirect('index.php?page=siswa');
    }

    if ($act === 'tambah') {
        $nis  = trim($_POST['nis']  ?? '');
        $nama = trim($_POST['nama'] ?? '');
        $foto = simpanFotoSiswa($uploadAbs);
        $pdo->prepare("INSERT INTO siswa (nis,nama,kelas,jurusan,tahun_ajaran,no_hp,alamat,foto,status) VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute([$nis,$nama,$_POST['kelas']??'',$_POST['jurusan']??'',$_POST['tahun_ajaran']??'',$_POST['no_hp']??'',$_POST['alamat']??'',$foto,$_POST['status']??'aktif']);
        $siswaId  = (int)$pdo->lastInsertId();
        $userInfo = autoCreateUserSiswa($pdo, $siswaId, $nis, $nama);
        $msgUser  = $userInfo['created'] ? " 🔑 Akun login dibuat: username={$userInfo['username']}, password={$userInfo['password']}" : '';
        $_SESSION['toast'] = '✅ Siswa berhasil ditambahkan'.($foto?' (foto tersimpan)':'').$msgUser;
    } elseif ($act === 'edit') {
        $id=$_POST['id']??0; $foto=simpanFotoSiswa($uploadAbs);
        $fotoSql=$foto?', foto=?':''; $fotoVal=$foto?[$foto]:[];
        $params=array_merge([$_POST['nis']??'',$_POST['nama']??'',$_POST['kelas']??'',$_POST['jurusan']??'',$_POST['tahun_ajaran']??'',$_POST['no_hp']??'',$_POST['alamat']??'',$_POST['status']??'aktif'],$fotoVal,[$id]);
        $pdo->prepare("UPDATE siswa SET nis=?,nama=?,kelas=?,jurusan=?,tahun_ajaran=?,no_hp=?,alamat=?,status=?{$fotoSql} WHERE id=?")->execute($params);
        $_SESSION['toast'] = '✅ Data siswa diperbarui'.($foto?' (foto diperbarui)':'');
    } elseif ($act === 'hapus') {
        $pdo->prepare("DELETE FROM siswa WHERE id=?")->execute([(int)$_POST['id']]);
        $_SESSION['toast'] = '🗑️ Siswa berhasil dihapus';
    } elseif ($act === 'nonaktif') {
        $sid = (int)$_POST['id'];
        $sw  = $pdo->prepare("SELECT nama, kelas, jurusan, tahun_ajaran FROM siswa WHERE id=? LIMIT 1");
        $sw->execute([$sid]);
        $sw  = $sw->fetch();
        $pdo->prepare("UPDATE siswa SET status='nonaktif' WHERE id=?")->execute([$sid]);
        if ($sw) catatRiwayatSiswa($pdo, $sid, 'nonaktif', [
            'kelas_dari'   => $sw['kelas'], 'jurusan_dari' => $sw['jurusan'],
            'tahun_ajaran' => $sw['tahun_ajaran'], 'keterangan' => 'Siswa dinonaktifkan',
        ]);
        $_SESSION['toast'] = '⛔ Siswa dinonaktifkan';
    } elseif ($act === 'aktifkan') {
        $sid = (int)$_POST['id'];
        $sw  = $pdo->prepare("SELECT nama, kelas, jurusan, tahun_ajaran FROM siswa WHERE id=? LIMIT 1");
        $sw->execute([$sid]);
        $sw  = $sw->fetch();
        $pdo->prepare("UPDATE siswa SET status='aktif' WHERE id=?")->execute([$sid]);
        if ($sw) catatRiwayatSiswa($pdo, $sid, 'aktif', [
            'kelas_dari'   => $sw['kelas'], 'jurusan_dari' => $sw['jurusan'],
            'tahun_ajaran' => $sw['tahun_ajaran'], 'keterangan' => 'Siswa diaktifkan kembali',
        ]);
        $_SESSION['toast'] = '✅ Siswa diaktifkan kembali';
    }

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

require_once 'layout/header.php';

$search  = trim($_GET['q']      ?? '');
$kelas   = trim(rawurldecode($_GET['kelas']   ?? ''));
$jurusan = trim(rawurldecode($_GET['jurusan'] ?? ''));
$status  = trim($_GET['status'] ?? 'aktif');

$sql = "SELECT * FROM siswa WHERE status=?"; $params = [$status];
if ($search)  { $sql .= " AND (nama LIKE ? OR nis LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($kelas)   { $sql .= " AND kelas=?";   $params[] = $kelas; }
if ($jurusan) { $sql .= " AND jurusan=?"; $params[] = $jurusan; }
$sql .= " ORDER BY kelas, jurusan, nama";
$stmt = $pdo->prepare($sql); $stmt->execute($params);
$siswas = $stmt->fetchAll();

$totalAktif    = $pdo->query("SELECT COUNT(*) FROM siswa WHERE status='aktif'")->fetchColumn();
$totalNonaktif = $pdo->query("SELECT COUNT(*) FROM siswa WHERE status='nonaktif'")->fetchColumn();

/* Preview naik kelas: hitung berapa siswa per kelas yang bisa naik */
$previewNaik = [];
foreach (['X','XI','XII'] as $k) {
    $n = $pdo->prepare("SELECT COUNT(*) FROM siswa WHERE status='aktif' AND kelas=?");
    $n->execute([$k]);
    $previewNaik[$k] = (int)$n->fetchColumn();
}

$toast = $_SESSION['toast'] ?? ''; unset($_SESSION['toast']);
$avatarColors = ['#FF6B9D','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];

/* Tahun ajaran saat ini untuk default naik kelas */
$tahunAjaranList = $pdo->query("SELECT DISTINCT tahun_ajaran FROM siswa ORDER BY tahun_ajaran DESC")->fetchAll(PDO::FETCH_COLUMN);
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
/* ══ View Toggle ══ */
.view-toggle {
  display:flex;gap:4px;background:var(--surface2,#f1f5f9);
  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 ease;white-space:nowrap;font-family:inherit;
}
.view-toggle button svg { flex-shrink:0; }
.view-toggle button.active {
  background:var(--surface,#fff);color:var(--candy-purple,#7C3AED);
  box-shadow:0 1px 4px rgba(0,0,0,.08);
}
.view-toggle button:hover:not(.active) { color:var(--text); }

.siswa-view-wrap { display:flex;flex-direction:column; }
.siswa-tbl-scroll { overflow-x:auto;overflow-y:auto;max-height:480px;scrollbar-width:thin;scrollbar-color:var(--border) transparent; }
.siswa-tbl-scroll::-webkit-scrollbar { width:5px;height:5px; }
.siswa-tbl-scroll::-webkit-scrollbar-thumb { background:var(--border);border-radius:99px; }
.siswa-tbl-scroll::-webkit-scrollbar-track { background:transparent; }
.siswa-tbl-scroll table { width:100%; }
.siswa-tbl-scroll thead { position:sticky;top:0;z-index:2; }
.siswa-tbl-scroll thead th { box-shadow:0 1.5px 0 var(--border); }

.siswa-cards-scroll { overflow-y:auto;max-height:520px;scrollbar-width:thin;scrollbar-color:var(--border) transparent; }
.siswa-cards-scroll::-webkit-scrollbar { width:5px; }
.siswa-cards-scroll::-webkit-scrollbar-thumb { background:var(--border);border-radius:99px; }
.siswa-cards-scroll::-webkit-scrollbar-track { background:transparent; }

.siswa-cards { display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;padding:16px; }

.siswa-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:siswaCardIn .22s ease both;position:relative;
}
.siswa-card:hover { box-shadow:0 6px 22px rgba(0,0,0,.09);transform:translateY(-3px); }
@keyframes siswaCardIn { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
.siswa-card-bar  { height:5px;width:100%; }
.siswa-card-body { padding:14px 15px;display:flex;flex-direction:column;gap:11px;flex:1; }
.siswa-card-top  { display:flex;align-items:center;gap:11px; }
.siswa-card-photo { width:44px;height:44px;border-radius:12px;object-fit:cover;flex-shrink:0;border:2px solid var(--border); }
.siswa-card-avatar { width:44px;height:44px;border-radius:12px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;color:#fff;font-family:inherit; }
.siswa-card-name { font-weight:700;font-size:13.5px;color:var(--text);line-height:1.25;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
.siswa-card-nis  { font-size:11px;color:var(--text3);font-family:monospace;background:var(--surface2);padding:1px 6px;border-radius:5px;display:inline-block;margin-top:2px; }
.siswa-card-status { margin-left:auto;flex-shrink:0; }
.siswa-card-hr     { border:none;border-top:1px solid var(--border);margin:0; }
.siswa-card-rows   { display:flex;flex-direction:column;gap:7px; }
.siswa-card-row    { display:flex;align-items:center;justify-content:space-between;font-size:12.5px; }
.siswa-card-row-label { display:flex;align-items:center;gap:5px;color:var(--text3);font-size:12px; }
.siswa-card-footer { display:flex;gap:6px;padding:10px 15px 13px;border-top:1px solid var(--border);background:var(--surface2,#f8fafc);flex-wrap:wrap; }
.siswa-card-footer .btn { flex:1;justify-content:center;font-size:12px; }

.siswa-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);flex-shrink:0; }
.pager-info  { font-size:12.5px;color:var(--text2); }
.pager-btns  { display:flex;gap:4px;align-items:center;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:inherit;transition:background .15s,color .15s,border-color .15s;display:inline-flex;align-items:center;justify-content:center; }
.pager-btn:hover:not(.disabled):not(.active) { background:var(--surface2);border-color:var(--candy-purple,#7C3AED);color:var(--candy-purple,#7C3AED); }
.pager-btn.active  { background:var(--candy-purple,#7C3AED);color:#fff;border-color:var(--candy-purple,#7C3AED);font-weight:700; }
.pager-btn.disabled{ opacity:.38;cursor:not-allowed; }
.pager-ellipsis    { font-size:13px;color:var(--text3);padding:0 3px;user-select:none; }

.kelas-filter-wrap { display:flex;align-items:center;flex-wrap:wrap;gap:4px;background:var(--surface2,#f1f5f9);border:1.5px solid var(--border);border-radius:12px;padding:5px 8px;width:100%; }
.kelas-btn { display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:8px;font-size:12px;font-weight:600;text-decoration:none;color:var(--text2);transition:background .15s,color .15s,box-shadow .15s;white-space:nowrap;line-height:1.5; }
.kelas-btn:hover { background:var(--surface,#fff);color:var(--candy-purple,#7C3AED);box-shadow:0 1px 4px rgba(0,0,0,.07); }
.kelas-btn.active { background:var(--candy-purple,#7C3AED);color:#fff;box-shadow:0 2px 8px rgba(124,58,237,.25); }
.kelas-btn.active .kelas-btn-count { background:rgba(255,255,255,.25);color:#fff; }
.kelas-btn-count { background:var(--surface,#fff);color:var(--candy-purple,#7C3AED);border-radius:99px;font-size:10px;font-weight:700;padding:0 5px;min-width:16px;text-align:center;line-height:1.6; }

/* ══ Naik Kelas — Banner / Summary card ══ */
.naik-kelas-banner {
  background:linear-gradient(135deg,#4F46E5 0%,#7C3AED 50%,#A855F7 100%);
  border-radius:16px;padding:18px 22px;margin-bottom:16px;
  display:flex;align-items:center;gap:16px;flex-wrap:wrap;
  box-shadow:0 4px 20px rgba(124,58,237,.25);
  position:relative;overflow:hidden;
}
.naik-kelas-banner::before {
  content:'';position:absolute;right:-30px;top:-30px;
  width:140px;height:140px;border-radius:50%;
  background:rgba(255,255,255,.07);pointer-events:none;
}
.naik-kelas-banner::after {
  content:'';position:absolute;right:60px;bottom:-40px;
  width:100px;height:100px;border-radius:50%;
  background:rgba(255,255,255,.05);pointer-events:none;
}
.naik-kelas-banner-icon { font-size:36px;flex-shrink:0; }
.naik-kelas-banner-text { flex:1;min-width:0; }
.naik-kelas-banner-title { font-weight:700;font-size:15px;color:#fff;margin-bottom:3px; }
.naik-kelas-banner-sub   { font-size:12.5px;color:rgba(255,255,255,.75); }
.naik-kelas-counts { display:flex;gap:8px;flex-wrap:wrap;margin-left:auto;align-items:center; }
.naik-kelas-pill {
  background:rgba(255,255,255,.18);border-radius:99px;
  padding:5px 13px;font-size:12px;color:#fff;font-weight:600;
  display:flex;align-items:center;gap:5px;border:1px solid rgba(255,255,255,.25);
}
.naik-kelas-pill span { font-size:15px;font-weight:800; }
.btn-naik-massal {
  background:#fff;color:#7C3AED;border:none;border-radius:10px;
  padding:9px 18px;font-size:13px;font-weight:700;cursor:pointer;
  font-family:inherit;transition:background .15s,transform .1s;white-space:nowrap;
  box-shadow:0 2px 8px rgba(0,0,0,.15);flex-shrink:0;
}
.btn-naik-massal:hover { background:#F5F3FF;transform:translateY(-1px); }

/* ══ Modal Naik Kelas ══ */
.naik-preview-table { width:100%;border-collapse:collapse;font-size:13px; }
.naik-preview-table th { background:var(--surface2);padding:8px 12px;text-align:left;font-weight:600;font-size:11.5px;color:var(--text2);text-transform:uppercase;letter-spacing:.04em; }
.naik-preview-table td { padding:8px 12px;border-top:1px solid var(--border);vertical-align:middle; }
.naik-preview-table tr:hover td { background:var(--surface2); }
.arrow-kelas { color:var(--candy-purple,#7C3AED);font-weight:700;margin:0 6px; }

/* ══ Naik kelas — badge kecil di row tabel ══ */
.btn-naik-single {
  background:linear-gradient(135deg,#EDE9FE,#DDD6FE);
  border:1.5px solid #C4B5FD;color:#5B21B6;
  border-radius:7px;padding:4px 8px;font-size:11px;font-weight:700;
  cursor:pointer;font-family:inherit;transition:all .15s;white-space:nowrap;
  display:inline-flex;align-items:center;gap:3px;
}
.btn-naik-single:hover { background:linear-gradient(135deg,#DDD6FE,#C4B5FD);transform:translateY(-1px); }

/* ══ Pindah kelas — badge di row tabel ══ */
.btn-pindah-single {
  background:linear-gradient(135deg,#E0F2FE,#BAE6FD);
  border:1.5px solid #7DD3FC;color:#0369A1;
  border-radius:7px;padding:4px 8px;font-size:11px;font-weight:700;
  cursor:pointer;font-family:inherit;transition:all .15s;white-space:nowrap;
  display:inline-flex;align-items:center;gap:3px;
}
.btn-pindah-single:hover { background:linear-gradient(135deg,#BAE6FD,#7DD3FC);transform:translateY(-1px); }

/* ══ Step-tabs di modal pindah ══ */
.pindah-step-tabs { display:flex;gap:0;border-bottom:2px solid var(--border);margin-bottom:18px; }
.pindah-step-tab  {
  padding:9px 18px;font-size:13px;font-weight:600;cursor:pointer;
  border-bottom:2px solid transparent;margin-bottom:-2px;color:var(--text2);
  transition:color .15s,border-color .15s;background:none;border-top:none;border-left:none;border-right:none;
  font-family:inherit;
}
.pindah-step-tab.active { color:#0369A1;border-bottom-color:#0369A1; }

@media (max-width:640px) {
  .view-toggle button .toggle-label { display:none; }
  .siswa-cards { grid-template-columns:1fr 1fr;gap:10px;padding:12px; }
  .perpage-label { display:none; }
  .naik-kelas-banner { flex-direction:column;align-items:flex-start; }
  .naik-kelas-counts { margin-left:0; }
}
@media (max-width:420px) {
  .siswa-cards { grid-template-columns:1fr; }
  .siswa-pager { flex-direction:column;align-items:flex-start; }
  .pager-btn   { min-width:30px;height:30px;font-size:12px; }
}
</style>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title">🎒 Data Siswa</div>
    <div class="page-header-sub"><?= count($siswas) ?> siswa ditemukan</div>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <button class="btn btn-outline" onclick="openModal('modalImpor')" style="border-color:#0D9488;color:#0D9488">📥 Impor CSV</button>
    <form method="POST" style="display:inline">
      <input type="hidden" name="action" value="ekspor_csv">
      <button type="submit" class="btn btn-outline" style="border-color:#059669;color:#059669">📤 Ekspor CSV</button>
    </form>
    <button class="btn btn-outline" onclick="downloadTemplate()" style="border-color:#7C3AED;color:#7C3AED">📋 Template CSV</button>
    <button class="btn btn-primary" onclick="openModal('modalTambah')">➕ Tambah Siswa</button>
  </div>
</div>

<!-- ══════════════════════════════════════════
     BANNER NAIK KELAS
══════════════════════════════════════════ -->
<div class="naik-kelas-banner">
  <div class="naik-kelas-banner-icon">🎓</div>
  <div class="naik-kelas-banner-text">
    <div class="naik-kelas-banner-title">Proses Kenaikan Kelas</div>
    <div class="naik-kelas-banner-sub">Naikkan siswa ke jenjang berikutnya secara massal atau satu per satu</div>
  </div>
  <div class="naik-kelas-counts">
    <?php foreach(['X'=>'🏫','XI'=>'📚','XII'=>'🎓'] as $k=>$ic): ?>
    <div class="naik-kelas-pill">
      <?= $ic ?> Kelas <?= $k ?> <span><?= $previewNaik[$k] ?? 0 ?></span>
    </div>
    <?php endforeach ?>
  </div>
  <button class="btn-naik-massal" onclick="openModal('modalNaikMassal')">
    ⬆️ Naik Kelas Massal
  </button>
</div>

<!-- Toolbar -->
<div class="toolbar" style="margin-bottom:8px;flex-wrap:wrap;gap:10px">
  <div class="search-box" style="flex:1;min-width:200px;position:relative">
    <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    <input type="text" id="siswaSearchInput"
           value="<?= e($search) ?>"
           placeholder="Cari nama atau NIS..."
           oninput="siswaDomSearch(this.value)"
           onkeydown="if(event.key==='Enter'){siswaSearchSubmit()}"
           autocomplete="off">
    <?php if($search): ?>
    <button type="button" onclick="siswaClearSearch()"
            style="position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text3);font-size:16px;line-height:1;padding:0">×</button>
    <?php endif ?>
  </div>
  <!-- Hidden form untuk submit ke server (fallback Enter / pindah halaman) -->
  <form id="siswaSearchForm" method="GET" action="index.php" style="display:none">
    <input type="hidden" name="page"    value="siswa">
    <input type="hidden" name="kelas"   value="<?= e($kelas) ?>">
    <input type="hidden" name="jurusan" value="<?= e($jurusan) ?>">
    <input type="hidden" name="status"  value="<?= e($status) ?>">
    <input type="hidden" name="q"       id="siswaSearchQ" value="<?= e($search) ?>">
  </form>
  <div style="display:flex;gap:4px;background:var(--surface2);border-radius:10px;padding:4px">
    <a href="index.php?page=siswa&status=aktif&kelas=<?= rawurlencode($kelas) ?>&jurusan=<?= rawurlencode($jurusan) ?>&q=<?= rawurlencode($search) ?>"
       style="padding:6px 14px;border-radius:7px;font-size:12.5px;font-weight:700;text-decoration:none;transition:.15s;
              <?= $status==='aktif' ? 'background:#fff;color:var(--candy-purple);box-shadow:0 1px 6px rgba(0,0,0,.10)' : 'color:var(--text2)' ?>">
      ✅ Aktif <span style="background:var(--surface2);border-radius:99px;padding:1px 7px;font-size:11px;margin-left:2px"><?= $totalAktif ?></span>
    </a>
    <a href="index.php?page=siswa&status=nonaktif&kelas=<?= rawurlencode($kelas) ?>&jurusan=<?= rawurlencode($jurusan) ?>&q=<?= rawurlencode($search) ?>"
       style="padding:6px 14px;border-radius:7px;font-size:12.5px;font-weight:700;text-decoration:none;transition:.15s;
              <?= $status==='nonaktif' ? 'background:#fff;color:var(--candy-pink);box-shadow:0 1px 6px rgba(0,0,0,.10)' : 'color:var(--text2)' ?>">
      ⛔ Nonaktif <span style="background:var(--surface2);border-radius:99px;padding:1px 7px;font-size:11px;margin-left:2px"><?= $totalNonaktif ?></span>
    </a>
  </div>
</div>

<!-- Kelas Filter Bar -->
<div style="margin-bottom:16px;display:flex;flex-direction:column;gap:6px">
  <?php
  $kelasCounts   = [];
  $jurusanCounts = [];
  $stmtCount = $pdo->prepare("SELECT kelas, jurusan, COUNT(*) as total FROM siswa WHERE status=? GROUP BY kelas, jurusan");
  $stmtCount->execute([$status]);
  foreach ($stmtCount->fetchAll() as $row) {
      $kelasCounts[$row['kelas']] = ($kelasCounts[$row['kelas']] ?? 0) + $row['total'];
      $jurusanCounts[$row['kelas'].'|'.$row['jurusan']] = $row['total'];
  }
  $baseUrl = 'index.php?page=siswa&status='.rawurlencode($status).'&q='.rawurlencode($search);
  ?>
  <div class="kelas-filter-wrap">
    <a href="<?= $baseUrl ?>&kelas=&jurusan=" class="kelas-btn <?= (!$kelas && !$jurusan) ? 'active' : '' ?>">🏫 Semua</a>
    <?php foreach($daftarJurusan as $tkt => $jList):
      $jml = $kelasCounts[$tkt] ?? 0;
    ?>
    <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($tkt) ?>&jurusan=" class="kelas-btn <?= ($kelas===$tkt) ? 'active' : '' ?>">
      Kelas <?= $tkt ?>
      <?php if($jml > 0): ?><span class="kelas-btn-count"><?= $jml ?></span><?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php if($kelas && isset($daftarJurusan[$kelas])): ?>
  <div class="kelas-filter-wrap" style="background:var(--surface,#fff);border-style:solid;border-color:var(--candy-purple,#7C3AED);border-width:1.5px;border-left-width:4px">
    <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=" class="kelas-btn <?= !$jurusan ? 'active' : '' ?>">Semua <?= e($kelas) ?></a>
    <?php foreach($daftarJurusan[$kelas] as $j):
      $jml2 = $jurusanCounts[$kelas.'|'.$j] ?? 0;
    ?>
      <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=<?= rawurlencode($j) ?>" class="kelas-btn <?= ($jurusan===$j) ? 'active' : '' ?>">
        <?= e($kelas) ?> <?= e($j) ?>
        <?php if($jml2 > 0): ?><span class="kelas-btn-count"><?= $jml2 ?></span><?php endif ?>
      </a>
    <?php endforeach ?>
  </div>
  <?php endif ?>
</div>

<!-- Card Wrapper -->
<div class="card" style="padding:0;overflow:visible">
  <!-- Card header -->
  <div style="padding:13px 16px;display:flex;align-items:center;justify-content:space-between;gap:10px;border-bottom:1px solid var(--border);flex-wrap:wrap">
    <div style="display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--text)">
      🎒 Daftar Siswa
      <?php if(!empty($siswas)): ?>
        <span class="pill pill-purple"><?= count($siswas) ?> siswa</span>
      <?php endif ?>
    </div>
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
      <?php if(!empty($siswas)): ?>
      <div style="display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--text2)">
        <span class="perpage-label">Tampil</span>
        <select id="siswaPerPage" onchange="siswaOnPerPage(this.value)"
                style="padding:4px 8px;border:1.5px solid var(--border);border-radius:7px;font-size:12px;background:var(--surface,#fff);color:var(--text);font-family:inherit;cursor:pointer">
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
        <span class="perpage-label">/ hal</span>
      </div>
      <?php endif ?>
      <div class="view-toggle" role="group" aria-label="Pilih tampilan">
        <button id="siswa-btn-table" class="active" onclick="siswaSwitchView('table')" title="Tampilan tabel">
          <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 class="toggle-label">Tabel</span>
        </button>
        <button id="siswa-btn-cards" onclick="siswaSwitchView('cards')" title="Tampilan kartu">
          <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 class="toggle-label">Kartu</span>
        </button>
      </div>
    </div>
  </div>

  <!-- TABLE VIEW -->
  <div id="siswa-view-table" class="siswa-view-wrap">
    <div class="siswa-tbl-scroll">
      <table>
        <thead>
          <tr>
            <th>#</th><th>Foto</th><th>Nama & NIS</th><th>Kelas</th>
            <th>Jurusan</th><th>No. HP</th><th>Tahun Ajaran</th><th>Status</th><th>Aksi</th>
          </tr>
        </thead>
        <tbody id="siswa-tbody">
        <?php if(empty($siswas)): ?>
          <tr><td colspan="9">
            <div class="empty-state">
              <div class="empty-state-icon">🎒</div>
              <h4>Belum ada data siswa</h4>
              <p>Klik "Tambah Siswa" atau "Impor CSV" untuk mulai menambahkan data</p>
            </div>
          </td></tr>
        <?php else: foreach($siswas as $i=>$s):
          $c       = $avatarColors[$i % count($avatarColors)];
          $fotoAda = !empty($s['foto']) && file_exists($uploadAbs.$s['foto']);
          $bisaNaik= in_array($s['kelas'], ['X','XI']);
        ?>
          <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>
              <?php if($fotoAda): ?>
                <img src="<?= e($uploadUrl.$s['foto']) ?>" style="width:36px;height:36px;border-radius:10px;object-fit:cover;border:2px solid var(--border)">
              <?php else: ?>
                <div class="avatar" style="background:<?= $c ?>"><?= mb_strtoupper(mb_substr($s['nama'],0,1)) ?></div>
              <?php endif ?>
            </td>
            <td>
              <div style="font-weight:600;font-size:13.5px"><?= e($s['nama']) ?></div>
              <span style="font-family:monospace;font-size:11px;background:var(--surface2);padding:2px 7px;border-radius:5px;color:var(--text3)"><?= e($s['nis']) ?></span>
            </td>
            <td><span class="pill pill-purple"><?= e($s['kelas']) ?></span></td>
            <td><span class="pill pill-blue"><?= e($s['jurusan']) ?></span></td>
            <td style="color:var(--text2);font-size:13px"><?= e($s['no_hp']??'–') ?></td>
            <td style="color:var(--text2);font-size:13px"><?= e($s['tahun_ajaran']) ?></td>
            <td>
              <?php if($s['status']==='aktif'): ?>
                <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;flex-wrap:nowrap;align-items:center">
                <button class="btn btn-outline btn-sm" onclick='isiFormEdit(<?= json_encode($s) ?>)'>✏️</button>
                <?php if($bisaNaik && $s['status']==='aktif'): ?>
                  <button class="btn-naik-single" onclick='bukaNaikSingle(<?= json_encode($s) ?>)' title="Naik kelas">⬆️</button>
                <?php endif ?>
                <?php if($s['status']==='aktif'): ?>
                  <button class="btn-pindah-single" onclick='bukaPindahSingle(<?= json_encode($s) ?>)' title="Pindah kelas">🔀</button>
                <?php endif ?>
                <?php if($s['status']==='aktif'): ?>
                <form method="POST" style="display:inline" onsubmit="return confirm('Nonaktifkan siswa ini?')">
                  <input type="hidden" name="action" value="nonaktif">
                  <input type="hidden" name="id" value="<?= $s['id'] ?>">
                  <button class="btn btn-sm" style="background:#FEF3C7;color:#92400E;border:none" type="submit">🚫</button>
                </form>
                <?php else: ?>
                <form method="POST" style="display:inline" onsubmit="return confirm('Aktifkan kembali?')">
                  <input type="hidden" name="action" value="aktifkan">
                  <input type="hidden" name="id" value="<?= $s['id'] ?>">
                  <button class="btn btn-sm" style="background:#D1FAE5;color:#065F46;border:none" type="submit">✅</button>
                </form>
                <?php endif ?>
                <form method="POST" style="display:inline" onsubmit="return confirm('Hapus permanen?')">
                  <input type="hidden" name="action" value="hapus">
                  <input type="hidden" name="id" value="<?= $s['id'] ?>">
                  <button class="btn btn-danger btn-sm" type="submit">🗑️</button>
                </form>
              </div>
            </td>
          </tr>
        <?php endforeach; endif ?>
        </tbody>
      </table>
    </div>
    <div id="paging-table"></div>
  </div>

  <!-- CARD VIEW -->
  <div id="siswa-view-cards" class="siswa-view-wrap" style="display:none">
    <?php if(empty($siswas)): ?>
      <div style="padding:32px">
        <div class="empty-state">
          <div class="empty-state-icon">🎒</div>
          <h4>Belum ada data siswa</h4>
          <p>Klik "Tambah Siswa" atau "Impor CSV" untuk mulai menambahkan data</p>
        </div>
      </div>
    <?php else: ?>
    <div class="siswa-cards-scroll">
      <div class="siswa-cards" id="siswa-cards-grid">
        <?php
        $accentColors = ['#4F6EF7','#A855F7','#38BDF8','#34D399','#FB923C','#FBBF24','#818CF8','#F472B6'];
        foreach($siswas as $i=>$s):
          $c       = $avatarColors[$i % count($avatarColors)];
          $accent  = $accentColors[$i % count($accentColors)];
          $fotoAda = !empty($s['foto']) && file_exists($uploadAbs.$s['foto']);
          $isAktif = $s['status'] === 'aktif';
          $bisaNaik= in_array($s['kelas'], ['X','XI']) && $isAktif;
        ?>
        <div class="siswa-card" data-card="<?= $i ?>" style="animation-delay:<?= $i*30 ?>ms">
          <div class="siswa-card-bar" style="background:<?= $accent ?>22;border-top:3px solid <?= $accent ?>"></div>
          <div class="siswa-card-body">
            <div class="siswa-card-top">
              <?php if($fotoAda): ?>
                <img src="<?= e($uploadUrl.$s['foto']) ?>" class="siswa-card-photo" alt="">
              <?php else: ?>
                <div class="siswa-card-avatar" style="background:<?= $c ?>"><?= mb_strtoupper(mb_substr($s['nama'],0,1)) ?></div>
              <?php endif ?>
              <div style="min-width:0;flex:1">
                <div class="siswa-card-name"><?= e($s['nama']) ?></div>
                <span class="siswa-card-nis"><?= e($s['nis']) ?></span>
              </div>
              <div class="siswa-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">⛔ Non</span>
                <?php endif ?>
              </div>
            </div>
            <hr class="siswa-card-hr">
            <div class="siswa-card-rows">
              <div class="siswa-card-row">
                <span class="siswa-card-row-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="M22 10v6M2 10l10-5 10 5-10 5z"/><path d="M6 12v5c3 3 9 3 12 0v-5"/></svg>
                  Kelas
                </span>
                <div style="display:flex;gap:4px">
                  <span class="pill pill-purple" style="font-size:11px;padding:2px 8px"><?= e($s['kelas']) ?></span>
                  <span class="pill pill-blue"   style="font-size:11px;padding:2px 8px"><?= e($s['jurusan']) ?></span>
                </div>
              </div>
              <div class="siswa-card-row">
                <span class="siswa-card-row-label">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                  Tahun Ajaran
                </span>
                <span style="font-size:12px;color:var(--text2)"><?= e($s['tahun_ajaran']) ?></span>
              </div>
              <div class="siswa-card-row">
                <span class="siswa-card-row-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="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.15 12a19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 3.07 1h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.09 8.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 21 16z"/></svg>
                  No. HP
                </span>
                <span style="font-size:12px;color:var(--text2)"><?= e($s['no_hp'] ?: '–') ?></span>
              </div>
            </div>
          </div>
          <div class="siswa-card-footer">
            <button class="btn btn-outline btn-sm" onclick='isiFormEdit(<?= json_encode($s) ?>)' style="font-size:11.5px">✏️ Edit</button>
            <?php if($bisaNaik): ?>
              <button class="btn-naik-single" onclick='bukaNaikSingle(<?= json_encode($s) ?>)' style="font-size:11.5px;flex:1;justify-content:center">⬆️ Naik Kelas</button>
            <?php elseif($s['kelas']==='XII' && $isAktif): ?>
              <span style="font-size:11px;color:var(--text3);padding:4px 8px;border-radius:6px;background:var(--surface2);flex:1;text-align:center">🎓 Kelas XII</span>
            <?php endif ?>
            <?php if($isAktif): ?>
              <button class="btn-pindah-single" onclick='bukaPindahSingle(<?= json_encode($s) ?>)' style="font-size:11.5px" title="Pindah kelas">🔀</button>
            <?php endif ?>
            <?php if($isAktif): ?>
            <form method="POST" onsubmit="return confirm('Nonaktifkan siswa ini?')">
              <input type="hidden" name="action" value="nonaktif">
              <input type="hidden" name="id" value="<?= $s['id'] ?>">
              <button class="btn btn-sm" style="background:#FEF3C7;color:#92400E;border:none;font-size:11.5px" type="submit">🚫</button>
            </form>
            <?php else: ?>
            <form method="POST" onsubmit="return confirm('Aktifkan kembali?')">
              <input type="hidden" name="action" value="aktifkan">
              <input type="hidden" name="id" value="<?= $s['id'] ?>">
              <button class="btn btn-sm" style="background:#D1FAE5;color:#065F46;border:none;font-size:11.5px" type="submit">✅</button>
            </form>
            <?php endif ?>
            <form method="POST" onsubmit="return confirm('Hapus permanen?')">
              <input type="hidden" name="action" value="hapus">
              <input type="hidden" name="id" value="<?= $s['id'] ?>">
              <button class="btn btn-danger btn-sm" style="font-size:11.5px" type="submit">🗑️</button>
            </form>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <div id="paging-cards"></div>
    <?php endif; ?>
  </div>
</div>


<!-- ══════════════════════════════════════════
     MODAL NAIK KELAS MASSAL
══════════════════════════════════════════ -->
<div class="modal-overlay" id="modalNaikMassal">
  <div class="modal" style="max-width:540px;overflow:hidden">
    <div class="modal-header" style="background:linear-gradient(135deg,#4F46E5,#7C3AED);border-radius:var(--radius) var(--radius) 0 0">
      <h3 style="color:#fff">⬆️ Kenaikan Kelas Massal</h3>
      <button class="modal-close" onclick="closeModal('modalNaikMassal')" style="color:#fff;opacity:.8">×</button>
    </div>
    <form method="POST" id="formNaikMassal" onsubmit="return konfirmasiNaikMassal(this)">
      <input type="hidden" name="action" value="naik_kelas_massal">
      <div class="modal-body" style="overflow-y:auto;max-height:calc(90vh - 130px)">

        <!-- Info mapping -->
        <div style="background:#F5F3FF;border-radius:12px;padding:14px 16px;margin-bottom:16px;border-left:4px solid #7C3AED;overflow:hidden">
          <div style="font-weight:700;font-size:13px;color:#4C1D95;margin-bottom:10px">🗺️ Peta Kenaikan Kelas (dari database)</div>
          <div style="overflow-x:auto">
            <table class="naik-preview-table" style="min-width:280px">
              <thead><tr><th>Kelas Asal</th><th style="width:30px;text-align:center">→</th><th>Kelas Tujuan</th></tr></thead>
              <tbody>
                <?php foreach($naikkKelasMap as $tkt => $rombelMap): foreach($rombelMap as $dari => $ke): ?>
                <tr>
                  <td><span class="pill <?= $tkt==='X'?'pill-purple':'pill-blue' ?>"><?= e($tkt) ?> <?= e($dari) ?></span></td>
                  <td class="arrow-kelas" style="text-align:center">→</td>
                  <td><span class="pill" style="background:<?= $ke['kelas']==='XII'?'#D1FAE5':'#DBEAFE' ?>;color:<?= $ke['kelas']==='XII'?'#065F46':'#1E40AF' ?>"><?= e($ke['kelas']) ?> <?= e($ke['jurusan']) ?></span></td>
                </tr>
                <?php endforeach; endforeach; ?>
                <?php if(empty($naikkKelasMap)): ?>
                <tr><td colspan="3" style="text-align:center;color:var(--text3);font-size:12px;padding:10px">
                  ⚠️ Belum ada mapping — tambahkan kelas di halaman Kelas
                </td></tr>
                <?php endif ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Pilih kelas + rombel -->
        <div class="form-row" style="margin-bottom:14px">
          <div class="form-group" style="margin-bottom:0">
            <label>Kelas yang Dinaikkan <span style="color:red">*</span></label>
            <select name="kelas_massal" id="naikKelas" required onchange="syncNaikJurusan(this.value)">
              <option value="">– Pilih Kelas –</option>
              <?php if(isset($daftarJurusan['X'])): ?><option value="X">Kelas X (→ XI)</option><?php endif ?>
              <?php if(isset($daftarJurusan['XI'])): ?><option value="XI">Kelas XI (→ XII)</option><?php endif ?>
              <?php if(isset($daftarJurusan['XII'])): ?><option value="XII">Kelas XII (Kelulusan)</option><?php endif ?>
            </select>
          </div>
          <div class="form-group" style="margin-bottom:0">
            <label>Rombel <span style="color:var(--text3);font-weight:400;font-size:10px">(opsional)</span></label>
            <select name="jurusan_massal" id="naikJurusan">
              <option value="">— Semua Rombel —</option>
            </select>
          </div>
        </div>

        <!-- Tahun ajaran baru -->
        <div class="form-group" style="margin-bottom:12px">
          <label>Tahun Ajaran Baru <span style="color:var(--text3);font-weight:400;font-size:10px">(opsional)</span></label>
          <input type="text" name="tahun_baru_massal" id="naikTahunBaru"
                 placeholder="Contoh: 2025/2026"
                 value="<?= e($tahunAjaranList[0] ?? '') ?>">
          <div style="font-size:11.5px;color:var(--text3);margin-top:4px">Kosongkan jika tidak ingin mengubah tahun ajaran</div>
        </div>

        <!-- Opsi XII — diluluskan -->
        <div id="xiiOption" style="display:none;background:#FFFBEB;border:1.5px solid #FCD34D;border-radius:12px;padding:14px 16px;margin-top:8px">
          <div style="font-size:11px;font-weight:700;color:#92400E;text-transform:uppercase;letter-spacing:.06em;margin-bottom:10px">
            🎓 Opsi Kelulusan
          </div>
          <label style="display:flex;align-items:flex-start;gap:10px;cursor:pointer">
            <input type="checkbox" name="luluskan_xii" value="1"
                   style="width:16px;height:16px;margin-top:2px;flex-shrink:0;accent-color:#D97706">
            <div style="min-width:0">
              <div style="font-size:13px;color:#92400E;font-weight:600;line-height:1.4">
                Luluskan siswa kelas XII
              </div>
              <div style="font-size:11.5px;color:#B45309;margin-top:3px;line-height:1.5">
                Status siswa XII akan diubah menjadi <strong>Nonaktif</strong>.
                Siswa yang diluluskan tidak dapat naik kelas lagi.
              </div>
            </div>
          </label>
        </div>

        <!-- Preview jumlah siswa -->
        <div id="naikPreviewBox" style="display:none;margin-top:12px;background:var(--surface2);border-radius:10px;padding:12px 14px;border:1.5px solid var(--border)">
          <div style="font-size:12px;font-weight:600;color:var(--text2);margin-bottom:5px">📊 Siswa yang akan diproses:</div>
          <div id="naikPreviewContent" style="font-size:13px;color:var(--text);line-height:1.5;word-break:break-word"></div>
        </div>

        <!-- Peringatan -->
        <div style="background:#FEF3C7;border-radius:8px;padding:10px 12px;margin-top:12px;font-size:12px;color:#92400E;line-height:1.5">
          ⚠️ <strong>Peringatan:</strong> Proses ini tidak dapat dibatalkan. Pastikan data sudah benar sebelum melanjutkan.
        </div>

      </div><!-- /modal-body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalNaikMassal')">Batal</button>
        <button type="submit" id="btnNaikMassal" class="btn btn-primary" style="background:linear-gradient(135deg,#4F46E5,#7C3AED)">
          ⬆️ Proses Kenaikan Kelas
        </button>
      </div>
    </form>
  </div>
</div>


<!-- ══════════════════════════════════════════
     MODAL NAIK KELAS SINGLE
══════════════════════════════════════════ -->
<div class="modal-overlay" id="modalNaikSingle">
  <div class="modal" style="max-width:440px">
    <div class="modal-header" style="background:linear-gradient(135deg,#059669,#10B981);border-radius:var(--radius) var(--radius) 0 0">
      <h3 style="color:#fff">⬆️ Naik Kelas Siswa</h3>
      <button class="modal-close" onclick="closeModal('modalNaikSingle')" style="color:#fff;opacity:.8">×</button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="naik_kelas">
      <input type="hidden" name="id" id="naikSingleId">
      <div class="modal-body">
        <!-- Info siswa -->
        <div style="display:flex;align-items:center;gap:12px;padding:14px;background:var(--surface2);border-radius:12px;margin-bottom:16px">
          <div id="naikSingleAvatar" style="width:48px;height:48px;border-radius:12px;background:#10B981;display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:800;color:#fff;flex-shrink:0"></div>
          <div style="min-width:0;flex:1">
            <div id="naikSingleNama" style="font-weight:700;font-size:14px;color:var(--text)"></div>
            <div id="naikSingleNis"  style="font-size:11.5px;color:var(--text3);font-family:monospace;margin-top:2px"></div>
          </div>
        </div>
        <!-- Panah kelas -->
        <div style="display:flex;align-items:center;gap:10px;justify-content:center;padding:16px 0">
          <div style="text-align:center">
            <div style="font-size:11px;font-weight:600;color:var(--text3);margin-bottom:6px;text-transform:uppercase;letter-spacing:.06em">Kelas Sekarang</div>
            <span id="naikSingleDari" class="pill pill-purple" style="font-size:14px;padding:6px 16px;font-weight:700"></span>
          </div>
          <div style="font-size:22px;color:var(--candy-purple,#7C3AED);font-weight:900">→</div>
          <div style="text-align:center">
            <div style="font-size:11px;font-weight:600;color:var(--text3);margin-bottom:6px;text-transform:uppercase;letter-spacing:.06em">Kelas Baru</div>
            <span id="naikSingleKe" class="pill pill-blue" style="font-size:14px;padding:6px 16px;font-weight:700"></span>
          </div>
        </div>
        <!-- Tahun ajaran baru -->
        <div class="form-group" style="margin-top:8px">
          <label>Tahun Ajaran Baru <span style="font-weight:400;color:var(--text3)">(opsional)</span></label>
          <input type="text" name="tahun_baru" id="naikSingleTahun" placeholder="Contoh: 2025/2026">
          <div style="font-size:11.5px;color:var(--text3);margin-top:4px">Kosongkan jika tidak ingin mengubah tahun ajaran</div>
        </div>
        <div id="naikSingleWarning" style="display:none;background:#FEF3C7;border-radius:8px;padding:10px 12px;margin-top:8px;font-size:12px;color:#92400E"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalNaikSingle')">Batal</button>
        <button type="submit" class="btn btn-primary" style="background:linear-gradient(135deg,#059669,#10B981)">✅ Konfirmasi Naik Kelas</button>
      </div>
    </form>
  </div>
</div>


<!-- ══════════════════════════════════════════
     MODAL PINDAH KELAS
══════════════════════════════════════════ -->
<div class="modal-overlay" id="modalPindahSingle">
  <div class="modal" style="max-width:500px">
    <div class="modal-header" style="background:linear-gradient(135deg,#0369A1,#0EA5E9);border-radius:var(--radius) var(--radius) 0 0">
      <h3 style="color:#fff">🔀 Pindah Kelas Siswa</h3>
      <button class="modal-close" onclick="closeModal('modalPindahSingle')" style="color:#fff;opacity:.8">×</button>
    </div>
    <form method="POST" onsubmit="return konfirmasiPindah(this)">
      <input type="hidden" name="action" value="pindah_kelas">
      <input type="hidden" name="id" id="pindahId">
      <div class="modal-body">

        <!-- Info siswa -->
        <div style="display:flex;align-items:center;gap:12px;padding:14px;background:var(--surface2);border-radius:12px;margin-bottom:18px">
          <div id="pindahAvatar" style="width:48px;height:48px;border-radius:12px;background:#0EA5E9;display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:800;color:#fff;flex-shrink:0"></div>
          <div style="min-width:0;flex:1">
            <div id="pindahNama" style="font-weight:700;font-size:14px;color:var(--text)"></div>
            <div id="pindahNis"  style="font-size:11.5px;color:var(--text3);font-family:monospace;margin-top:2px"></div>
          </div>
          <div>
            <div style="font-size:11px;color:var(--text3);margin-bottom:4px;text-align:right">Kelas Sekarang</div>
            <span id="pindahKelasSekarang" class="pill pill-purple" style="font-size:13px;padding:4px 12px;font-weight:700"></span>
          </div>
        </div>

        <!-- Pilih kelas tujuan -->
        <div style="background:#E0F2FE;border-radius:12px;padding:14px 16px;margin-bottom:16px;border-left:4px solid #0369A1">
          <div style="font-weight:700;font-size:13px;color:#0C4A6E;margin-bottom:12px">🎯 Kelas Tujuan</div>
          <div class="form-row" style="margin-bottom:0">
            <div class="form-group" style="margin-bottom:0">
              <label style="font-size:12px">Tingkat Kelas <span style="color:red">*</span></label>
              <select name="kelas_pindah" id="pindahKelasTarget" required
                      onchange="syncPindahJurusan(this.value)"
                      style="border-color:#7DD3FC">
                <option value="">– Pilih Kelas –</option>
                <option value="X">Kelas X</option>
                <option value="XI">Kelas XI</option>
                <option value="XII">Kelas XII</option>
              </select>
            </div>
            <div class="form-group" style="margin-bottom:0">
              <label style="font-size:12px">Rombel / Jurusan <span style="color:red">*</span></label>
              <select name="jurusan_pindah" id="pindahJurusanTarget" required
                      style="border-color:#7DD3FC">
                <option value="">– Pilih Kelas dulu –</option>
              </select>
            </div>
          </div>
        </div>

        <!-- Preview panah asal → tujuan -->
        <div id="pindahArrowBox" style="display:none;align-items:center;gap:10px;justify-content:center;padding:12px 0 4px">
          <div style="text-align:center">
            <div style="font-size:10px;font-weight:700;color:var(--text3);margin-bottom:5px;text-transform:uppercase;letter-spacing:.06em">Dari</div>
            <span id="pindahArrowDari" class="pill pill-purple" style="font-size:13px;padding:4px 14px;font-weight:700"></span>
          </div>
          <div style="font-size:24px;color:#0369A1;font-weight:900">→</div>
          <div style="text-align:center">
            <div style="font-size:10px;font-weight:700;color:var(--text3);margin-bottom:5px;text-transform:uppercase;letter-spacing:.06em">Ke</div>
            <span id="pindahArrowKe" class="pill" style="background:#E0F2FE;color:#0369A1;font-size:13px;padding:4px 14px;font-weight:700"></span>
          </div>
        </div>

        <!-- Sama-kelas warning -->
        <div id="pindahSamaWarning" style="display:none;background:#FEF3C7;border-radius:8px;padding:9px 12px;margin-top:8px;font-size:12px;color:#92400E">
          ⚠️ Siswa sudah berada di kelas ini. Pilih kelas yang berbeda.
        </div>

        <!-- Tahun ajaran & alasan -->
        <div class="form-row" style="margin-top:14px">
          <div class="form-group">
            <label>Tahun Ajaran <span style="font-weight:400;color:var(--text3)">(opsional)</span></label>
            <input type="text" name="tahun_baru_pindah" id="pindahTahun" placeholder="Contoh: 2025/2026">
          </div>
          <div class="form-group">
            <label>Alasan Pindah <span style="font-weight:400;color:var(--text3)">(opsional)</span></label>
            <input type="text" name="alasan_pindah" id="pindahAlasan" placeholder="Contoh: permintaan orang tua">
          </div>
        </div>

        <div style="background:#F0F9FF;border-radius:8px;padding:10px 12px;font-size:12px;color:#0369A1;margin-top:2px">
          ℹ️ Riwayat pindah kelas akan dicatat jika tabel <code>riwayat_pindah_kelas</code> tersedia di database.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalPindahSingle')">Batal</button>
        <button type="submit" id="btnPindah" class="btn btn-primary" style="background:linear-gradient(135deg,#0369A1,#0EA5E9)" disabled>
          🔀 Konfirmasi Pindah Kelas
        </button>
      </div>
    </form>
  </div>
</div>


<!-- ═══ Modal Impor CSV ═══ -->
<div class="modal-overlay" id="modalImpor">
  <div class="modal" style="max-width:520px">
    <div class="modal-header">
      <h3>📥 Impor Data Siswa dari CSV</h3>
      <button class="modal-close" onclick="closeModal('modalImpor')">×</button>
    </div>
    <form method="POST" enctype="multipart/form-data" id="formImpor" onsubmit="return submitImpor(this)">
      <input type="hidden" name="action" value="impor_csv">
      <div class="modal-body">
        <div style="background:#F0FDFA;border-radius:12px;padding:14px 16px;margin-bottom:16px;border-left:4px solid #0D9488">
          <div style="font-weight:700;font-size:13px;color:#134E4A;margin-bottom:8px">📋 Format CSV yang diperlukan:</div>
          <div style="font-family:monospace;font-size:11.5px;background:#fff;border-radius:8px;padding:10px;color:#374151;line-height:1.8;overflow-x:auto;white-space:nowrap">
            NIS, Nama, Kelas, Jurusan, Tahun Ajaran, No HP, Alamat, Status<br>
            2401001, Andi Pratama, X 1, IPA, 2024/2025, 081234567890, Jl. Merdeka, aktif
          </div>
        </div>
        <div id="dropZone"
             style="border:2px dashed #0D9488;border-radius:12px;padding:24px;text-align:center;cursor:pointer;transition:.2s;background:#F0FDFA"
             onclick="document.getElementById('fileCsv').click()"
             ondragover="event.preventDefault();this.style.background='#CCFBF1'"
             ondragleave="this.style.background='#F0FDFA'"
             ondrop="handleDrop(event)">
          <div style="font-size:32px;margin-bottom:8px">📂</div>
          <div id="dropLabel" style="font-size:13px;font-weight:600;color:#134E4A">Klik atau seret file CSV ke sini</div>
          <div style="font-size:11px;color:#6B7280;margin-top:4px">Format: .csv — Maksimal 5MB</div>
          <input type="file" id="fileCsv" name="file_csv" accept=".csv,text/csv" style="display:none"
                 onchange="tampilNamaFile(this)">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-outline" onclick="closeModal('modalImpor')">Batal</button>
        <button type="submit" id="btnImpor" class="btn btn-primary" style="background:#0D9488">📥 Impor Sekarang</button>
      </div>
    </form>
  </div>
</div>

<!-- ═══ Modal Tambah ═══ -->
<div class="modal-overlay" id="modalTambah">
  <div class="modal">
    <div class="modal-header">
      <h3>➕ Tambah Siswa Baru</h3>
      <button class="modal-close" onclick="closeModal('modalTambah')">×</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="tambah">
      <div class="modal-body">
        <div class="form-group">
          <label>Foto Siswa (opsional)</label>
          <div class="siswa-foto-zone" onclick="document.getElementById('fotoTambah').click()">
            <div id="prevFotoTambah" class="siswa-foto-preview">
              <span style="font-size:28px">📷</span>
              <div style="font-size:12px;color:var(--text2);margin-top:4px">Klik untuk upload foto</div>
              <div style="font-size:11px;color:var(--text3)">JPG, PNG, WEBP — maks 2MB</div>
            </div>
            <input type="file" id="fotoTambah" name="foto" accept="image/jpeg,image/png,image/webp" style="display:none"
                   onchange="prevSiswaFoto(this,'prevFotoTambah')">
          </div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>NIS</label><input name="nis" required placeholder="2401011"></div>
          <div class="form-group"><label>Tahun Ajaran</label><input name="tahun_ajaran" required placeholder="2024/2025" value="2024/2025"></div>
        </div>
        <div class="form-group"><label>Nama Lengkap</label><input name="nama" required placeholder="Nama lengkap siswa"></div>
        <div class="form-row">
          <div class="form-group">
            <label>Kelas</label>
            <select name="kelas" id="tambahKelas" required onchange="syncJurusan(this.value,'tambahJurusan')">
              <option value="">– Pilih Kelas –</option>
              <option value="X">X</option>
              <option value="XI">XI</option>
              <option value="XII">XII</option>
            </select>
          </div>
          <div class="form-group">
            <label>Rombel / Jurusan</label>
            <select name="jurusan" id="tambahJurusan" required>
              <option value="">– Pilih Kelas dulu –</option>
            </select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>No. HP</label><input name="no_hp" placeholder="08xxxxxxxxxx" type="tel"></div>
          <div class="form-group"><label>Status</label>
            <select name="status">
              <option value="aktif">✅ Aktif</option>
              <option value="nonaktif">⛔ Nonaktif</option>
            </select>
          </div>
        </div>
        <div class="form-group"><label>Alamat</label><textarea name="alamat" rows="2" placeholder="Alamat lengkap"></textarea></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</button>
      </div>
    </form>
  </div>
</div>

<!-- ═══ Modal Edit ═══ -->
<div class="modal-overlay" id="modalEdit">
  <div class="modal">
    <div class="modal-header">
      <h3>✏️ Edit Data Siswa</h3>
      <button class="modal-close" onclick="closeModal('modalEdit')">×</button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="id" id="editId">
      <div class="modal-body">
        <div class="form-group">
          <label>Foto Siswa</label>
          <div style="display:flex;align-items:center;gap:14px">
            <div id="editFotoDisplay" style="width:60px;height:60px;border-radius:14px;overflow:hidden;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:24px;flex-shrink:0;border:2px solid var(--border)"></div>
            <div style="flex:1">
              <div class="siswa-foto-zone" onclick="document.getElementById('fotoEdit').click()" style="min-height:54px">
                <div id="prevFotoEdit" class="siswa-foto-preview" style="padding:10px 8px">
                  <span style="font-size:20px">📷</span>
                  <div style="font-size:11px;color:var(--text2);margin-top:2px">Klik untuk ganti foto</div>
                </div>
                <input type="file" id="fotoEdit" name="foto" accept="image/jpeg,image/png,image/webp" style="display:none"
                       onchange="prevSiswaFoto(this,'prevFotoEdit','editFotoDisplay')">
              </div>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>NIS</label><input name="nis" id="editNis" required></div>
          <div class="form-group"><label>Tahun Ajaran</label><input name="tahun_ajaran" id="editTahun" required></div>
        </div>
        <div class="form-group"><label>Nama Lengkap</label><input name="nama" id="editNama" required></div>
        <div class="form-row">
          <div class="form-group">
            <label>Kelas</label>
            <select name="kelas" id="editKelas" required onchange="syncJurusan(this.value,'editJurusan')">
              <option value="X">X</option>
              <option value="XI">XI</option>
              <option value="XII">XII</option>
            </select>
          </div>
          <div class="form-group">
            <label>Rombel / Jurusan</label>
            <select name="jurusan" id="editJurusan" required>
              <option value="">– Pilih –</option>
            </select>
          </div>
        </div>
        <div class="form-row">
          <div class="form-group"><label>No. HP</label><input name="no_hp" id="editHp" type="tel"></div>
          <div class="form-group"><label>Status</label>
            <select name="status" id="editStatus">
              <option value="aktif">✅ Aktif</option>
              <option value="nonaktif">⛔ Nonaktif</option>
            </select>
          </div>
        </div>
        <div class="form-group"><label>Alamat</label><textarea name="alamat" id="editAlamat" rows="2"></textarea></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>

<style>
.siswa-foto-zone { border:2px dashed var(--border);border-radius:var(--radius-sm);cursor:pointer;transition:border-color .2s,background .2s;overflow:hidden }
.siswa-foto-zone:hover { border-color:var(--candy-purple);background:var(--surface2) }
.siswa-foto-preview { padding:14px;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:80px;gap:2px }
.siswa-foto-preview img { width:56px;height:56px;border-radius:10px;object-fit:cover;margin-bottom:4px }
</style>

<script>
const uploadUrl = '<?= $uploadUrl ?>';

/* ══ Mapping jurusan — diambil DINAMIS dari DB via PHP ══ */
const jurusanMap = <?= json_encode(
    array_map(fn($jList) => array_values($jList), $daftarJurusan),
    JSON_UNESCAPED_UNICODE
) ?>;

/* ══ Mapping naik kelas — diambil DINAMIS dari DB via PHP ══ */
const naikKelasMap = <?= json_encode($naikkKelasMap, JSON_UNESCAPED_UNICODE) ?>;

/* ══ Data jumlah siswa per kelas (untuk preview massal) ══ */
const previewNaik = <?= json_encode($previewNaik) ?>;

/* ════ Sync jurusan dropdown ════ */
function syncJurusan(kelas, targetId, selected) {
  const sel  = document.getElementById(targetId);
  const opts = jurusanMap[kelas] || [];
  sel.innerHTML = '<option value="">– Pilih –</option>';
  opts.forEach(function(j) {
    const opt = document.createElement('option');
    opt.value = j;
    opt.textContent = kelas + ' ' + j;
    sel.appendChild(opt);
  });
  if (selected) sel.value = selected;
}

/* ════ Sync jurusan modal naik kelas massal ════ */
function syncNaikJurusan(kelas) {
  const sel  = document.getElementById('naikJurusan');
  const opts = jurusanMap[kelas] || [];
  sel.innerHTML = '<option value="">— Semua Rombel —</option>';
  opts.forEach(function(j) {
    const opt = document.createElement('option');
    opt.value = j;
    opt.textContent = kelas + ' ' + j;
    sel.appendChild(opt);
  });
  // Tampil/sembunyikan opsi kelulusan XII
  document.getElementById('xiiOption').style.display = (kelas === 'XII') ? 'block' : 'none';
  // Update preview
  updateNaikPreview(kelas, '');
  sel.onchange = function() { updateNaikPreview(kelas, this.value); };
}

/* Preview jumlah siswa naik massal */
function updateNaikPreview(kelas, jurusan) {
  const box = document.getElementById('naikPreviewBox');
  const cnt = document.getElementById('naikPreviewContent');
  if (!kelas) { box.style.display = 'none'; return; }
  box.style.display = 'block';
  let html = '';
  if (kelas === 'XII') {
    html = `<span style="color:var(--text3);font-size:13px">🎓 Siswa kelas XII akan diluluskan (jika opsi dicentang), bukan naik kelas</span>`;
  } else {
    const target = kelas === 'X' ? 'XI' : 'XII';
    html = `Siswa kelas <b>${kelas}</b>${jurusan?' rombel '+jurusan:''} akan dipindah ke kelas <b>${target}</b> sesuai peta mapping.`;
  }
  cnt.innerHTML = html;
}

/* ════ Live DOM search ════ */
var _siswaSearchTimer = null;
var _siswaAllRowData  = null;
var _siswaAllCardData = null;

function siswaDomSearch(q) {
  clearTimeout(_siswaSearchTimer);
  _siswaSearchTimer = setTimeout(function() {
    q = q.trim().toLowerCase();

    /* Cache semua baris saat pertama kali */
    if (!_siswaAllRowData) {
      _siswaAllRowData = Array.from(
        document.querySelectorAll('#siswa-tbody tr[data-row]')
      ).map(function(r) {
        return { el: r, text: (r.textContent || '').toLowerCase() };
      });
    }
    if (!_siswaAllCardData) {
      _siswaAllCardData = Array.from(
        document.querySelectorAll('#siswa-cards-grid .siswa-card[data-card]')
      ).map(function(c) {
        return { el: c, text: (c.textContent || '').toLowerCase() };
      });
    }

    /* Filter dan assign data-row ulang secara berurutan */
    var rowIdx = 0, cardIdx = 0;
    _siswaAllRowData.forEach(function(item) {
      if (!q || item.text.includes(q)) {
        item.el.dataset.row = rowIdx++;
        item.el.style.display = '';
      } else {
        item.el.style.display = 'none';
        item.el.dataset.row   = '-1'; /* tandai: tidak aktif */
      }
    });
    _siswaAllCardData.forEach(function(item) {
      if (!q || item.text.includes(q)) {
        item.el.dataset.card = cardIdx++;
        item.el.style.display = '';
      } else {
        item.el.style.display = 'none';
        item.el.dataset.card  = '-1';
      }
    });

    /* Re-render pagination berdasarkan indeks baru */
    renderTable(0);
    renderCards(0);

    /* Update label jumlah */
    var pill = document.querySelector('#siswa-view-table .pill.pill-purple, .card .pill.pill-purple');
    if (pill) pill.textContent = rowIdx + ' siswa';

  }, 250);
}

function siswaSearchSubmit() {
  var q = document.getElementById('siswaSearchInput').value;
  document.getElementById('siswaSearchQ').value = q;
  document.getElementById('siswaSearchForm').submit();
}

function siswaClearSearch() {
  window.location = 'index.php?page=siswa'
    + '&status=<?= rawurlencode($status) ?>'
    + '&kelas=<?= rawurlencode($kelas) ?>'
    + '&jurusan=<?= rawurlencode($jurusan) ?>';
}

var _origSiswaSwitchView = window.siswaSwitchView;
window.siswaSwitchView = function(mode) {
  _siswaAllRowData  = null;
  _siswaAllCardData = null;
  _origSiswaSwitchView(mode);
  var q = document.getElementById('siswaSearchInput');
  if (q && q.value.trim()) siswaDomSearch(q.value);
};
var _pindahSiswa = null; // data siswa yang sedang dipindah

/* ════ Buka modal pindah kelas single ════ */
function bukaPindahSingle(s) {
  _pindahSiswa = s;
  document.getElementById('pindahId').value   = s.id;
  document.getElementById('pindahNama').textContent = s.nama;
  document.getElementById('pindahNis').textContent  = s.nis;
  document.getElementById('pindahAvatar').textContent = s.nama.charAt(0).toUpperCase();
  document.getElementById('pindahKelasSekarang').textContent = s.kelas + ' ' + s.jurusan;

  // Reset form
  document.getElementById('pindahKelasTarget').value = '';
  document.getElementById('pindahJurusanTarget').innerHTML = '<option value="">– Pilih Kelas dulu –</option>';
  document.getElementById('pindahTahun').value   = '';
  document.getElementById('pindahAlasan').value  = '';
  document.getElementById('pindahArrowBox').style.display    = 'none';
  document.getElementById('pindahSamaWarning').style.display = 'none';
  document.getElementById('btnPindah').disabled = true;

  openModal('modalPindahSingle');
}

/* ════ Sync jurusan dropdown modal pindah ════ */
function syncPindahJurusan(kelas) {
  const sel  = document.getElementById('pindahJurusanTarget');
  const opts = jurusanMap[kelas] || [];
  sel.innerHTML = '<option value="">– Pilih Rombel –</option>';
  opts.forEach(function(j) {
    const opt = document.createElement('option');
    opt.value = j;
    opt.textContent = kelas + ' ' + j;
    sel.appendChild(opt);
  });
  // Reset arrow & disable tombol
  document.getElementById('pindahArrowBox').style.display    = 'none';
  document.getElementById('pindahSamaWarning').style.display = 'none';
  document.getElementById('btnPindah').disabled = true;

  sel.onchange = function() { updatePindahArrow(kelas, this.value); };
}

/* ════ Update preview panah pindah ════ */
function updatePindahArrow(kelas, jurusan) {
  const arrowBox = document.getElementById('pindahArrowBox');
  const sameWarn = document.getElementById('pindahSamaWarning');
  const btnP     = document.getElementById('btnPindah');

  if (!kelas || !jurusan) {
    arrowBox.style.display = 'none';
    sameWarn.style.display = 'none';
    btnP.disabled = true;
    return;
  }

  const dari = (_pindahSiswa.kelas + ' ' + _pindahSiswa.jurusan);
  const ke   = (kelas + ' ' + jurusan);
  const sama = (_pindahSiswa.kelas === kelas && _pindahSiswa.jurusan === jurusan);

  document.getElementById('pindahArrowDari').textContent = dari;
  document.getElementById('pindahArrowKe').textContent   = ke;
  arrowBox.style.display = 'flex';
  sameWarn.style.display = sama ? 'block' : 'none';
  btnP.disabled = sama;
}

/* ════ Konfirmasi submit pindah kelas ════ */
function konfirmasiPindah(form) {
  const kelas   = form.kelas_pindah.value;
  const jurusan = form.jurusan_pindah.value;
  if (!kelas || !jurusan) { alert('⚠️ Pilih kelas dan rombel tujuan terlebih dahulu'); return false; }
  const nama = _pindahSiswa ? _pindahSiswa.nama : 'Siswa';
  return confirm('Pindahkan ' + nama + ' ke kelas ' + kelas + ' ' + jurusan + '?\nTindakan ini tidak dapat dibatalkan.');
}

/* ════ Buka modal naik kelas single ════ */
function bukaNaikSingle(s) {
  document.getElementById('naikSingleId').value = s.id;
  document.getElementById('naikSingleNama').textContent = s.nama;
  document.getElementById('naikSingleNis').textContent  = s.nis;
  // Avatar huruf
  const av = document.getElementById('naikSingleAvatar');
  av.textContent = s.nama.charAt(0).toUpperCase();
  // Mapping tujuan
  const warn = document.getElementById('naikSingleWarning');
  const dari = s.kelas + ' ' + s.jurusan;
  document.getElementById('naikSingleDari').textContent = dari;
  const map = (naikKelasMap[s.kelas] || {})[s.jurusan];
  if (map) {
    document.getElementById('naikSingleKe').textContent = map.kelas + ' ' + map.jurusan;
    warn.style.display = 'none';
  } else {
    document.getElementById('naikSingleKe').textContent = '???';
    warn.style.display  = 'block';
    warn.textContent    = '⚠️ Mapping kelas tujuan tidak ditemukan. Hubungi admin.';
  }
  document.getElementById('naikSingleTahun').value = '';
  openModal('modalNaikSingle');
}

/* ════ Konfirmasi submit naik massal ════ */
function konfirmasiNaikMassal(form) {
  const kelas = form.kelas_massal.value;
  if (!kelas) { alert('⚠️ Pilih kelas yang akan dinaikkan'); return false; }
  const label = kelas === 'XII' ? 'diluluskan (nonaktif)' : 'naik kelas';
  return confirm('Proses kenaikan kelas untuk kelas ' + kelas + '?\nSiswa akan ' + label + '. Tindakan ini tidak dapat dibatalkan.');
}

/* ════ Pagination ════ */
var siswaPerPage = parseInt(localStorage.getItem('siswa_per_page') || '10');
(function() { var sel = document.getElementById('siswaPerPage'); if(sel) sel.value = String(siswaPerPage); })();
window.siswaOnPerPage = function(val) { siswaPerPage = parseInt(val); localStorage.setItem('siswa_per_page', val); renderTable(0); renderCards(0); };

/* ════ View toggle ════ */
(function() {
  var saved = localStorage.getItem('siswa_view') || 'table';
  applyView(saved);
  function applyView(mode) {
    var isTable = mode === 'table';
    document.getElementById('siswa-view-table').style.display = isTable ? 'flex' : 'none';
    document.getElementById('siswa-view-cards').style.display = isTable ? 'none' : 'flex';
    document.getElementById('siswa-btn-table').classList.toggle('active',  isTable);
    document.getElementById('siswa-btn-cards').classList.toggle('active', !isTable);
  }
  window.siswaSwitchView = function(mode) {
    localStorage.setItem('siswa_view', mode);
    applyView(mode);
    if (mode === 'table') renderTable(0); else renderCards(0);
  };
})();

function renderTable(p) {
  var container = document.getElementById('siswa-view-table');
  var wasHidden = container && container.style.display === 'none';
  if (wasHidden) {
    container.style.visibility = 'hidden';
    container.style.display    = 'flex';
  }

  /* Hanya ambil baris yang aktif (data-row != -1, bukan yang disembunyikan live search) */
  var allRows    = document.querySelectorAll('#siswa-tbody tr[data-row]');
  var activeRows = Array.from(allRows).filter(function(r) {
    return r.dataset.row !== '-1';
  });
  var total = activeRows.length;
  var start = p * siswaPerPage;

  /* Sembunyikan dulu semua, lalu tampilkan yang masuk halaman ini */
  activeRows.forEach(function(r, i) {
    r.style.display = (i >= start && i < start + siswaPerPage) ? '' : 'none';
  });

  buildPager('paging-table', total, siswaPerPage, p, renderTable);
  var sc = document.querySelector('.siswa-tbl-scroll');
  if (sc && p > 0) sc.scrollTop = 0;

  if (wasHidden) {
    container.style.display    = 'none';
    container.style.visibility = '';
  }
}

function renderCards(p) {
  var container = document.getElementById('siswa-view-cards');
  var wasHidden = container && container.style.display === 'none';
  if (wasHidden) {
    container.style.visibility = 'hidden';
    container.style.display    = 'flex';
  }

  var allCards    = document.querySelectorAll('#siswa-cards-grid .siswa-card[data-card]');
  var activeCards = Array.from(allCards).filter(function(c) {
    return c.dataset.card !== '-1';
  });
  var total = activeCards.length;
  var start = p * siswaPerPage;

  activeCards.forEach(function(c, i) {
    c.style.display = (i >= start && i < start + siswaPerPage) ? '' : 'none';
  });

  buildPager('paging-cards', total, siswaPerPage, p, renderCards);
  var sc = document.querySelector('.siswa-cards-scroll');
  if (sc && p > 0) sc.scrollTop = 0;

  if (wasHidden) {
    container.style.display    = 'none';
    container.style.visibility = '';
  }
}

function buildPager(containerId, total, perPage, current, cb) {
  var wrap = document.getElementById(containerId);
  if (!wrap) return;
  var totalPages = Math.ceil(total / perPage);
  if (totalPages <= 1) { wrap.innerHTML = ''; return; }
  var from = current * perPage + 1;
  var to   = Math.min((current+1)*perPage, total);
  var html = '<div class="siswa-pager">';
  html += '<span class="pager-info">Menampilkan <b>'+from+'–'+to+'</b> dari <b>'+total+'</b></span>';
  html += '<div class="pager-btns">';
  html += '<button class="pager-btn'+(current===0?' disabled':'')+'" data-p="'+(current-1)+'"'+(current===0?' disabled':'')+'>‹ Prev</button>';
  var winStart = Math.max(0, current-2), winEnd = Math.min(totalPages-1, current+2);
  if (winStart > 0) { html += '<button class="pager-btn" data-p="0">1</button>'; if(winStart>1) html += '<span class="pager-ellipsis">…</span>'; }
  for (var i=winStart; i<=winEnd; i++) html += '<button class="pager-btn'+(i===current?' active':'')+'" data-p="'+i+'">'+(i+1)+'</button>';
  if (winEnd < totalPages-1) { if(winEnd<totalPages-2) html += '<span class="pager-ellipsis">…</span>'; html += '<button class="pager-btn" data-p="'+(totalPages-1)+'">'+totalPages+'</button>'; }
  html += '<button class="pager-btn'+(current===totalPages-1?' disabled':'')+'" data-p="'+(current+1)+'"'+(current===totalPages-1?' disabled':'')+'>Next ›</button>';
  html += '</div></div>';
  wrap.innerHTML = html;
  wrap.querySelectorAll('.pager-btn:not(.disabled)').forEach(function(btn) {
    btn.addEventListener('click', function() { cb(parseInt(this.dataset.p)); });
  });
}

/* ── Init: render kedua view agar pagination terbentuk di keduanya ── */
renderTable(0);
renderCards(0);

/* ════ Download Template CSV ════ */
function downloadTemplate() {
  const bom  = '\uFEFF';
  const head = 'NIS,Nama,Kelas,Jurusan,Tahun Ajaran,No HP,Alamat,Status\n';
  const rows = [
    '2401001,Andi Pratama,X,1,2024/2025,081234567890,Jl. Merdeka No.1,aktif',
    '2401002,Budi Santoso,XI,A-1,2024/2025,081234567891,Jl. Pahlawan No.2,aktif',
    '2401003,Citra Dewi,XII,IPA 1,2024/2025,081234567892,Jl. Kenangan No.3,aktif',
  ].join('\n');
  const blob = new Blob([bom+head+rows], {type:'text/csv;charset=utf-8'});
  const url  = URL.createObjectURL(blob);
  const a    = document.createElement('a');
  a.href=url; a.download='template_siswa.csv'; a.click();
  URL.revokeObjectURL(url);
}

/* ════ Submit Impor ════ */
function submitImpor(form) {
  const fileInput = document.getElementById('fileCsv');
  if (!fileInput.files || !fileInput.files[0]) { alert('⚠️ Pilih file CSV terlebih dahulu!'); return false; }
  setTimeout(function() {
    var btn=document.getElementById('btnImpor');
    if(btn){btn.disabled=true;btn.textContent='⏳ Mengimpor...';}
  }, 0);
  return true;
}

function tampilNamaFile(input) {
  if (input.files && input.files[0]) {
    const f = input.files[0];
    if (!f.name.toLowerCase().endsWith('.csv')) { alert('⚠️ Harap pilih file berformat .csv'); input.value=''; return; }
    document.getElementById('dropLabel').textContent = '✅ '+f.name+' ('+(f.size/1024).toFixed(1)+' KB)';
    document.getElementById('dropZone').style.background  = '#CCFBF1';
    document.getElementById('dropZone').style.borderColor = '#059669';
  }
}

function handleDrop(e) {
  e.preventDefault();
  document.getElementById('dropZone').style.background = '#F0FDFA';
  const file = e.dataTransfer.files[0];
  if (file && file.name.toLowerCase().endsWith('.csv')) {
    const input = document.getElementById('fileCsv');
    const dt = new DataTransfer(); dt.items.add(file); input.files = dt.files;
    tampilNamaFile(input);
  } else { alert('⚠️ Harap upload file berformat .csv'); }
}

/* ════ Edit Siswa ════ */
function isiFormEdit(s) {
  document.getElementById('editId').value      = s.id;
  document.getElementById('editNis').value     = s.nis;
  document.getElementById('editNama').value    = s.nama;
  document.getElementById('editKelas').value   = s.kelas;
  syncJurusan(s.kelas, 'editJurusan', s.jurusan);
  document.getElementById('editTahun').value   = s.tahun_ajaran;
  document.getElementById('editHp').value      = s.no_hp   || '';
  document.getElementById('editAlamat').value  = s.alamat  || '';
  document.getElementById('editStatus').value  = s.status  || 'aktif';
  const disp = document.getElementById('editFotoDisplay');
  if (s.foto) {
    disp.innerHTML = '<img src="'+uploadUrl+s.foto+'" style="width:100%;height:100%;object-fit:cover">';
  } else {
    disp.textContent = s.nama.charAt(0).toUpperCase();
    disp.style.cssText = 'width:60px;height:60px;border-radius:14px;overflow:hidden;display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0;border:2px solid var(--border);font-family:inherit;font-weight:700;color:#fff;background:linear-gradient(135deg,#A855F7,#6366F1)';
  }
  document.getElementById('prevFotoEdit').innerHTML = '<span style="font-size:20px">📷</span><div style="font-size:11px;color:var(--text2);margin-top:2px">Klik untuk ganti foto</div>';
  document.getElementById('fotoEdit').value = '';
  openModal('modalEdit');
}

function prevSiswaFoto(input, previewId, displayId) {
  if (!input.files || !input.files[0]) return;
  const reader = new FileReader();
  reader.onload = e => {
    document.getElementById(previewId).innerHTML =
      '<img src="'+e.target.result+'"><div style="font-size:11px;color:#059669;font-weight:600;margin-top:2px">✅ '+input.files[0].name+'</div>';
    if (displayId) document.getElementById(displayId).innerHTML =
      '<img src="'+e.target.result+'" style="width:100%;height:100%;object-fit:cover">';
  };
  reader.readAsDataURL(input.files[0]);
}
</script>

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