<?php
session_start();
if(!isset($_SESSION['login'])){ header("Location: login.php"); exit(); }
include 'koneksi.php';

// ══════════════════════════════════════════════════════
//  DETEKSI KOLOM TABEL — cegah "Unknown column" error
// ══════════════════════════════════════════════════════
function getColumns($conn, $table){
    $cols = [];
    $r = mysqli_query($conn, "SHOW COLUMNS FROM `$table`");
    if($r) while($row = mysqli_fetch_assoc($r)) $cols[] = $row['Field'];
    return $cols;
}
$kelasKolom   = getColumns($conn, 'kelas');
$hasRuang     = in_array('ruang_kelas',  $kelasKolom);
$hasTahun     = in_array('tahun_ajaran', $kelasKolom);
$hasJurusan   = in_array('jurusan',      $kelasKolom);
$hasTingkat   = in_array('tingkat',      $kelasKolom);
$hasKapasitas = in_array('kapasitas',    $kelasKolom);
$hasWali      = in_array('wali_kelas',   $kelasKolom);

$siswaTabel = mysqli_query($conn, "SHOW TABLES LIKE 'siswa'");
$hasSiswaTbl = $siswaTabel && mysqli_num_rows($siswaTabel) > 0;
$siswaCols   = $hasSiswaTbl ? getColumns($conn, 'siswa') : [];
$hasKelasId  = in_array('kelas_id', $siswaCols);
$hasStatus   = in_array('status_siswa', $siswaCols);

$msg      = '';
$msg_type = '';
$editData = null;

/* ══ EKSPOR CSV ══ */
if(isset($_GET['export']) && $_GET['export'] === 'csv'){
    $result = mysqli_query($conn, "SELECT * FROM kelas ORDER BY nama_kelas");
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="data_kelas_'.date('Ymd_His').'.csv"');
    header('Cache-Control: no-cache, must-revalidate');
    $out = fopen('php://output', 'w');
    fputs($out, "\xEF\xBB\xBF");
    $hdr = ['Nama Kelas'];
    if($hasTingkat)   $hdr[] = 'Tingkat';
    if($hasJurusan)   $hdr[] = 'Jurusan';
    if($hasWali)      $hdr[] = 'Wali Kelas';
    if($hasKapasitas) $hdr[] = 'Kapasitas';
    if($hasRuang)     $hdr[] = 'Ruang Kelas';
    if($hasTahun)     $hdr[] = 'Tahun Ajaran';
    fputcsv($out, $hdr);
    while($row = mysqli_fetch_assoc($result)){
        $line = [$row['nama_kelas']??''];
        if($hasTingkat)   $line[] = $row['tingkat']??'';
        if($hasJurusan)   $line[] = $row['jurusan']??'';
        if($hasWali)      $line[] = $row['wali_kelas']??'';
        if($hasKapasitas) $line[] = $row['kapasitas']??'';
        if($hasRuang)     $line[] = $row['ruang_kelas']??'';
        if($hasTahun)     $line[] = $row['tahun_ajaran']??'';
        fputcsv($out, $line);
    }
    fclose($out); exit();
}

/* ══ EKSPOR EXCEL ══ */
if(isset($_GET['export']) && $_GET['export'] === 'excel'){
    $result = mysqli_query($conn, "SELECT * FROM kelas ORDER BY nama_kelas");
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="data_kelas_'.date('Ymd_His').'.xls"');
    header('Cache-Control: no-cache, must-revalidate');
    echo "\xEF\xBB\xBF";
    echo '<table border="1" style="border-collapse:collapse;font-family:Arial,sans-serif">';
    echo '<thead><tr style="background:#0D9488;color:white;font-weight:bold">';
    $cols_xls = ['No','Nama Kelas'];
    if($hasTingkat)   $cols_xls[] = 'Tingkat';
    if($hasJurusan)   $cols_xls[] = 'Jurusan';
    if($hasWali)      $cols_xls[] = 'Wali Kelas';
    if($hasKapasitas) $cols_xls[] = 'Kapasitas';
    if($hasRuang)     $cols_xls[] = 'Ruang Kelas';
    if($hasTahun)     $cols_xls[] = 'Tahun Ajaran';
    foreach($cols_xls as $h) echo '<th style="padding:7px 12px">'.htmlspecialchars($h).'</th>';
    echo '</tr></thead><tbody>';
    $no = 1;
    while($row = mysqli_fetch_assoc($result)){
        $bg = ($no%2===0) ? '#F0FDFA' : '#FFFFFF';
        echo '<tr style="background:'.$bg.'">';
        echo '<td style="padding:5px 10px;text-align:center">'.$no++.'</td>';
        echo '<td style="padding:5px 10px;font-weight:bold">'.htmlspecialchars($row['nama_kelas']??'').'</td>';
        if($hasTingkat)   echo '<td style="padding:5px 10px">'.htmlspecialchars($row['tingkat']??'').'</td>';
        if($hasJurusan)   echo '<td style="padding:5px 10px">'.htmlspecialchars($row['jurusan']??'').'</td>';
        if($hasWali)      echo '<td style="padding:5px 10px">'.htmlspecialchars($row['wali_kelas']??'').'</td>';
        if($hasKapasitas) echo '<td style="padding:5px 10px;text-align:center">'.htmlspecialchars($row['kapasitas']??'').'</td>';
        if($hasRuang)     echo '<td style="padding:5px 10px">'.htmlspecialchars($row['ruang_kelas']??'').'</td>';
        if($hasTahun)     echo '<td style="padding:5px 10px">'.htmlspecialchars($row['tahun_ajaran']??'').'</td>';
        echo '</tr>';
    }
    echo '</tbody></table>'; exit();
}

/* ══ TEMPLATE CSV ══ */
if(isset($_GET['export']) && $_GET['export'] === 'template'){
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="template_import_kelas.csv"');
    header('Cache-Control: no-cache');
    $out = fopen('php://output', 'w');
    fputs($out, "\xEF\xBB\xBF");
    $hdr = ['Nama Kelas'];
    if($hasTingkat)   $hdr[] = 'Tingkat';
    if($hasJurusan)   $hdr[] = 'Jurusan';
    if($hasWali)      $hdr[] = 'Wali Kelas';
    if($hasKapasitas) $hdr[] = 'Kapasitas';
    if($hasRuang)     $hdr[] = 'Ruang Kelas';
    if($hasTahun)     $hdr[] = 'Tahun Ajaran';
    fputcsv($out, $hdr);
    $ex1 = ['X IPA 1'];
    if($hasTingkat)   $ex1[] = 'X';
    if($hasJurusan)   $ex1[] = 'IPA';
    if($hasWali)      $ex1[] = 'Drs. Ahmad Fauzi';
    if($hasKapasitas) $ex1[] = '36';
    if($hasRuang)     $ex1[] = 'R.101';
    if($hasTahun)     $ex1[] = date('Y').'/'.(date('Y')+1);
    fputcsv($out, $ex1);
    $ex2 = ['X IPS 1'];
    if($hasTingkat)   $ex2[] = 'X';
    if($hasJurusan)   $ex2[] = 'IPS';
    if($hasWali)      $ex2[] = 'Siti Rahmawati S.Pd';
    if($hasKapasitas) $ex2[] = '34';
    if($hasRuang)     $ex2[] = 'R.102';
    if($hasTahun)     $ex2[] = date('Y').'/'.(date('Y')+1);
    fputcsv($out, $ex2);
    fclose($out); exit();
}

/* ══ IMPOR CSV ══ */
$import_result = null;
if(isset($_POST['import_kelas'])){
    $csv_err = $_FILES['csv_file']['error'] ?? 4;
    if($csv_err !== 0){
        $err_map = [1=>'File terlalu besar',2=>'File terlalu besar',3=>'Upload tidak selesai',4=>'Tidak ada file dipilih'];
        $import_result = ['error' => $err_map[$csv_err] ?? 'Gagal upload (kode '.$csv_err.')'];
    } elseif(strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION)) !== 'csv'){
        $import_result = ['error' => 'File harus berformat .CSV!'];
    } elseif($_FILES['csv_file']['size'] > 5*1024*1024){
        $import_result = ['error' => 'Ukuran file maksimal 5 MB!'];
    } else {
        $content = file_get_contents($_FILES['csv_file']['tmp_name']);
        if(substr($content, 0, 3) === "\xEF\xBB\xBF") $content = substr($content, 3);
        $tmpClean = tempnam(sys_get_temp_dir(), 'kelas_csv_');
        file_put_contents($tmpClean, $content);
        $handle = fopen($tmpClean, 'r');
        $header = fgetcsv($handle, 0, ',');
        $delim  = ',';
        if(count($header) <= 1){ fclose($handle); $handle = fopen($tmpClean, 'r'); $header = fgetcsv($handle, 0, ';'); $delim = ';'; }
        $headerMap = [];
        foreach($header as $i => $h) $headerMap[strtolower(trim($h))] = $i;
        $ok = 0; $upd = 0; $fail = 0; $errors = [];
        $row_num = 1;
        while(($row = fgetcsv($handle, 0, $delim)) !== false){
            $row_num++;
            if(count($row) === 1 && trim($row[0]) === '') continue;
            $get = function($key) use ($row, $headerMap){
                $k = strtolower(trim($key));
                if(isset($headerMap[$k])) return trim($row[$headerMap[$k]] ?? '');
                $fb = ['nama kelas'=>0,'tingkat'=>1,'jurusan'=>2,'wali kelas'=>3,'kapasitas'=>4,'ruang kelas'=>5,'tahun ajaran'=>6];
                $idx = $fb[$k] ?? null;
                return $idx !== null ? trim($row[$idx] ?? '') : '';
            };
            $nama_kelas   = $get('nama kelas');
            if(empty($nama_kelas)){ $fail++; $errors[] = "Baris $row_num: Nama kelas kosong"; continue; }
            $tingkat      = $get('tingkat');
            $jurusan      = $get('jurusan');
            $wali_kelas   = $get('wali kelas');
            $kapasitas    = intval($get('kapasitas') ?: 36);
            $ruang_kelas  = $get('ruang kelas');
            $tahun_ajaran = $get('tahun ajaran') ?: date('Y').'/'.(date('Y')+1);
            $esc = fn($v) => mysqli_real_escape_string($conn, $v);
            $dupQ = "SELECT id FROM kelas WHERE nama_kelas='".$esc($nama_kelas)."'";
            if($hasTahun) $dupQ .= " AND tahun_ajaran='".$esc($tahun_ajaran)."'";
            $dupR = mysqli_query($conn, $dupQ);
            if($dupR && mysqli_num_rows($dupR) > 0){
                $existId = mysqli_fetch_assoc($dupR)['id'];
                $sets = ["nama_kelas='".$esc($nama_kelas)."'"];
                if($hasTingkat)   $sets[] = "tingkat='".$esc($tingkat)."'";
                if($hasJurusan)   $sets[] = "jurusan='".$esc($jurusan)."'";
                if($hasWali)      $sets[] = "wali_kelas='".$esc($wali_kelas)."'";
                if($hasKapasitas) $sets[] = "kapasitas=".intval($kapasitas);
                if($hasRuang)     $sets[] = $ruang_kelas ? "ruang_kelas='".$esc($ruang_kelas)."'" : "ruang_kelas=NULL";
                if($hasTahun)     $sets[] = "tahun_ajaran='".$esc($tahun_ajaran)."'";
                $q = "UPDATE kelas SET ".implode(', ', $sets)." WHERE id=$existId";
                if(mysqli_query($conn, $q)) $upd++;
                else { $fail++; $errors[] = "Baris $row_num ($nama_kelas): ".mysqli_error($conn); }
            } else {
                $cols = ['nama_kelas']; $vals = ["'".$esc($nama_kelas)."'"];
                if($hasTingkat)   { $cols[] = 'tingkat';      $vals[] = "'".$esc($tingkat)."'"; }
                if($hasJurusan)   { $cols[] = 'jurusan';      $vals[] = "'".$esc($jurusan)."'"; }
                if($hasWali)      { $cols[] = 'wali_kelas';   $vals[] = "'".$esc($wali_kelas)."'"; }
                if($hasKapasitas) { $cols[] = 'kapasitas';    $vals[] = intval($kapasitas); }
                if($hasRuang)     { $cols[] = 'ruang_kelas';  $vals[] = $ruang_kelas ? "'".$esc($ruang_kelas)."'" : 'NULL'; }
                if($hasTahun)     { $cols[] = 'tahun_ajaran'; $vals[] = "'".$esc($tahun_ajaran)."'"; }
                $q = "INSERT INTO kelas (".implode(',', $cols).") VALUES (".implode(',', $vals).")";
                if(mysqli_query($conn, $q)) $ok++;
                else { $fail++; $errors[] = "Baris $row_num ($nama_kelas): ".mysqli_error($conn); }
            }
        }
        fclose($handle); @unlink($tmpClean);
        $import_result = ['insert' => $ok, 'update' => $upd, 'fail' => $fail, 'errors' => $errors];
    }
}

/* ══ HAPUS ══ */
if(isset($_GET['hapus'])){
    $id = intval($_GET['hapus']);
    if($hasSiswaTbl && $hasKelasId){
        $cek = mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) as total FROM siswa WHERE kelas_id=$id"));
        if($cek['total'] > 0){ $msg = '❌ Tidak dapat menghapus! Masih ada '.$cek['total'].' siswa di kelas ini.'; $msg_type = 'err'; }
    }
    if($msg_type !== 'err'){
        if(mysqli_query($conn,"DELETE FROM kelas WHERE id=$id")){ $msg='🗑️ Data kelas berhasil dihapus.'; $msg_type='del'; }
        else { $msg='❌ Gagal hapus: '.mysqli_error($conn); $msg_type='err'; }
    }
}

/* ══ EDIT ══ */
if(isset($_GET['edit'])){ $id=intval($_GET['edit']); $res=mysqli_query($conn,"SELECT * FROM kelas WHERE id=$id"); if($res) $editData=mysqli_fetch_assoc($res); }

/* ══ SIMPAN ══ */
if(isset($_POST['simpan'])){
    $nama_kelas  = mysqli_real_escape_string($conn, trim($_POST['nama_kelas']  ?? ''));
    $tingkat     = mysqli_real_escape_string($conn, trim($_POST['tingkat']     ?? ''));
    $jurusan     = mysqli_real_escape_string($conn, trim($_POST['jurusan']     ?? ''));
    $wali_kelas  = mysqli_real_escape_string($conn, trim($_POST['wali_kelas']  ?? ''));
    $kapasitas   = intval($_POST['kapasitas']   ?? 36);
    $ruang_kelas = mysqli_real_escape_string($conn, trim($_POST['ruang_kelas'] ?? ''));
    $tahun_ajaran= mysqli_real_escape_string($conn, trim($_POST['tahun_ajaran']?? ''));
    if(empty($nama_kelas)){ $msg='❌ Nama kelas wajib diisi!'; $msg_type='err'; }
    else {
        $dupQ = "SELECT COUNT(*) as total FROM kelas WHERE nama_kelas='$nama_kelas'";
        if($hasTahun) $dupQ .= " AND tahun_ajaran='$tahun_ajaran'";
        $dup = mysqli_fetch_assoc(mysqli_query($conn, $dupQ));
        if($dup['total'] > 0){ $msg="❌ Kelas \"$nama_kelas\" sudah ada!"; $msg_type='err'; }
        else {
            $cols=[]; $vals=[];
            $cols[]='nama_kelas'; $vals[]="'$nama_kelas'";
            if($hasTingkat)   { $cols[]='tingkat';      $vals[]="'$tingkat'"; }
            if($hasJurusan)   { $cols[]='jurusan';      $vals[]="'$jurusan'"; }
            if($hasWali)      { $cols[]='wali_kelas';   $vals[]="'$wali_kelas'"; }
            if($hasKapasitas) { $cols[]='kapasitas';    $vals[]=$kapasitas; }
            if($hasRuang)     { $cols[]='ruang_kelas';  $vals[]=$ruang_kelas ? "'$ruang_kelas'" : 'NULL'; }
            if($hasTahun)     { $cols[]='tahun_ajaran'; $vals[]="'$tahun_ajaran'"; }
            $q = "INSERT INTO kelas (".implode(',',$cols).") VALUES (".implode(',',$vals).")";
            if(mysqli_query($conn,$q)){ header("Location: kelas.php?ok=add"); exit(); }
            else { $msg='❌ Gagal menyimpan: '.mysqli_error($conn); $msg_type='err'; }
        }
    }
}

/* ══ UPDATE ══ */
if(isset($_POST['update'])){
    $id          = intval($_POST['id'] ?? 0);
    $nama_kelas  = mysqli_real_escape_string($conn, trim($_POST['nama_kelas']  ?? ''));
    $tingkat     = mysqli_real_escape_string($conn, trim($_POST['tingkat']     ?? ''));
    $jurusan     = mysqli_real_escape_string($conn, trim($_POST['jurusan']     ?? ''));
    $wali_kelas  = mysqli_real_escape_string($conn, trim($_POST['wali_kelas']  ?? ''));
    $kapasitas   = intval($_POST['kapasitas']   ?? 36);
    $ruang_kelas = mysqli_real_escape_string($conn, trim($_POST['ruang_kelas'] ?? ''));
    $tahun_ajaran= mysqli_real_escape_string($conn, trim($_POST['tahun_ajaran']?? ''));
    if(empty($nama_kelas)){ $msg='❌ Nama kelas wajib diisi!'; $msg_type='err'; $res=mysqli_query($conn,"SELECT * FROM kelas WHERE id=$id"); if($res) $editData=mysqli_fetch_assoc($res); }
    else {
        $dupQ = "SELECT COUNT(*) as total FROM kelas WHERE nama_kelas='$nama_kelas' AND id!=$id";
        if($hasTahun) $dupQ .= " AND tahun_ajaran='$tahun_ajaran'";
        $dup = mysqli_fetch_assoc(mysqli_query($conn,$dupQ));
        if($dup['total'] > 0){ $msg="❌ Kelas \"$nama_kelas\" sudah ada!"; $msg_type='err'; $res=mysqli_query($conn,"SELECT * FROM kelas WHERE id=$id"); if($res) $editData=mysqli_fetch_assoc($res); }
        else {
            $sets=['nama_kelas'=>"'$nama_kelas'"];
            if($hasTingkat)   $sets['tingkat']     = "'$tingkat'";
            if($hasJurusan)   $sets['jurusan']     = "'$jurusan'";
            if($hasWali)      $sets['wali_kelas']  = "'$wali_kelas'";
            if($hasKapasitas) $sets['kapasitas']   = $kapasitas;
            if($hasRuang)     $sets['ruang_kelas'] = $ruang_kelas ? "'$ruang_kelas'" : 'NULL';
            if($hasTahun)     $sets['tahun_ajaran']= "'$tahun_ajaran'";
            $setParts=[];
            foreach($sets as $k=>$v) $setParts[]="$k=$v";
            $q="UPDATE kelas SET ".implode(', ',$setParts)." WHERE id=$id";
            if(mysqli_query($conn,$q)){ header("Location: kelas.php?ok=update"); exit(); }
            else { $msg='❌ Gagal update: '.mysqli_error($conn); $msg_type='err'; $res=mysqli_query($conn,"SELECT * FROM kelas WHERE id=$id"); if($res) $editData=mysqli_fetch_assoc($res); }
        }
    }
}

if(isset($_GET['ok'])){
    if($_GET['ok']==='add')    { $msg='✅ Data kelas berhasil disimpan!';   $msg_type='ok'; }
    if($_GET['ok']==='update') { $msg='✅ Data kelas berhasil diperbarui!'; $msg_type='ok'; }
}

/* ══ STATISTIK ══ */
$total_kelas = 0;
$r = mysqli_query($conn,"SELECT COUNT(*) as t FROM kelas");
if($r){ $total_kelas = mysqli_fetch_assoc($r)['t']; }

$total_siswa_aktif = 0;
if($hasSiswaTbl){
    $sq = "SELECT COUNT(*) as t FROM siswa";
    if($hasStatus) $sq .= " WHERE status_siswa='Aktif'";
    $r2 = mysqli_query($conn,$sq);
    if($r2) $total_siswa_aktif = mysqli_fetch_assoc($r2)['t'];
}
$rata_siswa = $total_kelas > 0 ? round($total_siswa_aktif / $total_kelas) : 0;

$jumlahSub = "0";
if($hasSiswaTbl && $hasKelasId){
    $jumlahSub = "(SELECT COUNT(*) FROM siswa s WHERE s.kelas_id=k.id".($hasStatus?" AND s.status_siswa='Aktif'":'').")";
}

$orderBy = $hasTingkat
    ? "FIELD(k.tingkat,'VII','VIII','IX','X','XI','XII'), k.nama_kelas ASC"
    : "k.nama_kelas ASC";

$data = mysqli_query($conn,"SELECT k.*, $jumlahSub as jumlah_siswa FROM kelas k ORDER BY $orderBy");
$total_rows = $data ? mysqli_num_rows($data) : 0;

/* ══ NAVBAR ══ */
$page_title  = "Data Kelas — MA As-Syafi'iyah 02";
$active_menu = 'kelas';
$loader_text = 'Memuat Data Kelas';
include 'navbar.php';
?>

<div class="main">
<div class="wrap" id="pg-wrap">

<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">

<style>
/* ══════════════════════════════════════════════
   DESIGN TOKENS
══════════════════════════════════════════════ */
:root{
  --tl:    #0D9488;
  --tl-l:  #F0FDFA;
  --tl-m:  #99F6E4;
  --tl-d:  #0F766E;
  --em:    #10B981;
  --em-d:  #059669;
  --amb:   #D97706;
  --amb-l: #FFFBEB;
  --rose:  #E11D48;
  --rose-l:#FFF1F2;
  --pur:   #7C3AED;
  --pur-l: #F5F3FF;
  --pur-m: #DDD6FE;
  --p:     #2563EB;
  --p-l:   #EFF6FF;
  --sur:   #FFFFFF;
  --bg:    #F0FDFA;
  --tx:    #134E4A;
  --tx2:   #1F6B66;
  --tx3:   #5EEAD4;
  --tx4:   #99F6E4;
  --bd:    #CCFBF1;
  --bd-d:  #99F6E4;
  --sh:    rgba(13,148,136,.14);
  --sh-m:  0 4px 20px rgba(13,148,136,.12);
  --sh-l:  0 12px 40px rgba(13,148,136,.18);
  --r:     14px;
  --r-l:   20px;
  --r-xl:  24px;
}

#pg-wrap, #pg-wrap * { font-family:'Plus Jakarta Sans',sans-serif; box-sizing:border-box; }
#pg-wrap { padding:1.5rem; max-width:1440px; }

/* ── Animations ── */
@keyframes fadeIn  { from{opacity:0}to{opacity:1} }
@keyframes slideUp { from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)} }
@keyframes flt     { 0%,100%{transform:translateY(0) rotate(-2deg)}50%{transform:translateY(-12px) rotate(4deg)} }
.a0{animation:slideUp .45s cubic-bezier(.16,1,.3,1) both}
.a1{animation:slideUp .45s cubic-bezier(.16,1,.3,1) .07s both}
.a2{animation:slideUp .45s cubic-bezier(.16,1,.3,1) .14s both}
.a3{animation:slideUp .45s cubic-bezier(.16,1,.3,1) .21s both}

/* ══ HERO ══ */
.hero{
  background:linear-gradient(135deg,#0F766E 0%,#0D9488 45%,#059669 100%);
  border-radius:var(--r-xl);padding:2rem 2.5rem;margin-bottom:1.25rem;
  position:relative;overflow:hidden;box-shadow:var(--sh-l);
}
.hero::before{
  content:'';position:absolute;inset:0;
  background:url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='%23fff' fill-opacity='.05'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/svg%3E");
  pointer-events:none;
}
.hero-hb{position:absolute;border-radius:50%;background:rgba(255,255,255,.1);}
.hb1{width:220px;height:220px;top:-60px;right:60px;animation:flt 7s ease-in-out infinite;}
.hb2{width:130px;height:130px;bottom:-40px;right:250px;animation:flt 5s ease-in-out infinite 2s;}
.hb3{width:80px;height:80px;top:20px;right:350px;border-radius:20px;animation:flt 6s ease-in-out infinite 1s;}
.hero-in{position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;gap:1.5rem;flex-wrap:wrap;}
.hero-l{flex:1;min-width:0;}
.hero-tag{display:inline-flex;align-items:center;gap:.5rem;background:rgba(255,255,255,.18);border:1px solid rgba(255,255,255,.28);border-radius:50px;padding:.35rem 1rem;font-size:.72rem;font-weight:700;color:rgba(255,255,255,.92);letter-spacing:.06em;text-transform:uppercase;margin-bottom:.875rem;}
.hero-h1{font-size:clamp(1.5rem,2.5vw,2.25rem);font-weight:800;color:#fff;line-height:1.2;margin-bottom:.5rem;}
.hero-h1 em{font-style:normal;background:linear-gradient(90deg,#FDE68A,#A7F3D0);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;}
.hero-sub{font-size:.85rem;color:rgba(255,255,255,.75);font-weight:500;}
.hero-r{display:flex;align-items:center;gap:.875rem;flex-wrap:wrap;}
.hchip{background:rgba(255,255,255,.16);backdrop-filter:blur(10px);border:1px solid rgba(255,255,255,.22);border-radius:var(--r);padding:.875rem 1.25rem;text-align:center;min-width:95px;transition:background .2s;}
.hchip:hover{background:rgba(255,255,255,.24);}
.hcn{font-size:1.75rem;font-weight:800;color:#fff;font-family:'DM Mono',monospace;line-height:1;}
.hcl{font-size:.62rem;font-weight:700;color:rgba(255,255,255,.72);text-transform:uppercase;letter-spacing:.07em;margin-top:.2rem;}
.hero-illo{font-size:5.5rem;animation:flt 3.5s ease-in-out infinite;line-height:1;filter:drop-shadow(0 8px 20px rgba(0,0,0,.2));}

/* ══ STAT CARDS ══ */
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-bottom:1.25rem;}
.scard{background:var(--sur);border-radius:var(--r-l);border:2px solid var(--bd);box-shadow:var(--sh-m);padding:1.25rem 1.5rem;display:flex;align-items:center;gap:1rem;transition:all .25s cubic-bezier(.34,1.56,.64,1);}
.scard:hover{transform:translateY(-4px) scale(1.01);box-shadow:0 10px 28px var(--sh);}
.sorb{width:52px;height:52px;border-radius:14px;display:flex;align-items:center;justify-content:center;font-size:1.625rem;flex-shrink:0;}
.s-tl{background:var(--tl-l);}.s-em{background:#D1FAE5;}.s-am{background:var(--amb-l);}
.sval{font-size:2.125rem;font-weight:800;font-family:'DM Mono',monospace;color:var(--tl-d);line-height:1;}
.slbl{font-size:.72rem;font-weight:700;color:var(--tx3);text-transform:uppercase;letter-spacing:.05em;margin-top:.15rem;}

/* ══ TOASTS ══ */
.toast-stack{display:flex;flex-direction:column;gap:.625rem;margin-bottom:1.25rem;}
.toast{display:flex;align-items:flex-start;gap:.75rem;padding:.875rem 1.125rem;border-radius:var(--r);font-size:.85rem;font-weight:600;border:1.5px solid;animation:slideUp .4s cubic-bezier(.34,1.56,.64,1) both;}
.t-ok {background:#CCFBF1;color:var(--tl-d);border-color:var(--tl-m);}
.t-del{background:#D1FAE5;color:#065F46;border-color:#6EE7B7;}
.t-err{background:var(--rose-l);color:#9F1239;border-color:#FECDD3;word-break:break-word;}
.t-edt{background:var(--amb-l);color:#78350F;border-color:#FDE68A;}
.toast a{font-weight:800;color:inherit;}

/* ══ SECTION CARDS ══ */
.sc{background:var(--sur);border-radius:var(--r-xl);border:2px solid var(--bd);box-shadow:var(--sh-m);overflow:hidden;margin-bottom:1.25rem;}
.sc.em-border{border-color:#FCD34D;}
.sc-head{padding:1rem 1.5rem;display:flex;align-items:center;justify-content:space-between;gap:1rem;border-bottom:2px solid var(--bd);flex-wrap:wrap;}
.sch-l{display:flex;align-items:center;gap:.75rem;}
.sc-ico{width:38px;height:38px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:1.05rem;flex-shrink:0;}
.i-tl{background:var(--tl-l);color:var(--tl-d);}
.i-am{background:var(--amb-l);color:var(--amb);}
.i-pu{background:var(--pur-l);color:var(--pur);}
.i-bl{background:var(--p-l);color:var(--p);}
.sc-ttl{font-size:.95rem;font-weight:800;color:var(--tx);}
.sc-sub{font-size:.72rem;font-weight:500;color:var(--tx3);margin-top:.1rem;}
.sc-body{padding:1.5rem;}

/* ══ BUTTONS ══ */
.btn{display:inline-flex;align-items:center;gap:.45rem;padding:.6rem 1rem;border-radius:9px;font-size:.8rem;font-weight:700;cursor:pointer;border:1.5px solid transparent;transition:all .22s cubic-bezier(.34,1.56,.64,1);text-decoration:none;font-family:inherit;white-space:nowrap;}
.btn:hover{transform:translateY(-2px);}
.btn-tl{background:var(--tl-l);color:var(--tl-d);border-color:var(--tl-m);}
.btn-tl:hover{background:var(--tl-m);box-shadow:0 4px 12px rgba(13,148,136,.2);}
.btn-grn{background:#D1FAE5;color:#065F46;border-color:#6EE7B7;}
.btn-grn:hover{background:#A7F3D0;box-shadow:0 4px 12px rgba(16,185,129,.2);}
.btn-pur{background:var(--pur-l);color:var(--pur);border-color:var(--pur-m);}
.btn-pur:hover{background:#EDE9FE;box-shadow:0 4px 12px rgba(124,58,237,.2);}
.btn-amb{background:var(--amb-l);color:var(--amb);border-color:#FDE68A;}
.btn-amb:hover{background:#FEF3C7;box-shadow:0 4px 12px rgba(217,119,6,.2);}
.btn-danger{background:var(--rose-l);color:var(--rose);border-color:#FECDD3;}
.btn-danger:hover{background:#FFE4E6;box-shadow:0 4px 12px rgba(225,29,72,.2);}
.btn-ghost{background:var(--bg);color:var(--tx2);border-color:var(--bd);}
.btn-ghost:hover{border-color:var(--bd-d);}
.btn-primary{background:linear-gradient(135deg,var(--tl),var(--tl-d));color:#fff;border-color:var(--tl-d);box-shadow:0 4px 14px rgba(13,148,136,.28);}
.btn-primary:hover{box-shadow:0 8px 22px rgba(13,148,136,.42);}
.btn-full{width:100%;justify-content:center;}
.btn-lg{padding:.875rem 1.75rem;font-size:.9rem;border-radius:12px;}
.btn-row{display:flex;flex-wrap:wrap;gap:.5rem;}

/* ══ EKSPOR / IMPOR PANEL ══ */
.ei-wrap{display:grid;grid-template-columns:1fr 1fr;gap:0;}
.ei-col{padding:1.375rem 1.5rem;}
.ei-col:first-child{border-right:2px solid var(--bd);}
.ei-lbl{font-size:.67rem;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--tx3);margin-bottom:.875rem;display:flex;align-items:center;gap:.4rem;}
.note{font-size:.74rem;color:var(--tx3);line-height:1.65;font-weight:500;margin-top:.75rem;}

/* Dropzone */
.dropzone{border:2.5px dashed var(--pur-m);border-radius:var(--r);padding:1.375rem 1rem;background:var(--pur-l);text-align:center;transition:all .2s;cursor:pointer;user-select:none;}
.dropzone:hover,.dropzone.drag{border-color:var(--pur);background:#EDE9FE;}
.dz-ico{font-size:2rem;margin-bottom:.375rem;display:block;transition:transform .25s;}
.dropzone.drag .dz-ico{transform:scale(1.2);}
.dz-msg{font-size:.82rem;font-weight:700;color:var(--tx);}
.dz-msg span{color:var(--pur);text-decoration:underline;cursor:pointer;}
.dz-hint{font-size:.7rem;color:var(--tx3);margin-top:.25rem;}
.file-badge{display:inline-flex;align-items:center;gap:.375rem;background:#fff;border:1.5px solid var(--pur-m);border-radius:7px;padding:.3rem .75rem;font-size:.76rem;font-weight:600;color:var(--pur);margin-top:.625rem;word-break:break-all;}
.im-warn{font-size:.72rem;color:var(--amb);font-weight:700;background:var(--amb-l);border:1.5px solid #FDE68A;border-radius:8px;padding:.375rem .875rem;margin:.625rem 0;}
input[type="file"]#csvFile{display:none;}

/* ══ FORM ══ */
.fs-lbl{display:flex;align-items:center;gap:.6rem;padding:.6rem .875rem;margin-bottom:.875rem;background:var(--bg);border-radius:9px;border-left:3px solid var(--tl);}
.fs-lbl.c-am{border-color:var(--amb);}
.fs-lbl-t{font-size:.82rem;font-weight:800;color:var(--tx);}
.fgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:.875rem;}
.fg{display:flex;flex-direction:column;gap:.35rem;}
.flbl{font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--tx2);display:flex;align-items:center;gap:.3rem;}
.freq{color:var(--rose);}
.fopt{background:var(--tl-l);color:var(--tl-d);border-radius:50px;padding:.05rem .45rem;font-size:.6rem;font-weight:700;border:1px solid var(--tl-m);}
.fi,.fsel{width:100%;padding:.7rem .9rem;background:#fff;border:1.5px solid var(--bd);border-radius:9px;font-size:.875rem;font-family:inherit;font-weight:500;color:var(--tx);transition:all .18s;outline:none;-webkit-appearance:none;}
.fi:focus,.fsel:focus{border-color:var(--tl);box-shadow:0 0 0 3px rgba(13,148,136,.12);background:#FAFFFE;}
.fi::placeholder{color:var(--tx4);}
.fsel{cursor:pointer;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='11' height='11' viewBox='0 0 12 12'%3E%3Cpath fill='%2364748B' d='M6 8L1 3h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right .875rem center;padding-right:2.25rem;}
.f-acts{display:flex;gap:.75rem;flex-wrap:wrap;padding-top:1.25rem;border-top:1.5px dashed var(--bd);margin-top:1.25rem;}
.btn-save{padding:.875rem 2rem;font-size:.9rem;font-weight:800;border-radius:12px;cursor:pointer;border:none;font-family:inherit;display:inline-flex;align-items:center;gap:.5rem;transition:all .28s cubic-bezier(.34,1.56,.64,1);}
.btn-save.sv{background:linear-gradient(135deg,var(--tl),var(--tl-d));color:#fff;box-shadow:0 5px 18px rgba(13,148,136,.3);}
.btn-save.sv:hover{transform:translateY(-3px);box-shadow:0 10px 26px rgba(13,148,136,.42);}
.btn-save.up{background:linear-gradient(135deg,var(--amb),#B45309);color:#fff;box-shadow:0 5px 18px rgba(217,119,6,.3);}
.btn-save.up:hover{transform:translateY(-3px);box-shadow:0 10px 26px rgba(217,119,6,.42);}

/* ══ TABLE ══ */
.tbl-top{display:flex;align-items:center;justify-content:space-between;gap:.875rem;padding:1rem 1.5rem;border-bottom:2px solid var(--bd);flex-wrap:wrap;}
.search-box{position:relative;flex:1;min-width:180px;max-width:340px;}
.search-box::before{content:'🔍';position:absolute;left:.875rem;top:50%;transform:translateY(-50%);font-size:.82rem;pointer-events:none;}
.si{width:100%;padding:.6rem 1rem .6rem 2.5rem;border-radius:50px;border:1.5px solid var(--bd);background:var(--bg);font-size:.84rem;font-family:inherit;font-weight:600;outline:none;transition:all .2s;color:var(--tx);}
.si:focus{border-color:var(--tl);background:#fff;box-shadow:0 0 0 3px rgba(13,148,136,.1);}
.cnt-badge{background:var(--tl-l);color:var(--tl-d);border:1px solid var(--tl-m);border-radius:50px;padding:.2rem .875rem;font-size:.72rem;font-weight:700;white-space:nowrap;}

/* Desktop table */
.tbl-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch;}
.tbl-scroll::-webkit-scrollbar{height:5px;}
.tbl-scroll::-webkit-scrollbar-track{background:var(--bg);}
.tbl-scroll::-webkit-scrollbar-thumb{background:var(--bd-d);border-radius:10px;}
.dt{width:100%;border-collapse:collapse;min-width:700px;}
.dt thead tr{background:var(--bg);}
.dt th{padding:.7rem 1rem;text-align:left;font-size:.63rem;font-weight:800;color:var(--tl-d);text-transform:uppercase;letter-spacing:.08em;white-space:nowrap;border-bottom:2px solid var(--bd);}
.dt tbody tr{border-bottom:1px solid var(--bd);transition:background .15s;}
.dt tbody tr:hover{background:var(--tl-l);}
.dt tbody tr:last-child{border-bottom:none;}
.dt td{padding:.875rem 1rem;font-size:.84rem;color:var(--tx);vertical-align:middle;}
.no-cell{font-family:'DM Mono',monospace;font-size:.7rem;color:var(--tx3);text-align:center;width:32px;}
.nm-cell{font-size:.95rem;font-weight:800;color:var(--tx);}
.tchip{display:inline-flex;align-items:center;justify-content:center;width:38px;height:38px;border-radius:9px;background:var(--tl-l);color:var(--tl-d);font-size:.875rem;font-weight:800;font-family:'DM Mono',monospace;border:1.5px solid var(--tl-m);}
.jbadge{display:inline-flex;align-items:center;gap:.3rem;padding:.25rem .75rem;border-radius:50px;font-size:.72rem;font-weight:700;white-space:nowrap;}
.jdot{width:6px;height:6px;border-radius:50%;}
.j-ipa   {background:#CCFBF1;color:#134E4A;}.j-ipa .jdot{background:#14B8A6;}
.j-ips   {background:var(--rose-l);color:#9F1239;}.j-ips .jdot{background:#F87171;}
.j-bahasa{background:var(--pur-l);color:var(--pur);}.j-bahasa .jdot{background:#A78BFA;}
.j-umum  {background:#D1FAE5;color:#065F46;}.j-umum .jdot{background:#34D399;}
.rchip{display:inline-flex;align-items:center;gap:.3rem;padding:.2rem .65rem;background:var(--tl-l);border:1.5px solid var(--tl-m);border-radius:7px;font-size:.75rem;font-weight:700;color:var(--tl-d);}
.wali-cell{font-size:.84rem;font-weight:700;}
.kapbar{display:flex;flex-direction:column;gap:.3rem;}
.kapnum{font-family:'DM Mono',monospace;font-size:.75rem;font-weight:700;color:var(--tx2);}
.kapbg{background:var(--bd);border-radius:50px;height:7px;width:100%;min-width:80px;overflow:hidden;}
.kapfill{height:100%;border-radius:50px;transition:width .5s;}
.kap-ok  {background:linear-gradient(90deg,var(--tl),var(--em));}
.kap-warn{background:linear-gradient(90deg,var(--amb),#B45309);}
.kap-full{background:linear-gradient(90deg,#F87171,#EF4444);}
.act-row{display:flex;gap:.3rem;}

/* Empty state */
.empty{text-align:center;padding:4rem 2rem;}
.empty-ico{font-size:3.5rem;margin-bottom:.875rem;}
.empty-title{font-size:1.05rem;font-weight:800;color:var(--tx);margin-bottom:.375rem;}
.empty-sub{font-size:.84rem;color:var(--tx3);}

/* ══ MOBILE CARDS ══ */
.mob-list{display:none;flex-direction:column;gap:.75rem;padding:1rem;}
.mob-card{background:#fff;border:1.5px solid var(--bd);border-radius:var(--r);padding:1rem;box-shadow:0 1px 4px var(--sh);}
.mob-top{display:flex;align-items:center;gap:.75rem;margin-bottom:.875rem;}
.mob-name{font-size:.975rem;font-weight:800;color:var(--tx);flex:1;}
.mob-tags{display:flex;gap:.35rem;flex-wrap:wrap;margin-top:.35rem;}
.mob-grid{display:grid;grid-template-columns:1fr 1fr;gap:.5rem .75rem;margin-bottom:.875rem;}
.mob-fl{font-size:.62rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:var(--tx3);margin-bottom:.1rem;}
.mob-fv{font-size:.8rem;font-weight:600;color:var(--tx2);line-height:1.4;}
.mob-acts{display:flex;gap:.5rem;padding-top:.75rem;border-top:1px solid var(--bd);}
.mob-acts .btn{flex:1;justify-content:center;}

/* Import result */
.imp-res{background:var(--pur-l);border:1.5px solid var(--pur-m);border-radius:var(--r);padding:1.125rem 1.375rem;margin-bottom:1.25rem;}
.imp-res h4{font-size:.875rem;font-weight:800;color:var(--pur);margin-bottom:.5rem;}
.imp-res-err{margin-top:.5rem;max-height:120px;overflow-y:auto;font-size:.73rem;color:#5B21B6;line-height:1.7;}

/* ══ MODAL ══ */
.modal-bg{display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,.55);backdrop-filter:blur(5px);align-items:center;justify-content:center;padding:1rem;}
.modal-bg.open{display:flex;}
.modal-box{background:#fff;border-radius:var(--r-xl);padding:2rem;max-width:400px;width:100%;box-shadow:0 12px 40px rgba(0,0,0,.15);animation:slideUp .32s cubic-bezier(.34,1.2,.64,1);}
.modal-ico{width:52px;height:52px;border-radius:14px;background:var(--rose-l);display:flex;align-items:center;justify-content:center;font-size:1.625rem;margin-bottom:1.125rem;}
.modal-ttl{font-size:1.2rem;font-weight:800;color:var(--tx);margin-bottom:.5rem;}
.modal-msg{font-size:.85rem;color:#64748B;line-height:1.65;}
.modal-acts{display:flex;gap:.75rem;margin-top:1.625rem;}
.modal-acts .btn{flex:1;justify-content:center;padding:.75rem;}

/* ══ RESPONSIVE ══ */
@media(max-width:1100px){
  .ei-wrap{grid-template-columns:1fr;}
  .ei-col:first-child{border-right:none;border-bottom:2px solid var(--bd);}
}
@media(max-width:900px){
  #pg-wrap{padding:1rem;}
  .hero{padding:1.5rem;}
  .stats{grid-template-columns:1fr 1fr;}
}
@media(max-width:640px){
  #pg-wrap{padding:.75rem;}
  .hero{padding:1.125rem;border-radius:var(--r-l);}
  .hero-in{flex-direction:column;align-items:flex-start;}
  .hero-illo{display:none;}
  .hero-r{width:100%;display:grid;grid-template-columns:repeat(3,1fr);}
  .hchip{text-align:center;}
  .hcn{font-size:1.375rem;}

  .stats{grid-template-columns:1fr;}
  .sc-head{padding:.875rem 1rem;}
  .sc-body{padding:1rem;}
  .ei-col{padding:1rem;}

  /* Swap table → cards on mobile */
  .tbl-scroll{display:none;}
  .mob-list{display:flex;}
  .tbl-top{padding:.75rem 1rem;}
  .search-box{max-width:100%;flex:1;}

  .btn{padding:.55rem .875rem;font-size:.76rem;}
  .btn-lg{padding:.75rem 1.25rem;font-size:.85rem;}
  .btn-save{width:100%;justify-content:center;}
  .f-acts{flex-direction:column;}
  .fgrid{grid-template-columns:1fr;}

  .modal-box{padding:1.5rem;}
  .modal-acts{flex-direction:column;}
}
@media(max-width:400px){
  .mob-grid{grid-template-columns:1fr;}
  .hero-r{grid-template-columns:1fr 1fr;}
}
</style>

<!-- ════ HERO ════ -->
<div class="hero a0">
  <div class="hero-hb hb1"></div>
  <div class="hero-hb hb2"></div>
  <div class="hero-hb hb3"></div>
  <div class="hero-in">
    <div class="hero-l">
      <div class="hero-tag">🏫 &nbsp;Manajemen Akademik</div>
      <div class="hero-h1">Kelola <em>Data Kelas</em></div>
      <div class="hero-sub">MA As-Syafi'iyah 02 — Atur kelas, wali kelas &amp; kapasitas dalam satu tempat 🎯</div>
    </div>
    <div class="hero-r">
      <div class="hero-illo">🏫</div>
      <div class="hchip">
        <div class="hcn"><?= $total_kelas ?></div>
        <div class="hcl">Total Kelas</div>
      </div>
      <div class="hchip">
        <div class="hcn"><?= $total_siswa_aktif ?></div>
        <div class="hcl">Siswa Aktif</div>
      </div>
      <div class="hchip">
        <div class="hcn"><?= $rata_siswa ?></div>
        <div class="hcl">Rata-rata</div>
      </div>
    </div>
  </div>
</div>

<!-- ════ STAT CARDS ════ -->
<div class="stats a1">
  <div class="scard">
    <div class="sorb s-tl">🏫</div>
    <div><div class="sval"><?= $total_kelas ?></div><div class="slbl">Total Kelas</div></div>
  </div>
  <div class="scard">
    <div class="sorb s-em">👨‍🎓</div>
    <div><div class="sval"><?= $total_siswa_aktif ?></div><div class="slbl">Siswa Aktif</div></div>
  </div>
  <div class="scard">
    <div class="sorb s-am">📊</div>
    <div><div class="sval"><?= $rata_siswa ?></div><div class="slbl">Rata-rata / Kelas</div></div>
  </div>
</div>

<!-- ════ TOASTS ════ -->
<div class="toast-stack">
<?php if($msg): ?>
  <div class="toast <?= $msg_type==='ok'?'t-ok':($msg_type==='del'?'t-del':'t-err') ?>" id="alertBox">
    <span style="font-size:1.1rem;flex-shrink:0;margin-top:.05rem"><?= $msg_type==='ok'?'✅':($msg_type==='del'?'🗑️':'❌') ?></span>
    <div><?= htmlspecialchars($msg) ?></div>
  </div>
<?php endif; ?>
<?php if($editData): ?>
  <div class="toast t-edt">
    <span style="font-size:1.1rem;flex-shrink:0">✏️</span>
    <div>Mode Edit: <b><?= htmlspecialchars($editData['nama_kelas']) ?></b> &nbsp;—&nbsp; <a href="kelas.php">Batal Edit</a></div>
  </div>
<?php endif; ?>
</div>

<!-- Import result -->
<?php if($import_result): ?>
  <?php if(isset($import_result['error'])): ?>
  <div class="toast t-err" style="margin-bottom:1.25rem">
    <span style="font-size:1.1rem;flex-shrink:0">❌</span>
    <div><b>Impor gagal:</b> <?= htmlspecialchars($import_result['error']) ?></div>
  </div>
  <?php else: ?>
  <div class="imp-res a0">
    <h4>📥 Hasil Impor CSV</h4>
    <div style="font-size:.84rem;font-weight:600;display:flex;gap:1rem;flex-wrap:wrap">
      <?php if($import_result['insert']>0): ?><span>✅ Ditambahkan: <b><?= $import_result['insert'] ?></b></span><?php endif; ?>
      <?php if($import_result['update']>0): ?><span>🔄 Diperbarui: <b><?= $import_result['update'] ?></b></span><?php endif; ?>
      <?php if($import_result['fail']>0): ?><span>❌ Gagal: <b><?= $import_result['fail'] ?></b></span><?php endif; ?>
      <?php if($import_result['insert']===0&&$import_result['update']===0&&$import_result['fail']===0): ?><span>⚠️ Tidak ada data diproses</span><?php endif; ?>
    </div>
    <?php if(!empty($import_result['errors'])): ?>
    <div class="imp-res-err"><b>Detail error:</b><br><?= implode('<br>',array_map('htmlspecialchars',$import_result['errors'])) ?></div>
    <?php endif; ?>
  </div>
  <?php endif; ?>
<?php endif; ?>

<!-- ════ EKSPOR & IMPOR ════ -->
<div class="sc a1">
  <div class="sc-head">
    <div class="sch-l">
      <div class="sc-ico i-pu">📊</div>
      <div>
        <div class="sc-ttl">Ekspor &amp; Impor Data Kelas</div>
        <div class="sc-sub">Unduh semua data atau unggah data massal via CSV</div>
      </div>
    </div>
  </div>
  <div class="ei-wrap">
    <!-- Ekspor -->
    <div class="ei-col">
      <div class="ei-lbl">📤 Ekspor Data</div>
      <div class="btn-row">
        <a href="kelas.php?export=excel" class="btn btn-grn">📊 Excel (.xls)</a>
        <a href="kelas.php?export=csv"   class="btn btn-tl">📄 CSV</a>
        <a href="kelas.php?export=template" class="btn btn-pur">📋 Template</a>
      </div>
      <div class="note">Unduh seluruh data kelas sebagai <b>Excel</b> atau <b>CSV</b>. Gunakan <b>Template</b> sebagai panduan format kolom saat mengimpor data massal.</div>
    </div>
    <!-- Impor -->
    <div class="ei-col">
      <div class="ei-lbl">📥 Impor Data CSV</div>
      <form method="POST" enctype="multipart/form-data" action="kelas.php" id="importForm">
        <input type="hidden" name="import_kelas" value="1">
        <div class="dropzone" id="dropzone">
          <span class="dz-ico" id="dzIco">📂</span>
          <div class="dz-msg">Seret &amp; lepas, atau <span onclick="document.getElementById('csvFile').click()">pilih file CSV</span></div>
          <div class="dz-hint">Format .CSV · Maks 5MB</div>
          <input type="file" id="csvFile" name="csv_file" accept=".csv,.CSV">
          <div id="fileBadge" style="display:none"><div class="file-badge">📄 <span id="fileName"></span></div></div>
        </div>
        <div class="im-warn">⚠️ Kelas nama sama akan <b>diperbarui</b>, tidak diduplikat.</div>
        <button type="submit" class="btn btn-primary btn-full btn-lg" id="impBtn"><span id="impBtnTxt">📥 Mulai Impor</span></button>
      </form>
    </div>
  </div>
</div>

<!-- ════ FORM TAMBAH / EDIT ════ -->
<div class="sc a2 <?= $editData ? 'em-border' : '' ?>" id="fcard" style="<?= $editData ? 'border-color:#FCD34D' : '' ?>">
  <div class="sc-head" style="<?= $editData ? 'background:linear-gradient(135deg,#FFFBEB,#FEF9C3);border-bottom-color:#FDE68A' : '' ?>">
    <div class="sch-l">
      <div class="sc-ico <?= $editData ? 'i-am' : 'i-tl' ?>"><?= $editData ? '✏️' : '➕' ?></div>
      <div>
        <div class="sc-ttl"><?= $editData ? 'Edit Data Kelas' : 'Tambah Kelas Baru' ?></div>
        <div class="sc-sub"><?= $editData ? 'Memperbarui: '.$editData['nama_kelas'] : 'Isi formulir untuk mendaftarkan kelas baru' ?></div>
      </div>
    </div>
    <?php if($editData): ?><a href="kelas.php" class="btn btn-ghost">✕ Batal</a><?php endif; ?>
  </div>
  <div class="sc-body">
  <form method="POST" action="kelas.php">
    <?php if($editData): ?><input type="hidden" name="id" value="<?= intval($editData['id']) ?>"><?php endif; ?>
    <div class="fgrid">
      <div class="fg">
        <label class="flbl">🏷️ Nama Kelas <span class="freq">*</span></label>
        <input type="text" name="nama_kelas" class="fi" placeholder="Cth: X IPA 1, VII A"
          value="<?= htmlspecialchars($editData?$editData['nama_kelas']:($_POST['nama_kelas']??'')) ?>" required>
      </div>
      <?php if($hasTingkat): ?>
      <div class="fg">
        <label class="flbl">📶 Tingkat <span class="freq">*</span></label>
        <select name="tingkat" class="fsel" required>
          <option value="">Pilih Tingkat</option>
          <?php $ct=$editData?$editData['tingkat']:($_POST['tingkat']??'');
          foreach(['VII'=>'VII (7)','VIII'=>'VIII (8)','IX'=>'IX (9)','X'=>'X (10)','XI'=>'XI (11)','XII'=>'XII (12)'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= $ct===$v?'selected':'' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>
      <?php if($hasJurusan): ?>
      <div class="fg">
        <label class="flbl">📖 Jurusan <span class="freq">*</span></label>
        <select name="jurusan" class="fsel" required>
          <option value="">Pilih Jurusan</option>
          <?php $cj=$editData?$editData['jurusan']:($_POST['jurusan']??'');
          foreach(['IPA'=>'🔬 IPA','IPS'=>'🌍 IPS','Bahasa'=>'📝 Bahasa','Umum'=>'📚 Umum'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= $cj===$v?'selected':'' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <?php endif; ?>
      <?php if($hasWali): ?>
      <div class="fg">
        <label class="flbl">👤 Wali Kelas <span class="req">*</span></label>
        <input type="text" name="wali_kelas" class="fi" placeholder="Nama wali kelas"
          value="<?= htmlspecialchars($editData?$editData['wali_kelas']:($_POST['wali_kelas']??'')) ?>" required>
      </div>
      <?php endif; ?>
      <?php if($hasKapasitas): ?>
      <div class="fg">
        <label class="flbl">👥 Kapasitas <span class="freq">*</span></label>
        <input type="number" name="kapasitas" class="fi" placeholder="36" min="1" max="100"
          value="<?= htmlspecialchars($editData?$editData['kapasitas']:($_POST['kapasitas']??'36')) ?>" required>
      </div>
      <?php endif; ?>
      <?php if($hasRuang): ?>
      <div class="fg">
        <label class="flbl">🚪 Ruang Kelas <span class="fopt">Opsional</span></label>
        <input type="text" name="ruang_kelas" class="fi" placeholder="Cth: R.101"
          value="<?= htmlspecialchars($editData?($editData['ruang_kelas']??''):($_POST['ruang_kelas']??'')) ?>">
      </div>
      <?php endif; ?>
      <?php if($hasTahun): ?>
      <div class="fg">
        <label class="flbl">📅 Tahun Ajaran <span class="freq">*</span></label>
        <input type="text" name="tahun_ajaran" class="fi" placeholder="2025/2026"
          value="<?= htmlspecialchars($editData?$editData['tahun_ajaran']:($_POST['tahun_ajaran']??date('Y').'/'.(date('Y')+1))) ?>" required>
      </div>
      <?php endif; ?>
    </div>
    <div class="f-acts">
      <button type="submit" name="<?= $editData?'update':'simpan' ?>" class="btn-save <?= $editData?'up':'sv' ?>">
        <?= $editData ? '🔄 Update Kelas' : '💾 Simpan Kelas' ?>
      </button>
      <?php if($editData): ?><a href="kelas.php" class="btn btn-ghost btn-lg">✕ Batal</a><?php endif; ?>
    </div>
  </form>
  </div>
</div>

<!-- ════ TABEL / CARDS DATA KELAS ════ -->
<div class="sc a3">
  <div class="sc-head">
    <div class="sch-l">
      <div class="sc-ico i-tl">📋</div>
      <div>
        <div class="sc-ttl">Daftar Kelas</div>
        <div class="sc-sub"><?= $total_rows ?> kelas terdaftar</div>
      </div>
    </div>
    <span class="cnt-badge"><?= $total_rows ?> kelas</span>
  </div>

  <!-- Search -->
  <div class="tbl-top">
    <div class="search-box">
      <input type="text" class="si" id="si" placeholder="Cari kelas, wali, jurusan…" oninput="srch()">
    </div>
  </div>

  <!-- Desktop Table -->
  <div class="tbl-scroll">
    <?php if($total_rows > 0): ?>
    <table class="dt" id="dtbl">
      <thead><tr>
        <th>#</th>
        <th>Nama Kelas</th>
        <?php if($hasTingkat): ?><th>Tingkat</th><?php endif; ?>
        <?php if($hasJurusan): ?><th>Jurusan</th><?php endif; ?>
        <?php if($hasWali): ?><th>Wali Kelas</th><?php endif; ?>
        <?php if($hasKapasitas): ?><th>Kapasitas</th><?php endif; ?>
        <?php if($hasSiswaTbl && $hasKelasId): ?><th>Isi Kelas</th><?php endif; ?>
        <?php if($hasRuang): ?><th>Ruang</th><?php endif; ?>
        <?php if($hasTahun): ?><th>Tahun Ajaran</th><?php endif; ?>
        <th>Aksi</th>
      </tr></thead>
      <tbody>
        <?php $no=1; while($d=mysqli_fetch_assoc($data)):
          $jur = strtolower($d['jurusan']??'umum');
          $jmap = ['ipa'=>'j-ipa','ips'=>'j-ips','bahasa'=>'j-bahasa','umum'=>'j-umum'];
          $jcls = $jmap[$jur] ?? 'j-umum';
          $jml  = intval($d['jumlah_siswa']??0);
          $kap  = intval($d['kapasitas']??1);
          $pct  = $kap > 0 ? min(100, round($jml/$kap*100)) : 0;
          $kcls = $pct>=100 ? 'kap-full' : ($pct>=85 ? 'kap-warn' : 'kap-ok');
        ?>
        <tr>
          <td class="no-cell"><?= $no++ ?></td>
          <td class="nm-cell"><?= htmlspecialchars($d['nama_kelas']) ?></td>
          <?php if($hasTingkat): ?>
          <td><div class="tchip"><?= htmlspecialchars($d['tingkat']??'—') ?></div></td>
          <?php endif; ?>
          <?php if($hasJurusan): ?>
          <td><span class="jbadge <?= $jcls ?>"><span class="jdot"></span><?= htmlspecialchars($d['jurusan']??'—') ?></span></td>
          <?php endif; ?>
          <?php if($hasWali): ?>
          <td class="wali-cell">👤 <?= htmlspecialchars($d['wali_kelas']??'—') ?></td>
          <?php endif; ?>
          <?php if($hasKapasitas): ?>
          <td><span style="font-family:'DM Mono',monospace;font-size:.82rem;font-weight:700"><?= $kap ?> siswa</span></td>
          <?php endif; ?>
          <?php if($hasSiswaTbl && $hasKelasId): ?>
          <td>
            <div class="kapbar">
              <span class="kapnum"><?= $jml ?>/<?= $kap ?> (<?= $pct ?>%)</span>
              <div class="kapbg"><div class="kapfill <?= $kcls ?>" style="width:<?= $pct ?>%"></div></div>
            </div>
          </td>
          <?php endif; ?>
          <?php if($hasRuang): ?>
          <td>
            <?php if(!empty($d['ruang_kelas'])): ?>
            <span class="rchip">🚪 <?= htmlspecialchars($d['ruang_kelas']) ?></span>
            <?php else: ?><span style="color:var(--tx3)">—</span><?php endif; ?>
          </td>
          <?php endif; ?>
          <?php if($hasTahun): ?>
          <td><span style="font-family:'DM Mono',monospace;font-size:.78rem;font-weight:700;color:var(--tl-d)"><?= htmlspecialchars($d['tahun_ajaran']??'') ?></span></td>
          <?php endif; ?>
          <td>
            <div class="act-row">
              <a href="?edit=<?= $d['id'] ?>" class="btn btn-amb" style="padding:.4rem .7rem;font-size:.74rem">✏️ Edit</a>
              <button class="btn btn-danger" style="padding:.4rem .7rem;font-size:.74rem" onclick="konfirmHapus(<?= $d['id'] ?>,'<?= htmlspecialchars(addslashes($d['nama_kelas'])) ?>')">🗑️</button>
            </div>
          </td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
    <?php else: ?>
    <div class="empty">
      <div class="empty-ico">🏫</div>
      <div class="empty-title">Belum ada data kelas</div>
      <div class="empty-sub">Tambahkan kelas pertama menggunakan form di atas 👆</div>
    </div>
    <?php endif; ?>
  </div>

  <!-- Mobile Cards -->
  <div class="mob-list" id="mobList">
    <?php if($total_rows > 0): mysqli_data_seek($data,0); while($d=mysqli_fetch_assoc($data)):
      $jur = strtolower($d['jurusan']??'umum');
      $jmap = ['ipa'=>'j-ipa','ips'=>'j-ips','bahasa'=>'j-bahasa','umum'=>'j-umum'];
      $jcls = $jmap[$jur] ?? 'j-umum';
      $jml  = intval($d['jumlah_siswa']??0);
      $kap  = intval($d['kapasitas']??1);
      $pct  = $kap > 0 ? min(100, round($jml/$kap*100)) : 0;
      $kcls = $pct>=100 ? 'kap-full' : ($pct>=85 ? 'kap-warn' : 'kap-ok');
    ?>
    <div class="mob-card" data-search="<?= strtolower(htmlspecialchars($d['nama_kelas'].' '.($d['jurusan']??'').' '.($d['wali_kelas']??'').' '.($d['tingkat']??''))) ?>">
      <div class="mob-top">
        <?php if($hasTingkat): ?><div class="tchip"><?= htmlspecialchars($d['tingkat']??'—') ?></div><?php endif; ?>
        <div class="mob-name"><?= htmlspecialchars($d['nama_kelas']) ?></div>
      </div>
      <div class="mob-tags">
        <?php if($hasJurusan): ?><span class="jbadge <?= $jcls ?>"><span class="jdot"></span><?= htmlspecialchars($d['jurusan']??'—') ?></span><?php endif; ?>
        <?php if($hasRuang && !empty($d['ruang_kelas'])): ?><span class="rchip">🚪 <?= htmlspecialchars($d['ruang_kelas']) ?></span><?php endif; ?>
      </div>
      <div class="mob-grid" style="margin-top:.75rem">
        <?php if($hasWali): ?>
        <div><div class="mob-fl">Wali Kelas</div><div class="mob-fv">👤 <?= htmlspecialchars($d['wali_kelas']??'—') ?></div></div>
        <?php endif; ?>
        <?php if($hasKapasitas): ?>
        <div><div class="mob-fl">Kapasitas</div><div class="mob-fv"><?= $kap ?> siswa</div></div>
        <?php endif; ?>
        <?php if($hasSiswaTbl && $hasKelasId): ?>
        <div style="grid-column:1/-1">
          <div class="mob-fl">Isi Kelas</div>
          <div class="kapbar" style="margin-top:.25rem">
            <span class="kapnum"><?= $jml ?>/<?= $kap ?> (<?= $pct ?>%)</span>
            <div class="kapbg"><div class="kapfill <?= $kcls ?>" style="width:<?= $pct ?>%"></div></div>
          </div>
        </div>
        <?php endif; ?>
        <?php if($hasTahun): ?>
        <div><div class="mob-fl">Tahun Ajaran</div><div class="mob-fv" style="font-family:'DM Mono',monospace"><?= htmlspecialchars($d['tahun_ajaran']??'') ?></div></div>
        <?php endif; ?>
      </div>
      <div class="mob-acts">
        <a href="?edit=<?= $d['id'] ?>" class="btn btn-amb">✏️ Edit</a>
        <button class="btn btn-danger" onclick="konfirmHapus(<?= $d['id'] ?>,'<?= htmlspecialchars(addslashes($d['nama_kelas'])) ?>')">🗑️ Hapus</button>
      </div>
    </div>
    <?php endwhile; else: ?>
    <div class="empty" style="padding:3rem 1rem">
      <div class="empty-ico">🏫</div>
      <div class="empty-title">Belum ada data kelas</div>
    </div>
    <?php endif; ?>
  </div>

</div><!-- /.sc table -->

</div><!-- /.wrap -->
</div><!-- /.main -->

<!-- ════ MODAL HAPUS ════ -->
<div class="modal-bg" id="delModal">
  <div class="modal-box">
    <div class="modal-ico">⚠️</div>
    <div class="modal-ttl">Konfirmasi Hapus</div>
    <div class="modal-msg" id="delMsg"></div>
    <div class="modal-acts">
      <button class="btn btn-ghost" onclick="document.getElementById('delModal').classList.remove('open')">✕ Batal</button>
      <button class="btn btn-danger" id="delConfirm">🗑️ Ya, Hapus</button>
    </div>
  </div>
</div>

<script>
/* ── Search ── */
function srch(){
  const q = document.getElementById('si').value.toLowerCase();
  document.querySelectorAll('#dtbl tbody tr').forEach(r => {
    r.style.display = r.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
  document.querySelectorAll('#mobList .mob-card').forEach(c => {
    const t = (c.dataset.search||'') + c.textContent.toLowerCase();
    c.style.display = t.includes(q) ? '' : 'none';
  });
}

/* ── Delete Modal ── */
let delId = null;
function konfirmHapus(id, nama){
  delId = id;
  document.getElementById('delMsg').textContent =
    `Hapus kelas "${nama}"?\n\nKelas tidak dapat dihapus jika masih ada siswa di dalamnya.`;
  document.getElementById('delModal').classList.add('open');
}
document.getElementById('delConfirm').addEventListener('click', () => {
  if(delId) location.href = 'kelas.php?hapus=' + delId;
});
document.getElementById('delModal').addEventListener('click', function(e){
  if(e.target === this) this.classList.remove('open');
});
document.addEventListener('keydown', e => {
  if(e.key === 'Escape') document.getElementById('delModal').classList.remove('open');
});

/* ── Scroll to form on edit/error ── */
<?php if($editData || $msg_type==='err'): ?>
window.addEventListener('load', () => {
  document.getElementById('fcard')?.scrollIntoView({ behavior:'smooth', block:'start' });
});
<?php endif; ?>

/* ── Auto-dismiss success toasts ── */
<?php if($msg_type==='ok'||$msg_type==='del'): ?>
const ab = document.getElementById('alertBox');
if(ab) setTimeout(() => {
  ab.style.transition = 'opacity .45s,transform .45s';
  ab.style.opacity = '0'; ab.style.transform = 'translateY(-8px)';
  setTimeout(() => ab.remove(), 450);
}, 5000);
<?php endif; ?>

/* ── CSV Drag & Drop ── */
const csvFile  = document.getElementById('csvFile');
const fileBadge= document.getElementById('fileBadge');
const fileNameEl=document.getElementById('fileName');
const dropzone = document.getElementById('dropzone');
const dzIco    = document.getElementById('dzIco');

function applyFile(file){
  if(!file) return;
  if(file.name.split('.').pop().toLowerCase() !== 'csv'){ alert('⚠️ Hanya file .CSV'); return; }
  if(file.size > 5*1024*1024){ alert('⚠️ Maks 5MB'); return; }
  const dt = new DataTransfer(); dt.items.add(file); csvFile.files = dt.files;
  fileNameEl.textContent = file.name;
  fileBadge.style.display = 'block';
  if(dzIco) dzIco.textContent = '✅';
}
csvFile?.addEventListener('change', function(){ if(this.files[0]) applyFile(this.files[0]); });
if(dropzone){
  dropzone.addEventListener('click', e => { if(e.target.tagName !== 'SPAN') csvFile.click(); });
  ['dragenter','dragover'].forEach(ev => dropzone.addEventListener(ev, e => { e.preventDefault(); dropzone.classList.add('drag'); }));
  ['dragleave','drop'].forEach(ev => dropzone.addEventListener(ev, () => dropzone.classList.remove('drag')));
  dropzone.addEventListener('drop', e => { e.preventDefault(); applyFile(e.dataTransfer.files[0]); });
}
document.getElementById('importForm')?.addEventListener('submit', function(e){
  if(!csvFile || !csvFile.files[0]){ e.preventDefault(); alert('⚠️ Pilih file CSV terlebih dahulu!'); return; }
  const t = document.getElementById('impBtnTxt');
  const b = document.getElementById('impBtn');
  if(t) t.textContent = '⏳ Mengimpor…';
  if(b){ b.disabled = true; b.style.opacity = '.65'; }
});
</script>