<?php
/* ══════════════════════════════════════════════════════
   mata_pelajaran.php — Manajemen Mata Pelajaran
   MA As-Syafi'iyah 02 Bekasi
   FIX: Semua proses POST/GET SEBELUM include navbar
        agar header() redirect tidak gagal
══════════════════════════════════════════════════════ */

// Buffer output — pengaman agar header() selalu bisa dipanggil
ob_start();

// Tampilkan error (nonaktifkan di production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ── Include 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>");
    }
}

// Daftar kategori valid
$validKat = ['Wajib','Pilihan','Muatan Lokal','Ekstrakurikuler','Lintas Minat','Peminatan'];

// Helper escape
function mpEsc($conn, $v) {
    return mysqli_real_escape_string($conn, trim((string)$v));
}

// Cek apakah kolom created_at ada
$cekKolom     = mysqli_query($conn, "SHOW COLUMNS FROM mata_pelajaran LIKE 'created_at'");
$adaCreatedAt = ($cekKolom && mysqli_num_rows($cekKolom) > 0);

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

// ── SIMPAN ──
if (isset($_POST['simpan'])) {
    $kode = mpEsc($conn, $_POST['kode_mapel'] ?? '');
    $nama = mpEsc($conn, $_POST['nama_mapel'] ?? '');
    $kat  = mpEsc($conn, $_POST['kategori']   ?? '');
    $kkm  = mpEsc($conn, $_POST['kkm']        ?? '');

    if ($kode==='' || $nama==='' || $kat==='' || $kkm==='') {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=empty"); exit();
    }
    if (!is_numeric($kkm) || (int)$kkm < 0 || (int)$kkm > 100) {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=kkm"); exit();
    }
    if (!in_array($_POST['kategori'] ?? '', $validKat)) {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=empty"); exit();
    }

    $kkmInt = (int)$kkm;

    $resCek = mysqli_query($conn, "SELECT id FROM mata_pelajaran WHERE kode_mapel='$kode' LIMIT 1");
    if ($resCek && mysqli_num_rows($resCek) > 0) {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=dupkode"); exit();
    }

    $sql = $adaCreatedAt
        ? "INSERT INTO mata_pelajaran (kode_mapel,nama_mapel,kategori,kkm,created_at) VALUES ('$kode','$nama','$kat',$kkmInt,NOW())"
        : "INSERT INTO mata_pelajaran (kode_mapel,nama_mapel,kategori,kkm) VALUES ('$kode','$nama','$kat',$kkmInt)";

    if (mysqli_query($conn, $sql)) {
        ob_end_clean(); header("Location: mata_pelajaran.php?success=simpan"); exit();
    } else {
        $msg = urlencode(mysqli_error($conn));
        ob_end_clean(); header("Location: mata_pelajaran.php?error=failed&msg=$msg"); exit();
    }
}

// ── UPDATE ──
if (isset($_POST['update'])) {
    $id   = (int)($_POST['id'] ?? 0);
    $kode = mpEsc($conn, $_POST['kode_mapel'] ?? '');
    $nama = mpEsc($conn, $_POST['nama_mapel'] ?? '');
    $kat  = mpEsc($conn, $_POST['kategori']   ?? '');
    $kkm  = mpEsc($conn, $_POST['kkm']        ?? '');

    if (!$id || $kode==='' || $nama==='' || $kat==='' || $kkm==='') {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=empty&edit=$id"); exit();
    }
    if (!is_numeric($kkm) || (int)$kkm < 0 || (int)$kkm > 100) {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=kkm&edit=$id"); exit();
    }

    $kkmInt = (int)$kkm;
    $resCek = mysqli_query($conn, "SELECT id FROM mata_pelajaran WHERE kode_mapel='$kode' AND id!=$id LIMIT 1");
    if ($resCek && mysqli_num_rows($resCek) > 0) {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=dupkode&edit=$id"); exit();
    }

    $sql = "UPDATE mata_pelajaran SET kode_mapel='$kode',nama_mapel='$nama',kategori='$kat',kkm=$kkmInt WHERE id=$id";
    if (mysqli_query($conn, $sql)) {
        ob_end_clean(); header("Location: mata_pelajaran.php?success=update"); exit();
    } else {
        $msg = urlencode(mysqli_error($conn));
        ob_end_clean(); header("Location: mata_pelajaran.php?error=failed&edit=$id&msg=$msg"); exit();
    }
}

// ── HAPUS ──
if (isset($_GET['hapus'])) {
    $id = (int)$_GET['hapus'];
    if ($id > 0 && mysqli_query($conn, "DELETE FROM mata_pelajaran WHERE id=$id")) {
        ob_end_clean(); header("Location: mata_pelajaran.php?success=hapus"); exit();
    } else {
        ob_end_clean(); header("Location: mata_pelajaran.php?error=failed"); exit();
    }
}

// ── AMBIL DATA EDIT ──
$editData = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    if ($id > 0) {
        $res = mysqli_query($conn, "SELECT * FROM mata_pelajaran WHERE id=$id LIMIT 1");
        if ($res) $editData = mysqli_fetch_assoc($res);
    }
}

// ── FILTER & DAFTAR ──
$fk = trim($_GET['kategori'] ?? '');
if (!in_array($fk, $validKat)) $fk = '';

if ($fk !== '') {
    $fkEsc   = mpEsc($conn, $fk);
    $resData = mysqli_query($conn, "SELECT * FROM mata_pelajaran WHERE kategori='$fkEsc' ORDER BY nama_mapel");
} else {
    $resData = mysqli_query($conn, "SELECT * FROM mata_pelajaran ORDER BY kategori, nama_mapel");
}

$rows = [];
if ($resData) {
    while ($r = mysqli_fetch_assoc($resData)) $rows[] = $r;
}
$rowCount = count($rows);

// ── STATISTIK ──
function mpCount($conn, $where = '') {
    $r = mysqli_query($conn, "SELECT COUNT(*) AS t FROM mata_pelajaran" . ($where ? " WHERE $where" : ""));
    return $r ? (int)(mysqli_fetch_assoc($r)['t'] ?? 0) : 0;
}
$total   = mpCount($conn);
$wajib   = mpCount($conn, "kategori='Wajib'");
$pilihan = mpCount($conn, "kategori='Pilihan'");
$mulok   = mpCount($conn, "kategori='Muatan Lokal'");
$ekskul  = mpCount($conn, "kategori='Ekstrakurikuler'");

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

// Setelah navbar, flush buffer ke browser
ob_end_flush();
?>

<style>
:root{--mp-rose:#F43F5E;--mp-rose-dark:#BE123C;--mp-rose-light:#FFE4E6;--mp-rose-pale:#FFF1F2;--mp-pink:#EC4899;--mp-pink-light:#FCE7F3;--mp-violet:#7C3AED;--mp-sky:#38BDF8;--mp-mint:#34D399;--mp-mint-dark:#059669;--mp-amber:#FBBF24;--mp-amber-dark:#D97706;--mp-purple:#A78BFA;--mp-border:#FECDD3;--mp-border-l:#FFE4E6;--mp-shadow:rgba(244,63,94,.1);--mp-shadow-s:rgba(244,63,94,.2)}
.main .wrap{font-family:'Outfit',sans-serif}
.mp-bg-deco{position:fixed;inset:0;pointer-events:none;z-index:0;overflow:hidden}
.mp-ds{position:absolute;opacity:.04;font-size:72px;user-select:none;line-height:1}
.mp-ds1{top:7%;left:3%;animation:mpf1 22s ease-in-out infinite}
.mp-ds2{top:60%;right:5%;font-size:96px;animation:mpf2 18s ease-in-out infinite 2s}
.mp-ds3{bottom:10%;left:12%;font-size:60px;animation:mpf3 20s ease-in-out infinite 4s}
.mp-ds4{top:28%;right:22%;font-size:80px;animation:mpf1 25s ease-in-out infinite 1s}
.mp-ds5{bottom:40%;left:44%;font-size:56px;animation:mpf2 16s ease-in-out infinite 3s}
@keyframes mpf1{0%,100%{transform:translate(0,0) rotate(0)}50%{transform:translate(22px,-28px) rotate(12deg)}}
@keyframes mpf2{0%,100%{transform:translate(0,0) rotate(0)}50%{transform:translate(-16px,24px) rotate(-10deg)}}
@keyframes mpf3{0%,100%{transform:translate(0,0) rotate(0)}33%{transform:translate(26px,-18px) rotate(9deg)}66%{transform:translate(-10px,14px) rotate(-6deg)}}
@keyframes mpFadeUp{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
@keyframes mpSlideDown{from{opacity:0;transform:translateY(-14px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}
@keyframes mpIllo{0%,100%{transform:rotate(-4deg) scale(1)}50%{transform:rotate(4deg) scale(1.06)}}
@keyframes mpBounce{0%,100%{transform:translateY(0)}50%{transform:translateY(-12px)}}
@keyframes mpCharF{0%,100%{transform:translateY(0) rotate(-5deg)}50%{transform:translateY(-12px) rotate(5deg)}}
.mp-hero{background:linear-gradient(135deg,#F43F5E 0%,#EC4899 55%,#A78BFA 100%);border-radius:22px;margin-bottom:1.5rem;position:relative;overflow:hidden;box-shadow:0 10px 40px rgba(244,63,94,.28);animation:mpFadeUp .55s ease-out}
.mp-hblobs{position:absolute;inset:0;pointer-events:none;z-index:0}
.mp-hb{position:absolute;border-radius:50%;background:white;opacity:.1}
.mp-hb1{width:260px;height:260px;top:-80px;right:10px;animation:mpf1 9s ease-in-out infinite}
.mp-hb2{width:150px;height:150px;bottom:-50px;right:260px;animation:mpf2 7s ease-in-out infinite}
.mp-hb3{width:90px;height:90px;top:20px;right:380px;border-radius:22px;opacity:.14;animation:mpf3 8s ease-in-out infinite}
.mp-hb4{width:50px;height:50px;bottom:14px;left:32px;opacity:.18;animation:mpf2 5s ease-in-out infinite 1.5s}
.mp-hero-body{position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;gap:1.5rem;padding:2rem 2.5rem;flex-wrap:wrap}
.mp-hero-left{flex:1;min-width:0}
.mp-eyebrow{display:inline-flex;align-items:center;gap:.4rem;background:rgba(255,255,255,.2);backdrop-filter:blur(8px);border:1.5px solid rgba(255,255,255,.3);border-radius:50px;padding:.3rem .9rem;font-size:.7rem;font-weight:700;color:white;letter-spacing:.06em;text-transform:uppercase;margin-bottom:.875rem}
.mp-hero-row{display:flex;align-items:flex-start;gap:.875rem;margin-bottom:.625rem}
.mp-hero-char{font-size:3.5rem;line-height:1;flex-shrink:0;filter:drop-shadow(0 4px 16px rgba(0,0,0,.2));animation:mpCharF 3.5s ease-in-out infinite}
.mp-hero-char img{width:72px;height:72px;object-fit:contain}
.mp-title{font-size:1.875rem;font-weight:900;color:white;line-height:1.15;letter-spacing:-.02em;margin:0}
.mp-title .acc{background:linear-gradient(90deg,#FEF9C3,#FDE68A,#FCA5A5);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.mp-sub{font-size:.875rem;color:rgba(255,255,255,.88);font-weight:600;margin-top:.375rem}
.mp-hero-right{display:flex;align-items:center;gap:1rem;flex-shrink:0}
.mp-illo{font-size:5.5rem;line-height:1;filter:drop-shadow(0 8px 24px rgba(0,0,0,.2));animation:mpIllo 4s ease-in-out infinite}
.mp-chips{display:flex;flex-direction:column;gap:.625rem}
.mp-chip{background:rgba(255,255,255,.18);backdrop-filter:blur(10px);border:1.5px solid rgba(255,255,255,.28);border-radius:13px;padding:.7rem 1.125rem;display:flex;align-items:center;gap:.75rem;min-width:130px}
.mp-chip-num{font-size:1.875rem;font-weight:900;color:white;line-height:1;font-family:'DM Mono',monospace}
.mp-chip-lbl{font-size:.62rem;font-weight:700;color:rgba(255,255,255,.78);text-transform:uppercase;letter-spacing:.05em;margin-top:2px}
.mp-chip-ico{font-size:1.25rem}
.mp-alert{display:flex;align-items:flex-start;gap:.75rem;padding:.875rem 1.25rem;border-radius:12px;margin-bottom:1.25rem;font-weight:700;font-size:.875rem;animation:mpSlideDown .4s cubic-bezier(.34,1.56,.64,1);border-left:4px solid;flex-direction:column}
.mp-alert-row{display:flex;align-items:center;gap:.75rem}
.mp-alert-ico{font-size:1.25rem;flex-shrink:0}
.mp-alert-ok{background:#DCFCE7;color:#166534;border-color:#4ADE80}
.mp-alert-err{background:var(--mp-rose-light);color:var(--mp-rose-dark);border-color:#FECDD3}
.mp-alert-edt{background:#FEF3C7;color:#92400E;border-color:#FDE68A}
.mp-err-detail{background:#FEF2F2;border:1.5px solid #FECDD3;border-radius:8px;padding:.6rem .875rem;font-size:.72rem;font-family:'DM Mono',monospace;color:#BE123C;word-break:break-all;width:100%;box-sizing:border-box}
.mp-stats{display:grid;grid-template-columns:repeat(5,1fr);gap:.875rem;margin-bottom:1.5rem}
.mp-sc{background:var(--sf);border-radius:18px;border:1.5px solid var(--mp-border-l);padding:1.25rem 1.125rem;box-shadow:0 3px 16px var(--mp-shadow);position:relative;overflow:hidden;transition:all .28s cubic-bezier(.34,1.56,.64,1);animation:mpFadeUp .5s ease-out backwards}
.mp-sc::after{content:'';position:absolute;top:0;left:0;right:0;height:3.5px;border-radius:18px 18px 0 0}
.mp-sc-all::after{background:linear-gradient(90deg,var(--mp-rose),var(--mp-pink))}
.mp-sc-wj::after{background:linear-gradient(90deg,var(--mp-mint),var(--mp-mint-dark))}
.mp-sc-pil::after{background:linear-gradient(90deg,var(--mp-sky),#0284C7)}
.mp-sc-mul::after{background:linear-gradient(90deg,var(--mp-amber),var(--mp-amber-dark))}
.mp-sc-eks::after{background:linear-gradient(90deg,var(--mp-purple),var(--mp-violet))}
.mp-sc:hover{transform:translateY(-5px);box-shadow:0 10px 28px var(--mp-shadow-s)}
.mp-sc:nth-child(1){animation-delay:.04s}.mp-sc:nth-child(2){animation-delay:.08s}.mp-sc:nth-child(3){animation-delay:.12s}.mp-sc:nth-child(4){animation-delay:.16s}.mp-sc:nth-child(5){animation-delay:.20s}
.mp-sc-top{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:.5rem}
.mp-sc-ico{width:40px;height:40px;border-radius:11px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:1.2rem;transition:transform .3s cubic-bezier(.34,1.56,.64,1)}
.mp-sc:hover .mp-sc-ico{transform:scale(1.16) rotate(-7deg)}
.mp-sc-all .mp-sc-ico{background:linear-gradient(135deg,#FFE4E6,#FECDD3)}
.mp-sc-wj  .mp-sc-ico{background:linear-gradient(135deg,#DCFCE7,#BBF7D0)}
.mp-sc-pil .mp-sc-ico{background:linear-gradient(135deg,#E0F2FE,#BAE6FD)}
.mp-sc-mul .mp-sc-ico{background:linear-gradient(135deg,#FEF3C7,#FDE68A)}
.mp-sc-eks .mp-sc-ico{background:linear-gradient(135deg,#EDE9FE,#DDD6FE)}
.mp-sc-lbl{font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--txl);margin-bottom:.2rem}
.mp-sc-num{font-size:1.875rem;font-weight:900;line-height:1;font-family:'DM Mono',monospace}
.mp-sc-all .mp-sc-num{color:var(--mp-rose)}.mp-sc-wj .mp-sc-num{color:var(--mp-mint-dark)}.mp-sc-pil .mp-sc-num{color:#0284C7}.mp-sc-mul .mp-sc-num{color:var(--mp-amber-dark)}.mp-sc-eks .mp-sc-num{color:var(--mp-violet)}
.mp-card{background:var(--sf);border-radius:20px;border:1.5px solid var(--bd);box-shadow:0 3px 18px var(--sh);margin-bottom:1.375rem;overflow:hidden;animation:mpFadeUp .5s ease-out backwards}
.mp-card.edit-mode{border-color:var(--mp-amber);box-shadow:0 4px 28px rgba(251,191,36,.2)}
.mp-card-head{padding:1rem 1.375rem;display:flex;align-items:center;justify-content:space-between;gap:.75rem;border-bottom:1.5px solid var(--bd);flex-wrap:wrap}
.mp-card-head-l{display:flex;align-items:center;gap:.75rem}
.mp-ch-badge{width:38px;height:38px;min-width:38px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:1.1rem;flex-shrink:0}
.mp-ch-rose{background:var(--mp-rose-light)}.mp-ch-amber{background:#FEF3C7}.mp-ch-filter{background:var(--mp-pink-light)}
.mp-card-title{font-size:.95rem;font-weight:800;color:var(--tx)}.mp-card-sub{font-size:.72rem;color:var(--txl);font-weight:600;margin-top:1px}
.mp-card-body{padding:1.375rem}
.mp-filter-row{display:flex;align-items:flex-end;gap:.875rem;flex-wrap:wrap}
.mp-fg{display:flex;flex-direction:column;gap:.4rem;flex:1;min-width:180px}
.mp-fg label{font-size:.72rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:var(--txm);display:flex;align-items:center;gap:.3rem}
.mp-fs,.mp-fi{padding:.75rem .9rem;background:var(--bg);border:1.5px solid var(--bd);border-radius:11px;font-size:max(.875rem,16px);font-family:'Outfit',sans-serif;font-weight:600;color:var(--tx);transition:all .2s;outline:none;width:100%;-webkit-appearance:none}
.mp-fs:focus,.mp-fi:focus{border-color:var(--mp-rose);background:white;box-shadow:0 0 0 3px rgba(244,63,94,.1)}
.mp-btn-filter{display:inline-flex;align-items:center;gap:.5rem;padding:.75rem 1.375rem;border-radius:11px;border:none;background:linear-gradient(135deg,var(--mp-rose),var(--mp-pink));color:white;font-size:.875rem;font-weight:800;font-family:'Outfit',sans-serif;cursor:pointer;box-shadow:0 4px 14px rgba(244,63,94,.3);transition:all .25s cubic-bezier(.34,1.56,.64,1);text-decoration:none;white-space:nowrap}
.mp-btn-filter:hover{transform:translateY(-2px);box-shadow:0 8px 20px rgba(244,63,94,.4)}
.mp-btn-reset{display:inline-flex;align-items:center;gap:.4rem;padding:.75rem 1.125rem;border-radius:11px;border:1.5px solid var(--bd);background:var(--sf);color:var(--txm);font-size:.825rem;font-weight:700;font-family:'Outfit',sans-serif;cursor:pointer;transition:all .22s;text-decoration:none;white-space:nowrap}
.mp-btn-reset:hover{border-color:var(--mp-rose);color:var(--mp-rose-dark);background:var(--mp-rose-pale)}
.mp-form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:.875rem;margin-bottom:1.25rem}
.mp-form-actions{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}
.mp-btn-save{display:inline-flex;align-items:center;gap:.5rem;padding:.75rem 1.625rem;border-radius:11px;border:none;background:linear-gradient(135deg,var(--mp-rose),var(--mp-pink));color:white;font-size:.875rem;font-weight:800;font-family:'Outfit',sans-serif;cursor:pointer;box-shadow:0 4px 16px rgba(244,63,94,.32);transition:all .25s cubic-bezier(.34,1.56,.64,1)}
.mp-btn-save:hover{transform:translateY(-2px);box-shadow:0 8px 22px rgba(244,63,94,.42)}
.mp-btn-update{background:linear-gradient(135deg,var(--mp-amber),var(--mp-amber-dark));box-shadow:0 4px 16px rgba(251,191,36,.32)}
.mp-btn-update:hover{box-shadow:0 8px 22px rgba(251,191,36,.42)}
.mp-btn-cancel{display:inline-flex;align-items:center;gap:.4rem;padding:.75rem 1.25rem;border-radius:11px;border:1.5px solid var(--bd);background:var(--sf);color:var(--txm);font-size:.875rem;font-weight:700;font-family:'Outfit',sans-serif;cursor:pointer;transition:all .22s;text-decoration:none}
.mp-btn-cancel:hover{border-color:var(--mp-rose);color:var(--mp-rose-dark);background:var(--mp-rose-pale)}
.mp-tbl-topbar{padding:1rem 1.375rem;background:linear-gradient(135deg,var(--mp-rose),var(--mp-pink));display:flex;align-items:center;justify-content:space-between;gap:.875rem;flex-wrap:wrap}
.mp-tbl-title{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;color:white;font-size:.975rem;font-weight:800}
.mp-tbl-count{background:rgba(255,255,255,.2);border:1px solid rgba(255,255,255,.3);border-radius:50px;padding:.15rem .7rem;font-size:.72rem;font-weight:800;color:white}
.mp-srch-wrap{position:relative}
.mp-srch-wrap::before{content:'🔍';position:absolute;left:.75rem;top:50%;transform:translateY(-50%);font-size:.75rem;pointer-events:none}
.mp-srch{padding:.55rem .875rem .55rem 2.25rem;background:rgba(255,255,255,.2);backdrop-filter:blur(8px);border:1.5px solid rgba(255,255,255,.35);border-radius:50px;color:white;font-size:.825rem;font-family:'Outfit',sans-serif;font-weight:600;outline:none;width:210px;transition:all .2s}
.mp-srch::placeholder{color:rgba(255,255,255,.65)}.mp-srch:focus{background:rgba(255,255,255,.3);border-color:white}
.mp-tbl-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
.mp-tbl-scroll::-webkit-scrollbar{height:4px}.mp-tbl-scroll::-webkit-scrollbar-thumb{background:var(--mp-border);border-radius:4px}
.mp-tbl-scroll table{width:100%;border-collapse:collapse;min-width:680px}
.mp-tbl-scroll thead tr{background:var(--mp-rose-pale);border-bottom:2px solid var(--mp-border)}
.mp-tbl-scroll th{padding:.75rem 1rem;text-align:left;font-size:.67rem;font-weight:800;color:var(--mp-rose-dark);text-transform:uppercase;letter-spacing:.07em;white-space:nowrap}
.mp-tbl-scroll tbody tr{border-bottom:1.5px solid var(--mp-border-l);transition:background .15s}
.mp-tbl-scroll tbody tr:hover{background:var(--mp-rose-pale)}.mp-tbl-scroll tbody tr:last-child{border-bottom:none}
.mp-tbl-scroll td{padding:.875rem 1rem;font-size:.825rem;font-weight:600;color:var(--tx);vertical-align:middle}
.mp-td-num{font-family:'DM Mono',monospace;font-size:.72rem;color:var(--txl);width:36px}
.mp-td-kode{font-family:'DM Mono',monospace;font-size:.78rem;font-weight:700;background:var(--mp-rose-light);color:var(--mp-rose-dark);padding:.22rem .65rem;border-radius:6px;display:inline-block;border:1.5px solid #FECDD3}
.mp-badge{display:inline-flex;align-items:center;gap:.25rem;padding:.22rem .75rem;border-radius:50px;font-size:.68rem;font-weight:800;letter-spacing:.03em}
.mp-bdot{width:5px;height:5px;border-radius:50%;flex-shrink:0}
.mp-b-wajib{background:#DCFCE7;color:#166534;border:1.5px solid #BBF7D0}.mp-b-wajib .mp-bdot{background:var(--mp-mint)}
.mp-b-pilihan{background:#E0F2FE;color:#0284C7;border:1.5px solid #BAE6FD}.mp-b-pilihan .mp-bdot{background:var(--mp-sky)}
.mp-b-mulok{background:#FEF3C7;color:#92400E;border:1.5px solid #FDE68A}.mp-b-mulok .mp-bdot{background:var(--mp-amber)}
.mp-b-ekskul{background:#EDE9FE;color:#5B21B6;border:1.5px solid #DDD6FE}.mp-b-ekskul .mp-bdot{background:var(--mp-purple)}
.mp-kkm{display:inline-flex;align-items:center;gap:.25rem;font-family:'DM Mono',monospace;font-weight:700;font-size:.78rem;padding:.22rem .65rem;border-radius:50px}
.mp-kkm-h{background:#DCFCE7;color:#166534}.mp-kkm-m{background:#FEF3C7;color:#92400E}.mp-kkm-l{background:var(--mp-rose-light);color:var(--mp-rose-dark)}
.mp-acts{display:flex;gap:.375rem}
.mp-ab{display:inline-flex;align-items:center;gap:.28rem;padding:.38rem .75rem;border-radius:8px;font-size:.72rem;font-weight:800;font-family:'Outfit',sans-serif;text-decoration:none;border:none;cursor:pointer;transition:all .2s cubic-bezier(.34,1.56,.64,1)}
.mp-ab:hover{transform:translateY(-2px)}.mp-ab-edit{background:#FEF3C7;color:#92400E}.mp-ab-edit:hover{background:#FDE68A;box-shadow:0 4px 10px rgba(251,191,36,.3)}
.mp-ab-del{background:var(--mp-rose-light);color:var(--mp-rose-dark)}.mp-ab-del:hover{background:#FECDD3;box-shadow:0 4px 10px rgba(244,63,94,.25)}
.mp-mobile-cards{display:none;padding:.875rem}
.mp-mcard{background:var(--sf);border:1.5px solid var(--mp-border-l);border-radius:14px;padding:1rem;margin-bottom:.75rem;box-shadow:0 2px 10px var(--mp-shadow)}
.mp-mcard-head{display:flex;align-items:center;gap:.75rem;margin-bottom:.75rem}
.mp-mcard-kode{font-family:'DM Mono',monospace;font-size:.78rem;font-weight:700;background:var(--mp-rose-light);color:var(--mp-rose-dark);padding:.22rem .65rem;border-radius:6px;border:1.5px solid #FECDD3;white-space:nowrap;flex-shrink:0}
.mp-mcard-name{font-size:.9rem;font-weight:800;color:var(--tx);flex:1;min-width:0}
.mp-mcard-meta{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin-bottom:.75rem}
.mp-mcard-date{font-size:.68rem;color:var(--txl);font-family:'DM Mono',monospace}
.mp-mcard-acts{display:flex;gap:.5rem;padding-top:.75rem;border-top:1.5px solid var(--mp-border-l)}
.mp-mcard-acts .mp-ab{flex:1;justify-content:center}
.mp-empty{text-align:center;padding:3.5rem 1.5rem}
.mp-empty-illo{font-size:4rem;margin-bottom:.875rem;animation:mpBounce 2.5s ease-in-out infinite}
.mp-empty-title{font-size:1.05rem;font-weight:900;color:var(--tx);margin-bottom:.3rem}
.mp-empty-sub{font-size:.825rem;font-weight:600;color:var(--txl)}
@media(min-width:1440px){.mp-stats{grid-template-columns:repeat(5,1fr)}}
@media(min-width:1025px) and (max-width:1439px){.mp-stats{grid-template-columns:repeat(3,1fr)}.mp-title{font-size:1.75rem}.mp-hero-body{padding:1.875rem 2rem}}
@media(min-width:769px) and (max-width:1024px){.mp-stats{grid-template-columns:repeat(3,1fr)}.mp-form-grid{grid-template-columns:1fr}.mp-hero-body{padding:1.75rem;flex-direction:column;align-items:flex-start}.mp-hero-right{align-self:flex-end}.mp-title{font-size:1.625rem}.mp-illo{font-size:4rem}.mp-chips{flex-direction:row;flex-wrap:wrap;gap:.5rem}.mp-chip{min-width:calc(50% - .25rem)}.mp-tbl-topbar{flex-direction:column;align-items:flex-start;padding:.875rem 1.125rem}.mp-srch{width:100%}.mp-srch-wrap{width:100%}.mp-filter-row{flex-direction:column}.mp-fg{min-width:100%}.mp-btn-filter,.mp-btn-reset,.mp-btn-save,.mp-btn-cancel{width:100%;justify-content:center}}
@media(max-width:768px){.mp-stats{grid-template-columns:repeat(2,1fr);gap:.75rem}.mp-form-grid{grid-template-columns:1fr}.mp-hero-body{flex-direction:column;align-items:flex-start;padding:1.625rem 1.375rem;gap:1rem}.mp-hero-right{align-self:flex-end;gap:.875rem}.mp-title{font-size:1.625rem}.mp-illo{font-size:4rem}.mp-chips{flex-direction:row;flex-wrap:wrap;gap:.5rem}.mp-chip{min-width:calc(50% - .25rem);flex:1}.mp-card-body{padding:1.125rem}.mp-card-head{padding:.875rem 1.125rem}.mp-filter-row{flex-direction:column}.mp-fg{min-width:100%}.mp-btn-filter,.mp-btn-reset,.mp-btn-save,.mp-btn-cancel{width:100%;justify-content:center}.mp-tbl-topbar{flex-direction:column;align-items:flex-start;padding:.875rem 1.125rem}.mp-srch{width:100%}.mp-srch-wrap{width:100%}.mp-tbl-scroll{display:none}.mp-mobile-cards{display:block}}
@media(max-width:480px){.mp-hero-body{padding:1.375rem 1rem;gap:.875rem}.mp-eyebrow{display:none}.mp-title{font-size:1.4rem}.mp-hero-char img{width:54px;height:54px}.mp-illo{display:none}.mp-chips{width:100%}.mp-chip{flex:1;padding:.6rem .875rem}.mp-chip-num{font-size:1.5rem}.mp-stats{grid-template-columns:repeat(2,1fr);gap:.625rem}.mp-sc{padding:1rem .875rem;border-radius:14px}.mp-sc-num{font-size:1.625rem}.mp-sc-ico{width:36px;height:36px;font-size:1.1rem}.mp-card-head{flex-direction:column;align-items:flex-start;gap:.625rem}}
@supports(padding:max(0px)){.mp-hero-body{padding-left:max(1.375rem,env(safe-area-inset-left));padding-right:max(1.375rem,env(safe-area-inset-right))}}
</style>

<div class="mp-bg-deco">
    <div class="mp-ds mp-ds1">📚</div><div class="mp-ds mp-ds2">📖</div>
    <div class="mp-ds mp-ds3">✏️</div><div class="mp-ds mp-ds4">🎒</div><div class="mp-ds mp-ds5">📝</div>
</div>

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

    <!-- HERO -->
    <div class="mp-hero">
        <div class="mp-hblobs">
            <div class="mp-hb mp-hb1"></div><div class="mp-hb mp-hb2"></div>
            <div class="mp-hb mp-hb3"></div><div class="mp-hb mp-hb4"></div>
        </div>
        <div class="mp-hero-body">
            <div class="mp-hero-left">
                <div class="mp-eyebrow">📖 &nbsp;Data Kurikulum</div>
                <div class="mp-hero-row">
                    <div class="mp-hero-char"><img src="assets/sekolah.png" alt="Logo"></div>
                    <div><h1 class="mp-title">Kelola <span class="acc">Mata Pelajaran</span><br>dengan mudah!</h1></div>
                </div>
                <p class="mp-sub">Atur kode, nama, kategori &amp; KKM semua mata pelajaran 📝</p>
            </div>
            <div class="mp-hero-right">
                <div class="mp-illo">📚</div>
                <div class="mp-chips">
                    <div class="mp-chip"><div><div class="mp-chip-num"><?= $total ?></div><div class="mp-chip-lbl">Total Mapel</div></div><div class="mp-chip-ico">📊</div></div>
                    <div class="mp-chip"><div><div class="mp-chip-num"><?= $wajib ?></div><div class="mp-chip-lbl">Mapel Wajib</div></div><div class="mp-chip-ico">✅</div></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ALERTS -->
    <?php
    $successMsg = ['simpan'=>['✅','Data mata pelajaran berhasil disimpan!'],'update'=>['✅','Data berhasil diupdate!'],'hapus'=>['🗑️','Data berhasil dihapus!']];
    $errorMsg   = ['empty'=>['⚠️','Semua field wajib harus diisi!'],'dupkode'=>['❌','Kode mapel sudah digunakan, gunakan kode lain!'],'failed'=>['❌','Operasi gagal. Lihat detail error di bawah.'],'kkm'=>['⚠️','KKM harus berupa angka antara 0–100!']];
    if (isset($_GET['success']) && isset($successMsg[$_GET['success']])) {
        [$ico,$txt] = $successMsg[$_GET['success']];
        echo "<div class='mp-alert mp-alert-ok'><div class='mp-alert-row'><span class='mp-alert-ico'>$ico</span>$txt</div></div>";
    }
    if (isset($_GET['error'])) {
        $key = $_GET['error'];
        [$ico,$txt] = $errorMsg[$key] ?? ['❌','Terjadi kesalahan tidak dikenal.'];
        echo "<div class='mp-alert mp-alert-err'><div class='mp-alert-row'><span class='mp-alert-ico'>$ico</span>".htmlspecialchars($txt)."</div>";
        if (!empty($_GET['msg'])) echo "<div class='mp-err-detail'>⚠️ MySQL: ".htmlspecialchars(urldecode($_GET['msg']))."</div>";
        echo "</div>";
    }
    if ($editData) echo "<div class='mp-alert mp-alert-edt'><div class='mp-alert-row'><span class='mp-alert-ico'>✏️</span>Mode Edit — mengedit <strong>".htmlspecialchars($editData['nama_mapel'])."</strong>. Selesai? Klik <em>Batal</em>.</div></div>";
    ?>

    <!-- STATS -->
    <div class="mp-stats">
        <div class="mp-sc mp-sc-all"><div class="mp-sc-top"><div><div class="mp-sc-lbl">Total Mapel</div><div class="mp-sc-num"><?=$total?></div></div><div class="mp-sc-ico">📚</div></div></div>
        <div class="mp-sc mp-sc-wj"><div class="mp-sc-top"><div><div class="mp-sc-lbl">Wajib</div><div class="mp-sc-num"><?=$wajib?></div></div><div class="mp-sc-ico">✅</div></div></div>
        <div class="mp-sc mp-sc-pil"><div class="mp-sc-top"><div><div class="mp-sc-lbl">Pilihan</div><div class="mp-sc-num"><?=$pilihan?></div></div><div class="mp-sc-ico">🎯</div></div></div>
        <div class="mp-sc mp-sc-mul"><div class="mp-sc-top"><div><div class="mp-sc-lbl">Muatan Lokal</div><div class="mp-sc-num"><?=$mulok?></div></div><div class="mp-sc-ico">🏛️</div></div></div>
        <div class="mp-sc mp-sc-eks"><div class="mp-sc-top"><div><div class="mp-sc-lbl">Ekstrakurikuler</div><div class="mp-sc-num"><?=$ekskul?></div></div><div class="mp-sc-ico">⚽</div></div></div>
    </div>

    <!-- FILTER -->
    <div class="mp-card" style="animation-delay:.06s">
        <div class="mp-card-head">
            <div class="mp-card-head-l">
                <div class="mp-ch-badge mp-ch-filter">🔍</div>
                <div><div class="mp-card-title">Filter Data</div><div class="mp-card-sub">Saring berdasarkan kategori</div></div>
            </div>
        </div>
        <div class="mp-card-body">
            <form method="GET" class="mp-filter-row">
                <div class="mp-fg">
                    <label><span>🏷️</span> Kategori</label>
                    <select name="kategori" class="mp-fs">
                        <option value="">Semua Kategori</option>
                        <?php foreach ($validKat as $k): ?>
                        <option value="<?=htmlspecialchars($k)?>" <?=$fk===$k?'selected':''?>><?=htmlspecialchars($k)?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="mp-btn-filter">🔍 Terapkan</button>
                <?php if ($fk): ?><a href="mata_pelajaran.php" class="mp-btn-reset">✖ Reset</a><?php endif; ?>
            </form>
        </div>
    </div>

    <!-- FORM -->
    <div class="mp-card <?=$editData?'edit-mode':''?>" style="animation-delay:.11s">
        <div class="mp-card-head">
            <div class="mp-card-head-l">
                <div class="mp-ch-badge <?=$editData?'mp-ch-amber':'mp-ch-rose'?>"><?=$editData?'✏️':'➕'?></div>
                <div>
                    <div class="mp-card-title"><?=$editData?'Edit Mata Pelajaran':'Tambah Mata Pelajaran Baru'?></div>
                    <div class="mp-card-sub"><?=$editData?'Perbarui data mata pelajaran':'Isi formulir di bawah ini'?></div>
                </div>
            </div>
            <?php if ($editData): ?><a href="mata_pelajaran.php" class="mp-btn-cancel">✖ Batal Edit</a><?php endif; ?>
        </div>
        <div class="mp-card-body">
            <form method="POST" id="formMapel" autocomplete="off">
                <?php if ($editData): ?>
                <input type="hidden" name="id" value="<?=(int)$editData['id']?>">
                <?php endif; ?>
                <div class="mp-form-grid">
                    <div class="mp-fg">
                        <label><span>🔢</span> Kode Mapel <span style="color:var(--mp-rose)">*</span></label>
                        <input type="text" name="kode_mapel" class="mp-fi" placeholder="Contoh: MTK, IPA, IPS"
                            value="<?=$editData?htmlspecialchars($editData['kode_mapel']):''?>" maxlength="20" required>
                    </div>
                    <div class="mp-fg">
                        <label><span>📖</span> Nama Mata Pelajaran <span style="color:var(--mp-rose)">*</span></label>
                        <input type="text" name="nama_mapel" class="mp-fi" placeholder="Contoh: Matematika"
                            value="<?=$editData?htmlspecialchars($editData['nama_mapel']):''?>" maxlength="100" required>
                    </div>
                    <div class="mp-fg">
                        <label><span>🏷️</span> Kategori <span style="color:var(--mp-rose)">*</span></label>
                        <select name="kategori" class="mp-fs" required>
                            <option value="">— Pilih Kategori —</option>
                            <?php foreach ($validKat as $k): ?>
                            <option value="<?=htmlspecialchars($k)?>" <?=($editData&&$editData['kategori']===$k)?'selected':''?>><?=htmlspecialchars($k)?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mp-fg">
                        <label><span>🎯</span> KKM (0–100) <span style="color:var(--mp-rose)">*</span></label>
                        <input type="number" name="kkm" class="mp-fi" placeholder="Contoh: 75"
                            min="0" max="100" step="1"
                            value="<?=$editData?(int)$editData['kkm']:'75'?>" required>
                    </div>
                </div>
                <div class="mp-form-actions">
                    <button type="submit" name="<?=$editData?'update':'simpan'?>" value="1"
                        class="mp-btn-save <?=$editData?'mp-btn-update':''?>">
                        <?=$editData?'🔄 Update Data':'💾 Simpan Data'?>
                    </button>
                    <?php if ($editData): ?>
                    <a href="mata_pelajaran.php" class="mp-btn-cancel">✖ Batal</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <!-- TABLE -->
    <div class="mp-card" style="animation-delay:.16s">
        <div class="mp-tbl-topbar">
            <div class="mp-tbl-title">
                <span style="font-size:1.15rem">📋</span>
                Daftar Mata Pelajaran
                <span class="mp-tbl-count"><?=$rowCount?> mapel</span>
                <?php if ($fk): ?><span class="mp-tbl-count">Filter: <?=htmlspecialchars($fk)?></span><?php endif; ?>
            </div>
            <div class="mp-srch-wrap">
                <input type="text" class="mp-srch" id="mpSrch" placeholder="Cari mapel…" onkeyup="mpSearch()">
            </div>
        </div>

        <?php if ($rowCount > 0): ?>
        <div class="mp-tbl-scroll">
            <table id="mpTbl">
                <thead>
                    <tr>
                        <th>No</th><th>Kode</th><th>Nama Mata Pelajaran</th>
                        <th>Kategori</th><th>KKM</th><th>Dibuat</th><th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                <?php $no=1; foreach ($rows as $d):
                    $kat=$d['kategori'];
                    $bc =$kat==='Wajib'?'mp-b-wajib':($kat==='Pilihan'?'mp-b-pilihan':($kat==='Muatan Lokal'?'mp-b-mulok':'mp-b-ekskul'));
                    $kkm=(int)$d['kkm'];
                    $kc =$kkm>=80?'mp-kkm-h':($kkm>=65?'mp-kkm-m':'mp-kkm-l');
                    $ki =$kkm>=80?'🟢':($kkm>=65?'🟡':'🔴');
                    $tgl=(!empty($d['created_at'])&&$d['created_at']!=='0000-00-00 00:00:00')?date('d/m/Y',strtotime($d['created_at'])):'—';
                ?>
                <tr>
                    <td class="mp-td-num"><?=$no++?></td>
                    <td><span class="mp-td-kode"><?=htmlspecialchars($d['kode_mapel'])?></span></td>
                    <td style="font-weight:700"><?=htmlspecialchars($d['nama_mapel'])?></td>
                    <td><span class="mp-badge <?=$bc?>"><span class="mp-bdot"></span><?=htmlspecialchars($kat)?></span></td>
                    <td><span class="mp-kkm <?=$kc?>"><?=$ki?> <?=$kkm?></span></td>
                    <td style="color:var(--txl);font-size:.75rem;font-family:'DM Mono',monospace"><?=$tgl?></td>
                    <td>
                        <div class="mp-acts">
                            <a href="?edit=<?=(int)$d['id']?>" class="mp-ab mp-ab-edit">✏️ Edit</a>
                            <button class="mp-ab mp-ab-del"
                                onclick="mpHapus(<?=(int)$d['id']?>,'<?=htmlspecialchars(addslashes($d['nama_mapel']),ENT_QUOTES)?>')">
                                🗑️ Hapus
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="mp-mobile-cards">
        <?php foreach ($rows as $d):
            $kat=$d['kategori'];
            $bc =$kat==='Wajib'?'mp-b-wajib':($kat==='Pilihan'?'mp-b-pilihan':($kat==='Muatan Lokal'?'mp-b-mulok':'mp-b-ekskul'));
            $kkm=(int)$d['kkm'];
            $kc =$kkm>=80?'mp-kkm-h':($kkm>=65?'mp-kkm-m':'mp-kkm-l');
            $ki =$kkm>=80?'🟢':($kkm>=65?'🟡':'🔴');
            $tgl=(!empty($d['created_at'])&&$d['created_at']!=='0000-00-00 00:00:00')?date('d/m/Y',strtotime($d['created_at'])):'—';
        ?>
        <div class="mp-mcard">
            <div class="mp-mcard-head">
                <span class="mp-mcard-kode"><?=htmlspecialchars($d['kode_mapel'])?></span>
                <div class="mp-mcard-name"><?=htmlspecialchars($d['nama_mapel'])?></div>
            </div>
            <div class="mp-mcard-meta">
                <span class="mp-badge <?=$bc?>"><span class="mp-bdot"></span><?=htmlspecialchars($kat)?></span>
                <span class="mp-kkm <?=$kc?>"><?=$ki?> <?=$kkm?></span>
                <span class="mp-mcard-date"><?=$tgl?></span>
            </div>
            <div class="mp-mcard-acts">
                <a href="?edit=<?=(int)$d['id']?>" class="mp-ab mp-ab-edit">✏️ Edit</a>
                <button class="mp-ab mp-ab-del"
                    onclick="mpHapus(<?=(int)$d['id']?>,'<?=htmlspecialchars(addslashes($d['nama_mapel']),ENT_QUOTES)?>')">
                    🗑️ Hapus
                </button>
            </div>
        </div>
        <?php endforeach; ?>
        </div>

        <?php else: ?>
        <div class="mp-empty">
            <div class="mp-empty-illo">📭</div>
            <div class="mp-empty-title">Belum ada mata pelajaran<?=$fk?' untuk kategori ini':''?>!</div>
            <div class="mp-empty-sub"><?=$fk?"Coba <a href='mata_pelajaran.php'>reset filter</a>":'Tambahkan mata pelajaran pertama di atas 👆'?></div>
        </div>
        <?php endif; ?>
    </div>

</div>
</div>

<script>
function mpHapus(id, nama) {
    if (confirm('🗑️ Hapus mata pelajaran "' + nama + '"?\n\nTindakan ini tidak dapat dibatalkan.')) {
        window.location.href = 'mata_pelajaran.php?hapus=' + id;
    }
}
function mpSearch() {
    const q = document.getElementById('mpSrch').value.toLowerCase().trim();
    document.querySelectorAll('#mpTbl tbody tr').forEach(tr => {
        tr.style.display = tr.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
    document.querySelectorAll('.mp-mcard').forEach(c => {
        c.style.display = c.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
}
<?php if ($editData): ?>
(function(){var el=document.querySelector('.mp-card.edit-mode');if(el)el.scrollIntoView({behavior:'smooth',block:'start'});})();
<?php endif; ?>
document.querySelectorAll('.mp-alert').forEach(a => {
    setTimeout(() => {
        a.style.transition='opacity .5s,transform .5s';
        a.style.opacity='0';
        a.style.transform='translateY(-10px)';
        setTimeout(()=>a.remove(),500);
    }, 7000);
});
</script>