<?php
/* ══════════════════════════════════════════════════════
   nilai.php — Manajemen Nilai Siswa
   MA As-Syafi'iyah 02 Bekasi
   FIX: ob_start() + koneksi.php SEBELUM navbar
        agar header() redirect tidak menyebabkan layar putih
══════════════════════════════════════════════════════ */

ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ── Koneksi DULU sebelum apapun ──
include 'koneksi.php';

// Pastikan $conn tersedia
if (!isset($conn)) {
    if      (isset($koneksi))  $conn = $koneksi;
    elseif  (isset($db))       $conn = $db;
    elseif  (isset($connect))  $conn = $connect;
    else {
        ob_end_clean();
        die("<div style='padding:2rem;font-family:sans-serif;color:red'>
            ❌ <b>Koneksi database tidak ditemukan.</b><br>
            Pastikan <code>koneksi.php</code> membuat variabel <code>\$conn</code>.
        </div>");
    }
}

// ── Helper: ambil kolom tabel ──
function getCol($conn, $table) {
    $c = [];
    $r = mysqli_query($conn, "SHOW COLUMNS FROM `$table`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $c[] = $row['Field'];
    return $c;
}

$nKol = getCol($conn, 'nilai');
$sKol = getCol($conn, 'siswa');
$mKol = getCol($conn, 'mata_pelajaran');

$hNA   = in_array('nilai_akhir',  $nKol);
$hPred = in_array('predikat',     $nKol);
$hCA   = in_array('created_at',   $nKol);
$hUA   = in_array('updated_at',   $nKol);
$hThn  = in_array('tahun_ajaran', $nKol);
$hSmt  = in_array('semester',     $nKol);
$hNisn = in_array('nisn',  $sKol);
$hNis  = in_array('nis',   $sKol);
$hKls  = in_array('kelas', $sKol);
$hKKM  = in_array('kkm',   $mKol);

function hitungPred($na) {
    if ($na >= 90) return 'A'; if ($na >= 80) return 'B';
    if ($na >= 70) return 'C'; if ($na >= 60) return 'D'; return 'E';
}
function semTxt($n) { return $n == 1 ? 'Ganjil' : ($n == 2 ? 'Genap' : (string)$n); }

// ══════════════════════════════════════════════════
// SEMUA PROSES POST/GET DI SINI — SEBELUM NAVBAR
// ══════════════════════════════════════════════════

$msg = ''; $mtype = ''; $editData = null; $debugSQL = '';

// ── HAPUS ──
if (isset($_GET['hapus'])) {
    $id = intval($_GET['hapus']);
    $deleteQuery = "DELETE FROM nilai WHERE id=$id";
    if (mysqli_query($conn, $deleteQuery)) {
        ob_end_clean(); header("Location: nilai.php?ok=del"); exit();
    } else {
        $msg = '❌ Gagal hapus: ' . mysqli_error($conn);
        $mtype = 'err'; $debugSQL = $deleteQuery;
    }
}

// ── SIMPAN ──
if (isset($_POST['simpan'])) {
    $sid = intval($_POST['siswa_id']  ?? 0);
    $mid = intval($_POST['mapel_id']  ?? 0);
    $smt = $hSmt ? intval($_POST['semester'] ?? 1) : 1;
    $thn = $hThn ? mysqli_real_escape_string($conn, trim($_POST['tahun_ajaran'] ?? '')) : date('Y') . '/' . (date('Y') + 1);
    $nt  = floatval($_POST['nilai_tugas'] ?? 0);
    $nu  = floatval($_POST['nilai_uts']   ?? 0);
    $na2 = floatval($_POST['nilai_uas']   ?? 0);

    if (!$sid || !$mid) {
        $msg = '❌ Siswa dan Mata Pelajaran wajib dipilih!'; $mtype = 'err';
    } elseif ($nt < 0 || $nt > 100 || $nu < 0 || $nu > 100 || $na2 < 0 || $na2 > 100) {
        $msg = '❌ Nilai harus antara 0-100!'; $mtype = 'err';
    } else {
        $dupWhere = ["siswa_id=$sid", "mapel_id=$mid"];
        if ($hSmt) $dupWhere[] = "semester=$smt";
        if ($hThn && $thn) $dupWhere[] = "tahun_ajaran='$thn'";
        $cek = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM nilai WHERE " . implode(' AND ', $dupWhere)));
        if ($cek && $cek['c'] > 0) {
            $msg = '⚠️ Data nilai sudah ada! Silakan edit data yang sudah ada.'; $mtype = 'err';
        } else {
            $naVal = round(($nt + $nu + $na2) / 3, 2);
            $pred  = hitungPred($naVal);
            $cols  = ['siswa_id', 'mapel_id']; $vals = [$sid, $mid];
            if ($hSmt) { $cols[] = 'semester';     $vals[] = $smt; }
            if ($hThn) { $cols[] = 'tahun_ajaran'; $vals[] = "'$thn'"; }
            $cols[] = 'nilai_tugas'; $vals[] = $nt;
            $cols[] = 'nilai_uts';   $vals[] = $nu;
            $cols[] = 'nilai_uas';   $vals[] = $na2;
            if ($hNA)   { $cols[] = 'nilai_akhir'; $vals[] = $naVal; }
            if ($hPred) { $cols[] = 'predikat';    $vals[] = "'$pred'"; }
            if ($hCA)   { $cols[] = 'created_at';  $vals[] = 'NOW()'; }
            if ($hUA)   { $cols[] = 'updated_at';  $vals[] = 'NOW()'; }
            $insertQuery = "INSERT INTO nilai (" . implode(',', $cols) . ") VALUES (" . implode(',', $vals) . ")";
            $debugSQL = $insertQuery;
            if (mysqli_query($conn, $insertQuery)) {
                ob_end_clean(); header("Location: nilai.php?ok=add"); exit();
            } else {
                $msg = '❌ Gagal menyimpan! Error: ' . mysqli_error($conn); $mtype = 'err';
            }
        }
    }
}

// ── UPDATE ──
if (isset($_POST['update'])) {
    $id  = intval($_POST['id']       ?? 0);
    $sid = intval($_POST['siswa_id'] ?? 0);
    $mid = intval($_POST['mapel_id'] ?? 0);
    $smt = $hSmt ? intval($_POST['semester'] ?? 1) : 1;
    $thn = $hThn ? mysqli_real_escape_string($conn, trim($_POST['tahun_ajaran'] ?? '')) : date('Y') . '/' . (date('Y') + 1);
    $nt  = floatval($_POST['nilai_tugas'] ?? 0);
    $nu  = floatval($_POST['nilai_uts']   ?? 0);
    $na2 = floatval($_POST['nilai_uas']   ?? 0);

    if (!$id || !$sid || !$mid) {
        $msg = '❌ Data tidak lengkap!'; $mtype = 'err';
        $r2 = mysqli_query($conn, "SELECT * FROM nilai WHERE id=$id");
        if ($r2) $editData = mysqli_fetch_assoc($r2);
    } elseif ($nt < 0 || $nt > 100 || $nu < 0 || $nu > 100 || $na2 < 0 || $na2 > 100) {
        $msg = '❌ Nilai harus antara 0-100!'; $mtype = 'err';
        $r2 = mysqli_query($conn, "SELECT * FROM nilai WHERE id=$id");
        if ($r2) $editData = mysqli_fetch_assoc($r2);
    } else {
        $dupWhere = ["siswa_id=$sid", "mapel_id=$mid", "id!=$id"];
        if ($hSmt) $dupWhere[] = "semester=$smt";
        if ($hThn && $thn) $dupWhere[] = "tahun_ajaran='$thn'";
        $cek = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM nilai WHERE " . implode(' AND ', $dupWhere)));
        if ($cek && $cek['c'] > 0) {
            $msg = '⚠️ Data dengan kombinasi yang sama sudah ada!'; $mtype = 'err';
            $r2 = mysqli_query($conn, "SELECT * FROM nilai WHERE id=$id");
            if ($r2) $editData = mysqli_fetch_assoc($r2);
        } else {
            $naVal = round(($nt + $nu + $na2) / 3, 2);
            $pred  = hitungPred($naVal);
            $sets  = ["siswa_id=$sid", "mapel_id=$mid"];
            if ($hSmt) $sets[] = "semester=$smt";
            if ($hThn) $sets[] = "tahun_ajaran='$thn'";
            $sets[] = "nilai_tugas=$nt";
            $sets[] = "nilai_uts=$nu";
            $sets[] = "nilai_uas=$na2";
            if ($hNA)   $sets[] = "nilai_akhir=$naVal";
            if ($hPred) $sets[] = "predikat='$pred'";
            if ($hUA)   $sets[] = "updated_at=NOW()";
            $updateQuery = "UPDATE nilai SET " . implode(',', $sets) . " WHERE id=$id";
            $debugSQL = $updateQuery;
            if (mysqli_query($conn, $updateQuery)) {
                ob_end_clean(); header("Location: nilai.php?ok=update"); exit();
            } else {
                $msg = '❌ Gagal update! Error: ' . mysqli_error($conn); $mtype = 'err';
                $r2 = mysqli_query($conn, "SELECT * FROM nilai WHERE id=$id");
                if ($r2) $editData = mysqli_fetch_assoc($r2);
            }
        }
    }
}

// ── EDIT MODE ──
if (isset($_GET['edit']) && !$editData) {
    $id = intval($_GET['edit']);
    $r  = mysqli_query($conn, "SELECT * FROM nilai WHERE id=$id");
    if ($r && mysqli_num_rows($r) > 0) {
        $editData = mysqli_fetch_assoc($r);
    } else {
        $msg = '❌ Data nilai tidak ditemukan!'; $mtype = 'err';
    }
}

// ── PESAN SUKSES ──
if (isset($_GET['ok'])) {
    if ($_GET['ok'] === 'add')    { $msg = '✅ Nilai berhasil disimpan!';   $mtype = 'ok'; }
    if ($_GET['ok'] === 'update') { $msg = '✅ Nilai berhasil diperbarui!'; $mtype = 'ok'; }
    if ($_GET['ok'] === 'del')    { $msg = '🗑️ Nilai berhasil dihapus.';    $mtype = 'del'; }
}

// ── FILTER ──
$fkelas = isset($_GET['kelas'])    ? mysqli_real_escape_string($conn, $_GET['kelas'])          : '';
$fmapel = isset($_GET['mapel'])    ? intval($_GET['mapel'])                                    : 0;
$fsem   = isset($_GET['semester']) ? intval($_GET['semester'])                                 : 0;
$ftahun = (isset($_GET['tahun']) && !empty(trim($_GET['tahun'])))
          ? mysqli_real_escape_string($conn, trim($_GET['tahun'])) : '';

$where = "WHERE 1=1";
if ($fkelas && $hKls) $where .= " AND s.kelas='$fkelas'";
if ($fmapel)          $where .= " AND n.mapel_id=$fmapel";
if ($fsem   && $hSmt) $where .= " AND n.semester=$fsem";
if ($ftahun && $hThn) $where .= " AND n.tahun_ajaran='$ftahun'";

// ── DATA DROPDOWN (disimpan ke array agar tidak perlu data_seek) ──
$sCols = 'id,nama';
if ($hNisn) $sCols .= ',nisn';
if ($hNis)  $sCols .= ',nis';
if ($hKls)  $sCols .= ',kelas';
$siswaRes = mysqli_query($conn, "SELECT $sCols FROM siswa ORDER BY nama");
$siswaRows = [];
if ($siswaRes) while ($s = mysqli_fetch_assoc($siswaRes)) $siswaRows[] = $s;

$mCols = 'id,nama_mapel';
if ($hKKM) $mCols .= ',kkm';
$mapelRes = mysqli_query($conn, "SELECT $mCols FROM mata_pelajaran ORDER BY nama_mapel");
$mapelRows = [];
if ($mapelRes) while ($m = mysqli_fetch_assoc($mapelRes)) $mapelRows[] = $m;

$kelasRows = [];
if ($hKls) {
    $klRes = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE kelas IS NOT NULL AND kelas!='' ORDER BY kelas");
    if ($klRes) while ($k = mysqli_fetch_assoc($klRes)) $kelasRows[] = $k;
}

// ── DATA TABEL ──
$tSel = "n.id,n.siswa_id,n.mapel_id,n.nilai_tugas,n.nilai_uts,n.nilai_uas,s.nama as nama_siswa,m.nama_mapel";
if ($hNA)   $tSel .= ",n.nilai_akhir";
if ($hPred) $tSel .= ",n.predikat";
if ($hSmt)  $tSel .= ",n.semester";
if ($hThn)  $tSel .= ",n.tahun_ajaran";
if ($hNisn) $tSel .= ",s.nisn";
if ($hNis)  $tSel .= ",s.nis";
if ($hKls)  $tSel .= ",s.kelas";
if ($hKKM)  $tSel .= ",m.kkm";

$ordP = ["s.nama", "m.nama_mapel"];
if ($hSmt) array_unshift($ordP, "n.semester");
if ($hThn) array_unshift($ordP, "n.tahun_ajaran DESC");

$dataRes  = mysqli_query($conn, "SELECT $tSel FROM nilai n JOIN siswa s ON n.siswa_id=s.id JOIN mata_pelajaran m ON n.mapel_id=m.id $where ORDER BY " . implode(',', $ordP));
$dataRows = [];
if ($dataRes) while ($d = mysqli_fetch_assoc($dataRes)) $dataRows[] = $d;
$totalRow = count($dataRows);

// ── STATISTIK ──
$rataKelas = 0; $lulus = 0; $tidakLulus = 0;
if ($hNA) {
    $ar = mysqli_fetch_assoc(mysqli_query($conn, "SELECT AVG(n.nilai_akhir) r FROM nilai n JOIN siswa s ON n.siswa_id=s.id JOIN mata_pelajaran m ON n.mapel_id=m.id $where"));
    $rataKelas = ($ar && $ar['r']) ? round($ar['r'], 1) : 0;
    if ($hKKM) {
        $sr = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(n.nilai_akhir>=m.kkm) l, SUM(n.nilai_akhir<m.kkm) tl FROM nilai n JOIN siswa s ON n.siswa_id=s.id JOIN mata_pelajaran m ON n.mapel_id=m.id $where"));
        $lulus = intval($sr['l'] ?? 0);
        $tidakLulus = intval($sr['tl'] ?? 0);
    }
}

$tahunList = [];
if ($hThn) {
    $tQ = mysqli_query($conn, "SELECT DISTINCT tahun_ajaran FROM nilai WHERE tahun_ajaran IS NOT NULL AND tahun_ajaran!='' ORDER BY tahun_ajaran DESC");
    if ($tQ) while ($tR = mysqli_fetch_assoc($tQ)) $tahunList[] = $tR['tahun_ajaran'];
}

// ── Baru include navbar setelah semua proses selesai ──
$page_title  = "Nilai Siswa — MA As-Syafi'iyah 02";
$active_menu = 'nilai';
$loader_text = 'Memuat Data Nilai';
include 'navbar.php';

ob_end_flush();
?>

<!-- Font tambahan -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;500;600;700;800;900&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">

<style>
:root{
    --nv-rose:#F43F5E; --nv-rose-dark:#E11D48; --nv-rose-xd:#BE123C;
    --nv-rose-lt:#FFE4E6; --nv-rose-pale:#FFF1F2;
    --nv-pink:#EC4899; --nv-amber:#FBBF24; --nv-amber-dark:#D97706;
    --nv-sky:#38BDF8; --nv-violet:#A78BFA;
    --nv-text:#4C0519; --nv-txm:#FDA4AF; --nv-txd:#BE123C;
    --nv-border:#FECDD3; --nv-sh:rgba(244,63,94,.15);
}
.main .wrap{font-family:'Nunito',sans-serif}
.main{overflow-x:hidden}
.wrap{overflow-x:hidden;box-sizing:border-box}
.main::before{content:'';position:fixed;inset:0;background-image:radial-gradient(circle,#FECDD3 1.5px,transparent 1.5px);background-size:36px 36px;opacity:.3;pointer-events:none;z-index:0}
.nv-bgd{position:fixed;inset:0;pointer-events:none;z-index:0;overflow:hidden}
.nv-ds{position:absolute;opacity:.055;user-select:none;line-height:1;font-size:72px}
.nv-d1{top:5%;left:2%;animation:nvdf1 23s ease-in-out infinite}
.nv-d2{top:55%;right:3%;font-size:90px;animation:nvdf2 18s ease-in-out infinite 2s}
.nv-d3{bottom:8%;left:11%;font-size:62px;animation:nvdf3 22s ease-in-out infinite 4s}
.nv-d4{top:30%;right:18%;font-size:78px;animation:nvdf1 26s ease-in-out infinite 1s}
.nv-d5{top:72%;left:38%;font-size:58px;animation:nvdf2 20s ease-in-out infinite 3s}
@keyframes nvdf1{0%,100%{transform:translate(0,0) rotate(0)}50%{transform:translate(18px,-26px) rotate(11deg)}}
@keyframes nvdf2{0%,100%{transform:translate(0,0)}50%{transform:translate(-14px,20px) rotate(-8deg)}}
@keyframes nvdf3{0%,100%{transform:translate(0,0)}33%{transform:translate(22px,-14px) rotate(7deg)}66%{transform:translate(-8px,10px) rotate(-5deg)}}
@keyframes nvFadeUp{from{opacity:0;transform:translateY(24px)}to{opacity:1;transform:translateY(0)}}
@keyframes nvSlideD{from{opacity:0;transform:translateY(-14px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}
@keyframes nvNoteFlt{0%,100%{transform:translateY(0) rotate(-5deg)}50%{transform:translateY(-14px) rotate(6deg)}}
@keyframes nvbA{0%,100%{transform:translateY(0)}50%{transform:translateY(-20px) rotate(10deg)}}
@keyframes nvbB{0%,100%{transform:translateY(0)}50%{transform:translateY(16px)}}
@keyframes nvbC{0%,100%{transform:translate(0,0) rotate(14deg)}50%{transform:translate(-12px,10px) rotate(-10deg)}}
@keyframes nvEmBnc{0%,100%{transform:translateY(0)}50%{transform:translateY(-12px)}}
@keyframes nvStag{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}

/* ═══ HERO ═══ */
.nv-hero{background:linear-gradient(135deg,#BE123C 0%,#F43F5E 40%,#EC4899 75%,#8B5CF6 100%);border-radius:24px;padding:2.125rem 2.5rem;margin-bottom:1.5rem;position:relative;overflow:hidden;box-shadow:0 10px 36px rgba(244,63,94,.35);animation:nvFadeUp .6s ease-out}
.nv-hb{position:absolute;border-radius:50%;opacity:.12;background:white}
.nv-hb1{width:220px;height:220px;top:-65px;right:48px;animation:nvbA 7s ease-in-out infinite}
.nv-hb2{width:140px;height:140px;bottom:-48px;right:240px;animation:nvbB 5s ease-in-out infinite}
.nv-hb3{width:86px;height:86px;top:10px;right:340px;border-radius:22px;opacity:.2;animation:nvbC 6s ease-in-out infinite}
.nv-hcon{position:relative;z-index:2;display:flex;align-items:center;justify-content:space-between;gap:1.5rem}
.nv-hey{display:inline-flex;align-items:center;gap:.5rem;background:rgba(255,255,255,.2);backdrop-filter:blur(8px);border:1px solid rgba(255,255,255,.3);border-radius:50px;padding:.325rem .875rem;font-size:.74rem;font-weight:700;color:white;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.875rem}
.nv-htit{font-size:2.125rem;font-weight:900;color:white;line-height:1.1;letter-spacing:-.03em;margin-bottom:.625rem}
.nv-htit span{background:linear-gradient(90deg,#FDE68A,#FCA5A5);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.nv-hdesc{font-size:.9rem;color:rgba(255,255,255,.88);font-weight:500}
.nv-hright{display:flex;align-items:center;gap:1.125rem;flex-shrink:0}
.nv-hchip{text-align:center;background:rgba(255,255,255,.15);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.25);border-radius:16px;padding:.875rem 1.25rem;min-width:96px}
.nv-hcnum{font-size:2rem;font-weight:900;color:white;line-height:1;font-family:'Space Mono',monospace}
.nv-hclbl{font-size:.65rem;color:rgba(255,255,255,.8);font-weight:700;margin-top:.25rem;text-transform:uppercase;letter-spacing:.06em}
.nv-illo{width:96px;height:96px;object-fit:contain;filter:drop-shadow(0 8px 24px rgba(0,0,0,.25));animation:nvNoteFlt 3.5s ease-in-out infinite}

/* ═══ STATS ═══ */
.nv-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:1.125rem;margin-bottom:1.5rem}
.nv-sc{background:#fff;border-radius:18px;border:2px solid var(--nv-border);box-shadow:0 4px 20px var(--nv-sh);padding:1.25rem 1.375rem;display:flex;align-items:center;gap:.875rem;transition:all .28s cubic-bezier(.34,1.56,.64,1);animation:nvStag .5s ease-out backwards}
.nv-sc:nth-child(1){animation-delay:.06s}.nv-sc:nth-child(2){animation-delay:.12s}.nv-sc:nth-child(3){animation-delay:.18s}.nv-sc:nth-child(4){animation-delay:.24s}
.nv-sc:hover{transform:translateY(-5px) scale(1.02);box-shadow:0 10px 28px var(--nv-sh)}
.nv-sorb{width:48px;height:48px;min-width:48px;border-radius:13px;display:flex;align-items:center;justify-content:center;font-size:1.5rem}
.nv-sorb.r{background:var(--nv-rose-lt)}.nv-sorb.g{background:#D1FAE5}.nv-sorb.a{background:#FEF3C7}.nv-sorb.p{background:#FCE7F3}
.nv-sval{font-size:2rem;font-weight:900;font-family:'Space Mono',monospace;color:var(--nv-rose-xd);line-height:1}
.nv-slbl{font-size:.7rem;color:var(--nv-txm);font-weight:800;text-transform:uppercase;letter-spacing:.05em;margin-top:2px}

/* ═══ ALERTS ═══ */
.nv-alert{display:flex;align-items:flex-start;gap:.875rem;padding:1rem 1.5rem;border-radius:16px;margin-bottom:1.25rem;font-weight:700;font-size:.9rem;animation:nvSlideD .4s cubic-bezier(.34,1.56,.64,1);font-family:'Nunito',sans-serif}
.nv-aico{font-size:1.625rem;flex-shrink:0;margin-top:1px}
.nv-aok {background:#FFE4E6;color:#9F1239;border:2px solid #FCA5A5}
.nv-adel{background:#FEF3C7;color:#92400E;border:2px solid #FCD34D}
.nv-aerr{background:#FEE2E2;color:#991B1B;border:2px solid #FCA5A5;word-break:break-word}
.nv-aedt{background:#FEF3C7;color:#92400E;border:2px solid #FCD34D}
.nv-dbg{background:#1E293B;color:#94A3B8;border-radius:12px;padding:.875rem 1.375rem;margin-bottom:1.25rem;font-family:'Space Mono',monospace;font-size:.7rem;line-height:1.9;word-break:break-all}
.nv-dbg strong{color:#FDA4AF;font-size:.74rem}

/* ═══ CARD ═══ */
.nv-card{background:#fff;border-radius:22px;border:2px solid var(--nv-border);box-shadow:0 4px 24px var(--nv-sh);margin-bottom:1.5rem;overflow:hidden;animation:nvFadeUp .5s ease-out backwards}
.nv-card.nv-em{border-color:var(--nv-amber);box-shadow:0 4px 32px rgba(251,191,36,.2)}
.nv-chd{padding:1.125rem 1.5rem;display:flex;align-items:center;justify-content:space-between;border-bottom:2px solid var(--nv-border);flex-wrap:wrap;gap:.5rem}
.nv-chdl{display:flex;align-items:center;gap:.75rem}
.nv-cbdg{width:42px;height:42px;min-width:42px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.25rem}
.nv-cbdg.r{background:var(--nv-rose-lt)}.nv-cbdg.am{background:#FEF3C7}.nv-cbdg.fi{background:#EDE9FE}
.nv-ctit{font-size:1.05rem;font-weight:800;color:var(--nv-text)}
.nv-csub{font-size:.76rem;color:var(--nv-txm);font-weight:700;margin-top:1px}

/* ═══ FORM ═══ */
.nv-cbdy{padding:1.5rem}
.nv-g5{display:grid;grid-template-columns:repeat(4,1fr);gap:1rem;align-items:end}
.nv-g4{display:grid;grid-template-columns:repeat(4,1fr);gap:1.125rem}
.nv-g3p{display:grid;grid-template-columns:1fr 1fr 1fr minmax(120px,auto);gap:1.125rem;align-items:end}
.nv-fg{display:flex;flex-direction:column;gap:.45rem}
.nv-flbl{font-size:.74rem;font-weight:800;color:var(--nv-text);text-transform:uppercase;letter-spacing:.05em;display:flex;align-items:center;gap:.35rem}
.nv-req{color:var(--nv-rose)}
.nv-fi,.nv-fs{padding:.78rem 1rem;background:var(--nv-rose-pale);border:2px solid var(--nv-border);border-radius:12px;font-size:.875rem;font-family:'Nunito',sans-serif;font-weight:600;color:var(--nv-text);transition:all .22s;outline:none;width:100%}
.nv-fi:focus,.nv-fs:focus{border-color:var(--nv-rose);background:white;box-shadow:0 0 0 4px rgba(244,63,94,.12);transform:translateY(-1px)}
.nv-fi.mn{font-family:'Space Mono',monospace;font-size:.9rem;font-weight:700;text-align:center}
.nv-prev{background:linear-gradient(135deg,var(--nv-rose-lt),#FFF1F2);border:2px solid var(--nv-border);border-radius:12px;padding:.875rem;text-align:center;transition:all .3s}
.nv-prev-num{font-size:2rem;font-weight:900;font-family:'Space Mono',monospace;color:var(--nv-rose-xd);line-height:1;transition:color .3s}
.nv-prev-lbl{font-size:.65rem;font-weight:800;color:var(--nv-txm);text-transform:uppercase;letter-spacing:.06em;margin-top:3px}
.nv-prev-pred{display:none;margin-top:.35rem;padding:.2rem .7rem;border-radius:50px;font-size:.82rem;font-weight:900;border:2px solid transparent;transition:all .3s}
.nv-kstrip{margin-top:.75rem;padding:.7rem 1.125rem;background:var(--nv-rose-pale);border:1.5px solid var(--nv-border);border-radius:11px;font-size:.8rem;font-weight:700;color:var(--nv-txd);display:none;align-items:center;gap:.625rem;flex-wrap:wrap;font-family:'Nunito',sans-serif}
.nv-kbdg{padding:.18rem .6rem;background:white;border:1.5px solid var(--nv-border);border-radius:7px;font-family:'Space Mono',monospace;font-size:.75rem;font-weight:700;color:var(--nv-rose-xd)}
.nv-fdiv{border:none;border-top:2px dashed var(--nv-border);margin:1.25rem 0}
.nv-fact{margin-top:1.5rem;display:flex;align-items:center;gap:.875rem;flex-wrap:wrap}
.nv-bsub{display:inline-flex;align-items:center;gap:.5rem;padding:.8rem 1.75rem;border-radius:12px;border:none;font-size:.95rem;font-weight:800;font-family:'Nunito',sans-serif;cursor:pointer;transition:all .25s cubic-bezier(.34,1.56,.64,1);-webkit-tap-highlight-color:transparent}
.nv-bsub.sv{background:linear-gradient(135deg,var(--nv-rose),var(--nv-rose-dark));color:white;box-shadow:0 5px 18px rgba(244,63,94,.4)}.nv-bsub.sv:hover{transform:translateY(-2px) scale(1.02);box-shadow:0 9px 26px rgba(244,63,94,.5)}
.nv-bsub.up{background:linear-gradient(135deg,var(--nv-amber),var(--nv-amber-dark));color:white;box-shadow:0 5px 18px rgba(251,191,36,.4)}.nv-bsub.up:hover{transform:translateY(-2px) scale(1.02)}
.nv-bsub.fi{background:linear-gradient(135deg,var(--nv-violet),#7C3AED);color:white;box-shadow:0 5px 18px rgba(167,139,250,.4)}.nv-bsub.fi:hover{transform:translateY(-2px) scale(1.02)}
.nv-bcan{display:inline-flex;align-items:center;gap:.4rem;padding:.8rem 1.375rem;border-radius:12px;border:2px solid var(--nv-border);font-size:.9rem;font-weight:700;font-family:'Nunito',sans-serif;background:#fff;color:var(--nv-txm);text-decoration:none;cursor:pointer;transition:all .25s;-webkit-tap-highlight-color:transparent}.nv-bcan:hover{border-color:var(--nv-rose-dark);color:var(--nv-rose-dark);background:#FFF1F2}
.nv-breset{display:inline-flex;align-items:center;justify-content:center;padding:.78rem 1rem;border-radius:12px;border:2px solid var(--nv-border);font-size:.95rem;font-weight:800;font-family:'Nunito',sans-serif;background:#fff;color:var(--nv-txm);text-decoration:none;cursor:pointer;transition:all .25s;-webkit-tap-highlight-color:transparent}.nv-breset:hover{border-color:var(--nv-rose);color:var(--nv-rose-dark);background:var(--nv-rose-pale)}

/* ═══ TABLE ═══ */
.nv-ttop{padding:1.125rem 1.5rem;background:linear-gradient(135deg,var(--nv-rose-xd),var(--nv-rose-dark));display:flex;align-items:center;justify-content:space-between;gap:.875rem;flex-wrap:wrap}
.nv-ttl{display:flex;align-items:center;gap:.625rem;color:white;font-size:1.05rem;font-weight:800;flex-wrap:wrap;font-family:'Nunito',sans-serif}
.nv-ttl img{filter:brightness(0) invert(1);opacity:.9}
.nv-tcnt{background:rgba(255,255,255,.22);padding:.18rem .75rem;border-radius:50px;font-size:.76rem}
.nv-sw{position:relative}
.nv-sw::before{content:'🔍';position:absolute;left:.875rem;top:50%;transform:translateY(-50%);font-size:.8rem;pointer-events:none}
.nv-si{padding:.575rem .875rem .575rem 2.5rem;background:rgba(255,255,255,.18);backdrop-filter:blur(8px);border:1.5px solid rgba(255,255,255,.3);border-radius:50px;color:white;font-size:.85rem;font-family:'Nunito',sans-serif;font-weight:600;outline:none;width:240px;transition:all .2s}
.nv-si::placeholder{color:rgba(255,255,255,.65)}.nv-si:focus{background:rgba(255,255,255,.28);border-color:white}
.nv-tscr{overflow-x:auto;-webkit-overflow-scrolling:touch;max-height:580px;overflow-y:auto}
.nv-tscr::-webkit-scrollbar{width:7px;height:7px}.nv-tscr::-webkit-scrollbar-track{background:var(--nv-rose-pale)}.nv-tscr::-webkit-scrollbar-thumb{background:var(--nv-rose);border-radius:50px}
.nv-tscr table{width:100%;border-collapse:collapse;min-width:820px}
.nv-tscr thead{position:sticky;top:0;z-index:5}
.nv-tscr thead tr{background:var(--nv-rose-lt);border-bottom:2px solid var(--nv-border)}
.nv-tscr th{padding:.8rem .9rem;text-align:left;font-size:.68rem;font-weight:800;color:var(--nv-rose-xd);text-transform:uppercase;letter-spacing:.07em;white-space:nowrap;font-family:'Nunito',sans-serif}
.nv-tscr th.ctr,.nv-tscr td.ctr{text-align:center}
.nv-tscr tbody tr{border-bottom:1.5px solid var(--nv-border);transition:all .18s}
.nv-tscr tbody tr:hover{background:var(--nv-rose-pale)}.nv-tscr tbody tr:last-child{border-bottom:none}
.nv-tscr td{padding:.875rem .9rem;font-size:.855rem;font-weight:600;color:var(--nv-text);vertical-align:middle;font-family:'Nunito',sans-serif}
.nv-tno{font-family:'Space Mono',monospace;font-size:.75rem;color:var(--nv-txm);width:32px}
.nv-tnm strong{font-size:.88rem;font-weight:800;display:block}
.nv-tnm small{font-size:.7rem;color:var(--nv-txm);font-weight:600;font-family:'Space Mono',monospace}
.nv-tval{font-family:'Space Mono',monospace;font-size:.9rem;font-weight:700;text-align:center}
.nv-tnaw{display:flex;align-items:center;gap:.4rem;min-width:100px}
.nv-tnan{font-family:'Space Mono',monospace;font-size:.9rem;font-weight:900;min-width:36px;text-align:right}
.nv-tnab{flex:1;background:var(--nv-border);border-radius:50px;height:6px;overflow:hidden}
.nv-tnaf{height:100%;border-radius:50px}
.nv-nA{background:linear-gradient(90deg,#22C55E,#16A34A)}.nv-nB{background:linear-gradient(90deg,#38BDF8,#0284C7)}.nv-nC{background:linear-gradient(90deg,#FBBF24,#D97706)}.nv-nD{background:linear-gradient(90deg,#FB923C,#EA580C)}.nv-nE{background:linear-gradient(90deg,#F43F5E,#E11D48)}
.nv-badge{display:inline-flex;align-items:center;gap:.22rem;padding:.26rem .7rem;border-radius:50px;font-size:.7rem;font-weight:800;white-space:nowrap}
.nv-bdot{width:5px;height:5px;border-radius:50%;display:inline-block}
.nv-bA{background:#DCFCE7;color:#166534}.nv-bA .nv-bdot{background:#22C55E}
.nv-bB{background:#DBEAFE;color:#1E40AF}.nv-bB .nv-bdot{background:#3B82F6}
.nv-bC{background:#FEF3C7;color:#92400E}.nv-bC .nv-bdot{background:#F59E0B}
.nv-bD{background:#FFEDD5;color:#9A3412}.nv-bD .nv-bdot{background:#F97316}
.nv-bE{background:#FEE2E2;color:#991B1B}.nv-bE .nv-bdot{background:#EF4444}
.nv-bsem1{background:#EDE9FE;color:#5B21B6}.nv-bsem1 .nv-bdot{background:#8B5CF6}
.nv-bsem2{background:#FCE7F3;color:#9D174D}.nv-bsem2 .nv-bdot{background:#EC4899}
.nv-blls{background:#D1FAE5;color:#065F46;border:1.5px solid #6EE7B7}
.nv-brmdi{background:#FEE2E2;color:#991B1B;border:1.5px solid #FCA5A5}
.nv-kchip{padding:.22rem .6rem;background:var(--nv-rose-pale);border:1.5px solid var(--nv-border);border-radius:7px;font-family:'Space Mono',monospace;font-size:.75rem;font-weight:700;color:var(--nv-txd)}
.nv-acts{display:flex;gap:.375rem;align-items:center}
.nv-ab{display:inline-flex;align-items:center;gap:.28rem;padding:.38rem .75rem;border-radius:9px;font-size:.72rem;font-weight:800;font-family:'Nunito',sans-serif;text-decoration:none;border:none;cursor:pointer;transition:all .22s;-webkit-tap-highlight-color:transparent}
.nv-ab:hover{transform:translateY(-2px)}
.nv-abedt{background:#FEF3C7;color:#92400E}.nv-abedt:hover{background:#FCD34D}
.nv-abdl{background:#FEE2E2;color:#991B1B}.nv-abdl:hover{background:#FECACA}
.nv-empty{text-align:center;padding:3.5rem 1.5rem}
.nv-emillo{font-size:5rem;margin-bottom:.875rem;animation:nvEmBnc 2s ease-in-out infinite}
.nv-emtit{font-size:1.125rem;font-weight:800;color:var(--nv-text);margin-bottom:.4rem;font-family:'Nunito',sans-serif}
.nv-emsub{font-size:.875rem;color:var(--nv-txm);font-weight:600;font-family:'Nunito',sans-serif}

/* ═══ RESPONSIVE ═══ */
@media(min-width:1280px){.nv-stats{grid-template-columns:repeat(4,1fr)}.nv-g5{grid-template-columns:repeat(4,1fr)}.nv-g4{grid-template-columns:repeat(4,1fr)}.nv-g3p{grid-template-columns:1fr 1fr 1fr auto}}
@media(min-width:1024px) and (max-width:1279px){.nv-stats{grid-template-columns:repeat(2,1fr);gap:1rem}.nv-g5{grid-template-columns:repeat(2,1fr);gap:1rem}.nv-g4{grid-template-columns:repeat(2,1fr);gap:1rem}.nv-g3p{grid-template-columns:1fr 1fr 1fr}.nv-htit{font-size:1.875rem}.nv-illo{width:80px;height:80px}.nv-hchip{min-width:88px;padding:.8rem 1rem}.nv-hcnum{font-size:1.75rem}}
@media(min-width:769px) and (max-width:1023px){.nv-stats{grid-template-columns:repeat(2,1fr);gap:.875rem;margin-bottom:1.25rem}.nv-g5{grid-template-columns:repeat(2,1fr);gap:.875rem}.nv-g4{grid-template-columns:repeat(2,1fr);gap:.875rem}.nv-g3p{grid-template-columns:1fr 1fr}.nv-g3p>.nv-fg:last-child{grid-column:1/-1}.nv-hero{padding:1.625rem 1.75rem;margin-bottom:1.25rem}.nv-hcon{gap:1rem}.nv-htit{font-size:1.625rem}.nv-hdesc{font-size:.82rem}.nv-hey{font-size:.65rem;padding:.275rem .75rem}.nv-illo{width:68px;height:68px}.nv-hright{gap:.875rem;flex-shrink:0}.nv-hchip{min-width:84px;padding:.7rem .9rem}.nv-hcnum{font-size:1.625rem}.nv-hclbl{font-size:.58rem}.nv-cbdy{padding:1.125rem}.nv-chd{padding:1rem 1.125rem}.nv-sc{padding:1.125rem 1rem}.nv-sval{font-size:1.75rem}.nv-sorb{width:42px;height:42px;font-size:1.25rem}.nv-ttop{flex-direction:column;align-items:flex-start;padding:1rem 1.125rem;gap:.625rem}.nv-sw{width:100%}.nv-si{width:100%}.nv-fact{flex-direction:column;gap:.625rem}.nv-bsub,.nv-bcan{width:100%;justify-content:center}.nv-g5>.nv-fg:last-child{grid-column:1/-1;flex-direction:row;gap:.5rem}.nv-bsub.fi{flex:1}.nv-tscr::before{content:'← Geser untuk lihat lebih →';display:block;text-align:center;font-size:.62rem;color:var(--nv-txm);font-weight:700;padding:.4rem;background:var(--nv-rose-lt);border-bottom:1px solid var(--nv-border)}}
@media(max-width:768px){.nv-hero{border-radius:18px;padding:1.625rem 1.5rem;margin-bottom:1.125rem}.nv-hcon{flex-direction:column;align-items:flex-start;gap:1rem}.nv-hright{align-self:stretch;flex-direction:row;justify-content:flex-end;gap:.875rem}.nv-htit{font-size:1.75rem}.nv-hdesc{font-size:.84rem}.nv-illo{width:68px;height:68px}.nv-hchip{min-width:88px;padding:.75rem 1rem}.nv-hcnum{font-size:1.75rem}.nv-stats{grid-template-columns:repeat(2,1fr);gap:.875rem;margin-bottom:1.125rem}.nv-g5,.nv-g4{grid-template-columns:repeat(2,1fr);gap:.875rem}.nv-g5>.nv-fg:last-child,.nv-g4>.nv-fg:last-child{grid-column:1/-1;flex-direction:row;gap:.5rem;align-items:flex-end}.nv-bsub.fi,.nv-breset{flex:1;justify-content:center}.nv-g3p{grid-template-columns:1fr 1fr;gap:.875rem}.nv-g3p>.nv-fg:last-child{grid-column:1/-1}.nv-cbdy{padding:1.125rem}.nv-chd{padding:1rem 1.125rem;flex-direction:column;align-items:flex-start;gap:.625rem}.nv-fact{gap:.625rem;flex-direction:column}.nv-bsub{width:100%;justify-content:center}.nv-bcan{width:100%;justify-content:center}.nv-ttop{flex-direction:column;align-items:flex-start;padding:1rem 1.125rem;gap:.75rem}.nv-sw{width:100%}.nv-si{width:100%}.nv-tscr::before{content:'← Geser untuk lihat lebih →';display:block;text-align:center;font-size:.62rem;color:var(--nv-txm);font-weight:700;padding:.4rem;background:var(--nv-rose-lt);border-bottom:1px solid var(--nv-border)}.nv-acts{gap:.3rem}}
@media(max-width:480px){.nv-hero{padding:1.25rem 1rem;border-radius:16px}.nv-hey{display:none}.nv-htit{font-size:1.375rem;margin-bottom:.3rem}.nv-hdesc{font-size:.78rem}.nv-hcon{gap:.875rem}.nv-hright{gap:.625rem}.nv-illo{width:56px;height:56px}.nv-hchip{min-width:78px;padding:.625rem .75rem}.nv-hcnum{font-size:1.5rem}.nv-hclbl{font-size:.56rem}.nv-stats{grid-template-columns:repeat(2,1fr);gap:.625rem;margin-bottom:1rem}.nv-sc{padding:.875rem;border-radius:14px}.nv-sval{font-size:1.625rem}.nv-sorb{width:38px;height:38px;min-width:38px;font-size:1.1rem;border-radius:10px}.nv-slbl{font-size:.62rem}.nv-g5,.nv-g4{grid-template-columns:1fr;gap:.75rem}.nv-g5>.nv-fg:last-child,.nv-g4>.nv-fg:last-child{grid-column:auto;flex-direction:row;gap:.5rem}.nv-g3p{grid-template-columns:1fr;gap:.75rem}.nv-g3p>.nv-fg:last-child{grid-column:auto}.nv-cbdy{padding:1rem}.nv-chd{padding:.875rem 1rem}.nv-fdiv{margin:.75rem 0}.nv-tscr table{min-width:600px}.nv-tscr td,.nv-tscr th{padding:.65rem .75rem;font-size:.78rem}.nv-slbl{letter-spacing:.03em}}
@media(max-width:360px){.nv-htit{font-size:1.25rem}.nv-hchip{min-width:70px;padding:.55rem .625rem}.nv-hcnum{font-size:1.375rem}.nv-hright{gap:.5rem}.nv-stats{grid-template-columns:1fr 1fr;gap:.5rem}.nv-sval{font-size:1.5rem}.nv-tscr table{min-width:520px}}
@media(max-height:500px) and (orientation:landscape){.nv-hero{padding:1rem 1.25rem;border-radius:14px;margin-bottom:1rem}.nv-hcon{flex-direction:row;gap:1rem}.nv-htit{font-size:1.375rem;margin-bottom:.25rem}.nv-hey{display:none}.nv-hright{flex-direction:row;gap:.75rem;align-self:center}.nv-illo{width:52px;height:52px}.nv-hchip{min-width:auto;padding:.5rem .75rem}.nv-hcnum{font-size:1.375rem}.nv-stats{grid-template-columns:repeat(4,1fr);gap:.625rem;margin-bottom:.875rem}.nv-g4{grid-template-columns:repeat(2,1fr)}.nv-g3p{grid-template-columns:1fr 1fr 1fr}.nv-g3p>.nv-fg:last-child{grid-column:auto}}
</style>

<!-- Dekorasi background -->
<div class="nv-bgd">
    <div class="nv-ds nv-d1">📝</div><div class="nv-ds nv-d2">📊</div>
    <div class="nv-ds nv-d3">🏆</div><div class="nv-ds nv-d4">📈</div>
    <div class="nv-ds nv-d5">🎯</div>
</div>

<div class="main">
<div class="wrap fade-up">

<!-- HERO -->
<div class="nv-hero">
    <div class="nv-hb nv-hb1"></div><div class="nv-hb nv-hb2"></div><div class="nv-hb nv-hb3"></div>
    <div class="nv-hcon">
        <div>
            <div class="nv-hey">📝 &nbsp;Sistem Penilaian</div>
            <h1 class="nv-htit">Kelola <span>Nilai Siswa</span><br>dengan akurat!</h1>
            <p class="nv-hdesc">Tugas, UTS, UAS — semua tercatat rapi &amp; nilai akhir otomatis dihitung 🎯</p>
        </div>
        <div class="nv-hright">
            <img src="assets/sekolah.png" alt="Logo" class="nv-illo">
            <div>
                <div class="nv-hchip"><div class="nv-hcnum"><?=$totalRow?></div><div class="nv-hclbl">Total Nilai</div></div>
                <div class="nv-hchip" style="margin-top:.5rem"><div class="nv-hcnum"><?=$rataKelas?></div><div class="nv-hclbl">Rata-rata</div></div>
            </div>
        </div>
    </div>
</div>

<!-- STAT CARDS -->
<div class="nv-stats">
    <div class="nv-sc"><div class="nv-sorb r">📝</div><div><div class="nv-sval"><?=$totalRow?></div><div class="nv-slbl">Total Data</div></div></div>
    <div class="nv-sc"><div class="nv-sorb p">📈</div><div><div class="nv-sval"><?=$rataKelas?></div><div class="nv-slbl">Rata-rata</div></div></div>
    <div class="nv-sc"><div class="nv-sorb g">✅</div><div><div class="nv-sval" style="color:#065F46"><?=$lulus?></div><div class="nv-slbl">Lulus KKM</div></div></div>
    <div class="nv-sc"><div class="nv-sorb a">⚠️</div><div><div class="nv-sval" style="color:#92400E"><?=$tidakLulus?></div><div class="nv-slbl">Perlu Remedi</div></div></div>
</div>

<!-- ALERTS -->
<?php if ($msg): ?>
<div class="nv-alert <?=$mtype==='ok'?'nv-aok':($mtype==='del'?'nv-adel':'nv-aerr')?>" id="nv-alertBox">
    <span class="nv-aico"><?=$mtype==='ok'?'✅':($mtype==='del'?'🗑️':'❌')?></span>
    <div><?=htmlspecialchars($msg)?></div>
</div>
<?php endif; ?>

<?php if ($mtype === 'err' && $debugSQL): ?>
<div class="nv-dbg">
    <strong>🔍 SQL Query:</strong><br><?=htmlspecialchars($debugSQL)?><br><br>
    <strong>Kolom "nilai":</strong><br><?=htmlspecialchars(implode(', ', $nKol))?><br>
    <strong>nilai_akhir:</strong> <?=$hNA?'✔':'✘'?> &nbsp;<strong>predikat:</strong> <?=$hPred?'✔':'✘'?> &nbsp;<strong>semester:</strong> <?=$hSmt?'✔':'✘'?> &nbsp;<strong>tahun_ajaran:</strong> <?=$hThn?'✔':'✘'?>
</div>
<?php endif; ?>

<?php if ($editData): ?>
<div class="nv-alert nv-aedt">
    <span class="nv-aico">✏️</span>
    <div><strong>Mode Edit Aktif</strong>&nbsp;<a href="nilai.php" style="color:inherit;font-weight:900;text-decoration:underline">✖ Batal Edit</a></div>
</div>
<?php endif; ?>

<!-- FILTER -->
<div class="nv-card">
<div class="nv-chd"><div class="nv-chdl"><div class="nv-cbdg fi">🔍</div>
    <div><div class="nv-ctit">Filter Data Nilai</div><div class="nv-csub">Saring berdasarkan kelas, mapel, semester, atau tahun</div></div>
</div></div>
<div class="nv-cbdy">
<form method="GET" action="nilai.php">
<div class="nv-g5">
    <?php if ($hKls && count($kelasRows) > 0): ?>
    <div class="nv-fg"><label class="nv-flbl">🏫 Kelas</label>
    <select name="kelas" class="nv-fs"><option value="">Semua Kelas</option>
    <?php foreach ($kelasRows as $k): ?>
    <option value="<?=htmlspecialchars($k['kelas'])?>" <?=$fkelas===$k['kelas']?'selected':''?>><?=htmlspecialchars($k['kelas'])?></option>
    <?php endforeach; ?></select></div>
    <?php endif; ?>

    <div class="nv-fg"><label class="nv-flbl">📚 Mata Pelajaran</label>
    <select name="mapel" class="nv-fs"><option value="">Semua Mapel</option>
    <?php foreach ($mapelRows as $m): ?>
    <option value="<?=$m['id']?>" <?=$fmapel==$m['id']?'selected':''?>><?=htmlspecialchars($m['nama_mapel'])?></option>
    <?php endforeach; ?></select></div>

    <?php if ($hSmt): ?>
    <div class="nv-fg"><label class="nv-flbl">📅 Semester</label>
    <select name="semester" class="nv-fs">
    <option value="">Semua</option>
    <option value="1" <?=$fsem===1?'selected':''?>>1 — Ganjil</option>
    <option value="2" <?=$fsem===2?'selected':''?>>2 — Genap</option>
    </select></div>
    <?php endif; ?>

    <?php if ($hThn): ?>
    <div class="nv-fg"><label class="nv-flbl">🗓️ Tahun Ajaran</label>
    <select name="tahun" class="nv-fs">
        <option value="">Semua Tahun</option>
        <?php foreach ($tahunList as $tahun): ?>
        <option value="<?=htmlspecialchars($tahun)?>" <?=$ftahun===$tahun?'selected':''?>><?=htmlspecialchars($tahun)?></option>
        <?php endforeach; ?>
        <option value="<?=date('Y').'/'.(date('Y')+1)?>" <?=$ftahun===(date('Y').'/'.(date('Y')+1))?'selected':''?>><?=date('Y').'/'.(date('Y')+1)?> (Tahun Ini)</option>
    </select></div>
    <?php endif; ?>

    <div class="nv-fg" style="flex-direction:row;gap:.5rem;align-items:flex-end">
        <button type="submit" class="nv-bsub fi" style="flex:1;justify-content:center;padding:.78rem 1rem">🔍 Filter</button>
        <a href="nilai.php" class="nv-breset" title="Reset">✕</a>
    </div>
</div>
</form>
</div>
</div>

<!-- FORM INPUT / EDIT -->
<div class="nv-card <?=$editData?'nv-em':''?>" id="nv-fcard">
<div class="nv-chd">
    <div class="nv-chdl">
        <div class="nv-cbdg <?=$editData?'am':'r'?>"><?=$editData?'✏️':'➕'?></div>
        <div>
            <div class="nv-ctit"><?=$editData?'Edit Data Nilai':'Input Nilai Baru'?></div>
            <div class="nv-csub"><?=$editData?'Perbarui nilai siswa':'Isi formulir untuk menambah nilai'?></div>
        </div>
    </div>
    <?php if ($editData): ?><a href="nilai.php" class="nv-bcan">✖ Batal Edit</a><?php endif; ?>
</div>
<div class="nv-cbdy">
<form method="POST" action="nilai.php" id="nv-formNilai">
<?php if ($editData): ?><input type="hidden" name="id" value="<?=intval($editData['id'])?>"> <?php endif; ?>

<!-- Baris 1: Siswa, Mapel, Semester, Tahun -->
<div class="nv-g4" style="margin-bottom:1.125rem">
    <div class="nv-fg"><label class="nv-flbl">👨‍🎓 Siswa <span class="nv-req">*</span></label>
    <select name="siswa_id" class="nv-fs" required>
        <option value="">— Pilih Siswa —</option>
        <?php foreach ($siswaRows as $s):
            $nim = ($s['nisn'] ?? '') ?: ($s['nis'] ?? '');
            $lbl = ($nim ? $nim . ' · ' : '') . $s['nama'] . ($hKls && !empty($s['kelas']) ? '  (' . $s['kelas'] . ')' : '');
        ?>
        <option value="<?=$s['id']?>" <?=($editData && $editData['siswa_id']==$s['id'])?'selected':''?>><?=htmlspecialchars($lbl)?></option>
        <?php endforeach; ?>
    </select></div>

    <div class="nv-fg"><label class="nv-flbl">📚 Mata Pelajaran <span class="nv-req">*</span></label>
    <select name="mapel_id" class="nv-fs" id="nv-selMapel" required onchange="nvUpdKKM()">
        <option value="">— Pilih Mapel —</option>
        <?php foreach ($mapelRows as $m):
            $mkkm = $hKKM ? intval($m['kkm']) : 0;
        ?>
        <option value="<?=$m['id']?>" data-kkm="<?=$mkkm?>" <?=($editData && $editData['mapel_id']==$m['id'])?'selected':''?>>
            <?=htmlspecialchars($m['nama_mapel'])?><?=$hKKM ? " — KKM $mkkm" : ''?>
        </option>
        <?php endforeach; ?>
    </select></div>

    <?php if ($hSmt): ?>
    <div class="nv-fg"><label class="nv-flbl">📅 Semester <span class="nv-req">*</span></label>
    <select name="semester" class="nv-fs" required>
        <option value="">— Pilih —</option>
        <option value="1" <?=($editData && $editData['semester']=='1')?'selected':''?>>1 — Ganjil</option>
        <option value="2" <?=($editData && $editData['semester']=='2')?'selected':''?>>2 — Genap</option>
    </select></div>
    <?php else: ?><input type="hidden" name="semester" value="1"><?php endif; ?>

    <?php if ($hThn): ?>
    <div class="nv-fg"><label class="nv-flbl">🗓️ Tahun Ajaran <span class="nv-req">*</span></label>
    <input type="text" name="tahun_ajaran" class="nv-fi" required placeholder="2025/2026"
        value="<?=htmlspecialchars($editData ? ($editData['tahun_ajaran'] ?? '') : date('Y') . '/' . (date('Y') + 1))?>">
    </div>
    <?php else: ?>
    <input type="hidden" name="tahun_ajaran" value="<?=date('Y').'/'.(date('Y')+1)?>">
    <?php endif; ?>
</div>

<hr class="nv-fdiv">

<!-- Baris 2: Nilai + Live Preview -->
<div class="nv-g3p">
    <div class="nv-fg"><label class="nv-flbl">📝 Nilai Tugas <span class="nv-req">*</span></label>
    <input type="number" name="nilai_tugas" id="nv-nt" class="nv-fi mn"
        placeholder="0 – 100" min="0" max="100" step="0.01" required
        value="<?=$editData ? htmlspecialchars($editData['nilai_tugas']) : ''?>" oninput="nvPrvN()"></div>

    <div class="nv-fg"><label class="nv-flbl">📄 Nilai UTS <span class="nv-req">*</span></label>
    <input type="number" name="nilai_uts" id="nv-nuts" class="nv-fi mn"
        placeholder="0 – 100" min="0" max="100" step="0.01" required
        value="<?=$editData ? htmlspecialchars($editData['nilai_uts']) : ''?>" oninput="nvPrvN()"></div>

    <div class="nv-fg"><label class="nv-flbl">📋 Nilai UAS <span class="nv-req">*</span></label>
    <input type="number" name="nilai_uas" id="nv-nuas" class="nv-fi mn"
        placeholder="0 – 100" min="0" max="100" step="0.01" required
        value="<?=$editData ? htmlspecialchars($editData['nilai_uas']) : ''?>" oninput="nvPrvN()"></div>

    <div class="nv-fg"><label class="nv-flbl">🏆 Nilai Akhir</label>
    <div class="nv-prev" id="nv-prevBox">
        <div class="nv-prev-num" id="nv-prevNum">—</div>
        <div class="nv-prev-lbl">Otomatis dihitung</div>
        <div class="nv-prev-pred" id="nv-prevPred"></div>
    </div></div>
</div>

<!-- KKM info -->
<div class="nv-kstrip" id="nv-kstrip">
    📌 KKM mapel ini: <span class="nv-kbdg" id="nv-kval">—</span>
    <span id="nv-kstat" style="font-weight:900"></span>
</div>

<div class="nv-fact">
    <button type="submit" name="<?=$editData?'update':'simpan'?>" value="1"
        class="nv-bsub <?=$editData?'up':'sv'?>">
        <?=$editData?'🔄 Update Nilai':'💾 Simpan Nilai'?>
    </button>
    <?php if ($editData): ?><a href="nilai.php" class="nv-bcan">✖ Batal</a><?php endif; ?>
</div>
</form>
</div>
</div>

<!-- TABLE -->
<div class="nv-card">
<div class="nv-ttop">
    <div class="nv-ttl">
        <img src="assets/sekolah.png" alt="Logo" style="width:44px;height:44px;object-fit:contain">
        Daftar Nilai Siswa
        <span class="nv-tcnt"><?=$totalRow?> data</span>
    </div>
    <div class="nv-sw"><input type="text" class="nv-si" id="nv-si" placeholder="Cari nama / mapel…" onkeyup="nvSrch()"></div>
</div>
<div class="nv-tscr">
<?php if ($totalRow > 0): ?>
<table id="nv-tbl">
<thead><tr>
    <th>No</th><th>Siswa</th>
    <?php if ($hKls): ?><th>Kelas</th><?php endif; ?>
    <th>Mata Pelajaran</th>
    <?php if ($hSmt): ?><th>Smt</th><?php endif; ?>
    <?php if ($hThn): ?><th>Tahun</th><?php endif; ?>
    <th class="ctr">Tugas</th><th class="ctr">UTS</th><th class="ctr">UAS</th>
    <?php if ($hNA): ?><th>Akhir</th><?php endif; ?>
    <?php if ($hPred): ?><th>Pred</th><?php endif; ?>
    <?php if ($hKKM): ?><th>KKM</th><?php endif; ?>
    <?php if ($hNA && $hKKM): ?><th>Status</th><?php endif; ?>
    <th>Aksi</th>
</tr></thead>
<tbody>
<?php $no = 1; foreach ($dataRows as $d):
    $naD  = $hNA ? floatval($d['nilai_akhir']) : round((floatval($d['nilai_tugas']) + floatval($d['nilai_uts']) + floatval($d['nilai_uas'])) / 3, 1);
    $pred = $hPred ? ($d['predikat'] ?? hitungPred($naD)) : hitungPred($naD);
    $kkm  = $hKKM ? floatval($d['kkm']) : 0;
    $lls  = $kkm > 0 ? ($naD >= $kkm) : true;
    $scls = (isset($d['semester']) && intval($d['semester']) == 2) ? 'nv-bsem2' : 'nv-bsem1';
    $nbc  = ['A'=>'nv-nA','B'=>'nv-nB','C'=>'nv-nC','D'=>'nv-nD','E'=>'nv-nE'][$pred] ?? 'nv-nC';
?>
<tr>
    <td class="nv-tno"><?=$no++?></td>
    <td class="nv-tnm"><strong><?=htmlspecialchars($d['nama_siswa'])?></strong>
    <?php $nim = ($d['nisn'] ?? '') ?: ($d['nis'] ?? ''); if ($nim): ?><small><?=htmlspecialchars($nim)?></small><?php endif; ?></td>
    <?php if ($hKls): ?><td><?=htmlspecialchars($d['kelas'] ?? '—')?></td><?php endif; ?>
    <td style="font-weight:700"><?=htmlspecialchars($d['nama_mapel'])?></td>
    <?php if ($hSmt): ?><td><span class="nv-badge <?=$scls?>"><span class="nv-bdot"></span><?=semTxt($d['semester'] ?? 1)?></span></td><?php endif; ?>
    <?php if ($hThn): ?><td style="font-family:'Space Mono',monospace;font-size:.76rem;font-weight:700;color:var(--nv-txd)"><?=htmlspecialchars($d['tahun_ajaran'] ?? '')?></td><?php endif; ?>
    <td class="nv-tval ctr"><?=number_format(floatval($d['nilai_tugas']), 1)?></td>
    <td class="nv-tval ctr"><?=number_format(floatval($d['nilai_uts']), 1)?></td>
    <td class="nv-tval ctr"><?=number_format(floatval($d['nilai_uas']), 1)?></td>
    <?php if ($hNA): ?><td><div class="nv-tnaw"><span class="nv-tnan"><?=number_format($naD, 1)?></span><div class="nv-tnab"><div class="nv-tnaf <?=$nbc?>" style="width:<?=min(100, $naD)?>%"></div></div></div></td><?php endif; ?>
    <?php if ($hPred): ?><td><span class="nv-badge nv-b<?=$pred?>"><span class="nv-bdot"></span><?=htmlspecialchars($pred)?></span></td><?php endif; ?>
    <?php if ($hKKM): ?><td><span class="nv-kchip"><?=$kkm?></span></td><?php endif; ?>
    <?php if ($hNA && $hKKM): ?><td><span class="nv-badge <?=$lls?'nv-blls':'nv-brmdi'?>"><?=$lls?'✓ Lulus':'✗ Remedi'?></span></td><?php endif; ?>
    <td><div class="nv-acts">
        <a href="?edit=<?=$d['id']?>" class="nv-ab nv-abedt">✏️ Edit</a>
        <button class="nv-ab nv-abdl" onclick="nvHapus(<?=$d['id']?>,'<?=htmlspecialchars(addslashes($d['nama_siswa']), ENT_QUOTES)?>')">🗑️</button>
    </div></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<div class="nv-empty">
    <div class="nv-emillo">📭</div>
    <div class="nv-emtit">Belum ada data nilai!</div>
    <div class="nv-emsub">Tambahkan nilai siswa menggunakan form di atas 👆</div>
</div>
<?php endif; ?>
</div>
</div>

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

<script>
/* ── Nilai preview ── */
const nvPC={'A':'#065F46','B':'#1E40AF','C':'#92400E','D':'#9A3412','E':'#991B1B'};
const nvPB={'A':'#D1FAE5','B':'#DBEAFE','C':'#FEF3C7','D':'#FFEDD5','E':'#FEE2E2'};
const nvPD={'A':'#6EE7B7','B':'#93C5FD','C':'#FCD34D','D':'#FDBA74','E':'#FCA5A5'};
function nvGP(n){return n>=90?'A':n>=80?'B':n>=70?'C':n>=60?'D':'E';}
let nvCurKKM = 0;

function nvPrvN(){
    const nt  = parseFloat(document.getElementById('nv-nt').value)   || 0;
    const nu  = parseFloat(document.getElementById('nv-nuts').value)  || 0;
    const na2 = parseFloat(document.getElementById('nv-nuas').value)  || 0;
    const hv  = document.getElementById('nv-nt').value !== '' ||
                document.getElementById('nv-nuts').value !== '' ||
                document.getElementById('nv-nuas').value !== '';
    const na  = Math.round((nt + nu + na2) / 3 * 100) / 100;
    const p   = nvGP(na);
    const bx  = document.getElementById('nv-prevBox');
    const nm  = document.getElementById('nv-prevNum');
    const pe  = document.getElementById('nv-prevPred');
    if (hv) {
        nm.textContent = na.toFixed(1); nm.style.color = nvPC[p];
        pe.textContent = p; pe.style.display = 'inline-block';
        pe.style.background = nvPB[p]; pe.style.color = nvPC[p]; pe.style.borderColor = nvPD[p];
        bx.style.borderColor = nvPD[p];
    } else {
        nm.textContent = '—'; nm.style.color = ''; pe.style.display = 'none'; bx.style.borderColor = '';
    }
    if (nvCurKKM && hv) {
        const st = document.getElementById('nv-kstat');
        const ok = na >= nvCurKKM;
        st.textContent = ok ? '✓ Lulus KKM 🎉' : '✗ Perlu Remediasi';
        st.style.color = ok ? '#065F46' : '#991B1B';
    }
}

function nvUpdKKM(){
    const sel = document.getElementById('nv-selMapel');
    const opt = sel.options[sel.selectedIndex];
    const kkm = opt ? parseInt(opt.dataset.kkm || 0) : 0;
    nvCurKKM  = kkm;
    const ks  = document.getElementById('nv-kstrip');
    if (kkm) { document.getElementById('nv-kval').textContent = kkm; ks.style.display = 'flex'; nvPrvN(); }
    else { ks.style.display = 'none'; }
}

window.addEventListener('DOMContentLoaded', () => { nvPrvN(); nvUpdKKM(); });

/* ── Search ── */
function nvSrch(){
    const q = document.getElementById('nv-si').value.toLowerCase();
    document.querySelectorAll('#nv-tbl tbody tr').forEach(r => {
        r.style.display = r.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
}

/* ── Hapus ── */
function nvHapus(id, nama){
    if (confirm('🗑️ Hapus nilai milik "' + nama + '"?\n\nData tidak dapat dikembalikan!'))
        location.href = 'nilai.php?hapus=' + id;
}

<?php if ($editData || $mtype === 'err'): ?>
document.getElementById('nv-fcard').scrollIntoView({behavior:'smooth', block:'start'});
<?php endif; ?>

<?php if ($mtype === 'ok' || $mtype === 'del'): ?>
const nvAlertBox = document.getElementById('nv-alertBox');
if (nvAlertBox) setTimeout(() => {
    nvAlertBox.style.transition = 'opacity .5s, transform .5s';
    nvAlertBox.style.opacity = '0';
    nvAlertBox.style.transform = 'translateY(-12px)';
    setTimeout(() => nvAlertBox.remove(), 500);
}, 5000);
<?php endif; ?>

/* ── Validasi form ── */
document.getElementById('nv-formNilai').addEventListener('submit', function(e){
    const siswa = document.querySelector('select[name="siswa_id"]').value;
    const mapel = document.querySelector('select[name="mapel_id"]').value;
    if (!siswa || !mapel) { e.preventDefault(); alert('❌ Harap pilih Siswa dan Mata Pelajaran!'); return false; }
    const nt  = parseFloat(document.getElementById('nv-nt').value);
    const nu  = parseFloat(document.getElementById('nv-nuts').value);
    const na  = parseFloat(document.getElementById('nv-nuas').value);
    if (nt<0||nt>100||nu<0||nu>100||na<0||na>100) { e.preventDefault(); alert('❌ Nilai harus antara 0-100!'); return false; }
    return true;
});
</script>