<?php
/* ══════════════════════════════════════════════════════
   absensi.php — Manajemen Absensi 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);

date_default_timezone_set('Asia/Jakarta');

// ── 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: cek kolom tabel ──
function getColAbs($conn, $t) {
    $c = [];
    $r = mysqli_query($conn, "SHOW COLUMNS FROM `$t`");
    if ($r) while ($row = mysqli_fetch_assoc($r)) $c[] = $row['Field'];
    return $c;
}
$aKol = getColAbs($conn, 'absensi');
$sKol = getColAbs($conn, 'siswa');
$hCA   = in_array('created_at', $aKol);
$hNisn = in_array('nisn', $sKol);
$hNis  = in_array('nis',  $sKol);
$hKls  = in_array('kelas', $sKol);

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

// ── SIMPAN ──
if (isset($_POST['simpan'])) {
    $tanggal    = mysqli_real_escape_string($conn, trim($_POST['tanggal']    ?? ''));
    $siswa_id   = intval($_POST['siswa_id']   ?? 0);
    $status     = mysqli_real_escape_string($conn, trim($_POST['status']     ?? ''));
    $keterangan = mysqli_real_escape_string($conn, trim($_POST['keterangan'] ?? ''));
    $fklsBack   = urlencode($_POST['_fkls'] ?? '');
    $tglBack    = urlencode($tanggal);

    if (empty($tanggal) || !$siswa_id || empty($status)) {
        ob_end_clean(); header("Location: absensi.php?error=empty&tanggal=$tglBack&kelas=$fklsBack"); exit();
    }

    $cek = mysqli_query($conn, "SELECT id FROM absensi WHERE siswa_id='$siswa_id' AND DATE(tanggal)='$tanggal'");
    if ($cek && mysqli_num_rows($cek) > 0) {
        ob_end_clean(); header("Location: absensi.php?error=duplicate&tanggal=$tglBack&kelas=$fklsBack"); exit();
    }

    $cols = ['siswa_id', 'tanggal', 'status', 'keterangan'];
    $vals = ["'$siswa_id'", "'$tanggal'", "'$status'", "'$keterangan'"];
    if ($hCA) { $cols[] = 'created_at'; $vals[] = 'NOW()'; }

    $sql = "INSERT INTO absensi (" . implode(',', $cols) . ") VALUES (" . implode(',', $vals) . ")";
    if (mysqli_query($conn, $sql)) {
        ob_end_clean(); header("Location: absensi.php?success=simpan&tanggal=$tglBack&kelas=$fklsBack"); exit();
    } else {
        $msg = urlencode(mysqli_error($conn));
        ob_end_clean(); header("Location: absensi.php?error=insert_failed&msg=$msg&tanggal=$tglBack"); exit();
    }
}

// ── UPDATE ──
if (isset($_POST['update'])) {
    $id         = intval($_POST['id']         ?? 0);
    $tanggal    = mysqli_real_escape_string($conn, trim($_POST['tanggal']    ?? ''));
    $siswa_id   = intval($_POST['siswa_id']   ?? 0);
    $status     = mysqli_real_escape_string($conn, trim($_POST['status']     ?? ''));
    $keterangan = mysqli_real_escape_string($conn, trim($_POST['keterangan'] ?? ''));
    $fklsBack   = urlencode($_POST['_fkls'] ?? '');
    $tglBack    = urlencode($tanggal);

    if (!$id || empty($tanggal) || !$siswa_id || empty($status)) {
        ob_end_clean(); header("Location: absensi.php?error=empty&tanggal=$tglBack&kelas=$fklsBack"); exit();
    }

    $sql = "UPDATE absensi SET siswa_id='$siswa_id',tanggal='$tanggal',status='$status',keterangan='$keterangan' WHERE id=$id";
    if (mysqli_query($conn, $sql)) {
        ob_end_clean(); header("Location: absensi.php?success=update&tanggal=$tglBack&kelas=$fklsBack"); exit();
    } else {
        $msg = urlencode(mysqli_error($conn));
        ob_end_clean(); header("Location: absensi.php?error=update_failed&msg=$msg&tanggal=$tglBack"); exit();
    }
}

// ── HAPUS ──
if (isset($_GET['hapus'])) {
    $id      = intval($_GET['hapus']);
    $tglBack = isset($_GET['tanggal']) ? '&tanggal=' . urlencode($_GET['tanggal']) : '';
    $klsBack = isset($_GET['kelas'])   ? '&kelas='   . urlencode($_GET['kelas'])   : '';
    if ($id > 0 && mysqli_query($conn, "DELETE FROM absensi WHERE id=$id")) {
        ob_end_clean(); header("Location: absensi.php?success=hapus$tglBack$klsBack"); exit();
    } else {
        $msg = urlencode(mysqli_error($conn));
        ob_end_clean(); header("Location: absensi.php?error=delete_failed&msg=$msg$tglBack$klsBack"); exit();
    }
}

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

// ── FILTER TANGGAL & KELAS ──
$_tglRaw = trim($_GET['tanggal'] ?? '');
if ($_tglRaw !== '') {
    $d = DateTime::createFromFormat('Y-m-d', $_tglRaw);
    $fTgl = ($d && $d->format('Y-m-d') === $_tglRaw) ? $_tglRaw : date('Y-m-d');
} else {
    $fTgl = date('Y-m-d');
}
$fTgl = mysqli_real_escape_string($conn, $fTgl);
$fKls = mysqli_real_escape_string($conn, trim($_GET['kelas'] ?? ''));

// ── AMBIL DATA ABSENSI ──
$wc = "WHERE DATE(a.tanggal)='$fTgl'";
if ($fKls && $hKls) $wc .= " AND s.kelas LIKE '%$fKls%'";

$sSel = "a.id,a.siswa_id,a.tanggal,a.status,a.keterangan,s.nama as nama_siswa";
if ($hNisn) $sSel .= ",s.nisn";
if ($hNis)  $sSel .= ",s.nis";
if ($hKls)  $sSel .= ",s.kelas";

$ord  = $hKls ? "s.kelas,s.nama" : "s.nama";
$data = mysqli_query($conn, "SELECT $sSel FROM absensi a JOIN siswa s ON a.siswa_id=s.id $wc ORDER BY $ord");

// Simpan ke array agar bisa dipakai berkali-kali (desktop tabel + mobile cards)
$dataRows  = [];
$dataCount = 0;
if ($data) {
    while ($r = mysqli_fetch_assoc($data)) $dataRows[] = $r;
    $dataCount = count($dataRows);
}

// ── DAFTAR KELAS & SISWA ──
$kelas_list  = ($hKls) ? mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE kelas IS NOT NULL AND kelas!='' ORDER BY kelas") : null;
$sCols       = 'id,nama';
if ($hNisn) $sCols .= ',nisn';
if ($hNis)  $sCols .= ',nis';
if ($hKls)  $sCols .= ',kelas';
$siswa_list  = mysqli_query($conn, "SELECT $sCols FROM siswa ORDER BY nama");

// Simpan siswa ke array agar tidak perlu data_seek
$siswaRows = [];
if ($siswa_list) while ($s = mysqli_fetch_assoc($siswa_list)) $siswaRows[] = $s;

// ── STATISTIK ──
function cntAbs($conn, $tgl, $st) {
    $r = mysqli_query($conn, "SELECT COUNT(*) c FROM absensi WHERE DATE(tanggal)='$tgl' AND status='$st'");
    return $r ? (int)(mysqli_fetch_assoc($r)['c'] ?? 0) : 0;
}
$hadir    = cntAbs($conn, $fTgl, 'Hadir');
$izin     = cntAbs($conn, $fTgl, 'Izin');
$sakit    = cntAbs($conn, $fTgl, 'Sakit');
$alpha    = cntAbs($conn, $fTgl, 'Alpha');
$totalAbs = $hadir + $izin + $sakit + $alpha;

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

ob_end_flush();
?>

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

<style>
:root{
    --ab-tl:#0EA5E9;--ab-tld:#0284C7;--ab-tlxd:#075985;
    --ab-tll:#E0F2FE;--ab-tlp:#F0F9FF;
    --ab-mn:#10B981;--ab-mnd:#059669;
    --ab-am:#F59E0B;--ab-amd:#D97706;
    --ab-ro:#F43F5E;--ab-rod:#E11D48;
    --ab-vi:#8B5CF6;--ab-vid:#7C3AED;
    --ab-tx:#0C4A6E;--ab-txm:#7DD3FC;--ab-txd:#0369A1;
    --ab-bd:#BAE6FD;--ab-sh:rgba(14,165,233,.12);
}

.main .wrap{font-family:'Baloo 2',sans-serif}

.ab-bgd{position:fixed;inset:0;pointer-events:none;z-index:0;overflow:hidden}
.ab-fe{position:absolute;opacity:.045;user-select:none;font-size:68px}
.ab-f1{top:6%;left:4%;animation:abfa 22s ease-in-out infinite}
.ab-f2{top:58%;right:4%;font-size:86px;animation:abfb 17s ease-in-out infinite 2s}
.ab-f3{bottom:10%;left:14%;font-size:56px;animation:abfc 24s ease-in-out infinite 4s}
.ab-f4{top:32%;right:20%;font-size:74px;animation:abfa 28s ease-in-out infinite 1s}
.ab-f5{top:74%;left:40%;font-size:54px;animation:abfb 21s ease-in-out infinite 3s}
@keyframes abfa{0%,100%{transform:translate(0,0) rotate(0)}50%{transform:translate(20px,-28px) rotate(12deg)}}
@keyframes abfb{0%,100%{transform:translate(0,0)}50%{transform:translate(-16px,22px) rotate(-9deg)}}
@keyframes abfc{0%,100%{transform:translate(0,0) rotate(8deg)}33%{transform:translate(24px,-16px) rotate(-8deg)}66%{transform:translate(-10px,12px) rotate(14deg)}}
@keyframes abFadeUp{from{opacity:0;transform:translateY(22px)}to{opacity:1;transform:translateY(0)}}
@keyframes abSlideD{from{opacity:0;transform:translateY(-14px) scale(.97)}to{opacity:1;transform:translateY(0) scale(1)}}
@keyframes abPop{0%,100%{transform:scale(1)}50%{transform:scale(1.08)}}
@keyframes abBoing{0%,100%{transform:translateY(0)}40%{transform:translateY(-16px)}70%{transform:translateY(-7px)}}
@keyframes abStag{from{opacity:0;transform:translateY(18px)}to{opacity:1;transform:translateY(0)}}

/* ══ HERO ══ */
.ab-hero{background:linear-gradient(135deg,#075985 0%,#0EA5E9 45%,#22D3EE 72%,#6EE7B7 100%);border-radius:22px;padding:2rem 2.5rem;margin-bottom:1.5rem;position:relative;overflow:hidden;box-shadow:0 10px 36px rgba(14,165,233,.3);animation:abFadeUp .55s ease-out}
.ab-hbl{position:absolute;border-radius:50%;opacity:.1;background:white}
.ab-hbl1{width:220px;height:220px;top:-70px;right:28px;animation:abBoing 7s ease-in-out infinite}
.ab-hbl2{width:148px;height:148px;bottom:-48px;right:238px;animation:abBoing 5.5s ease-in-out infinite .8s}
.ab-hbl3{width:86px;height:86px;top:12px;right:328px;border-radius:22px;opacity:.16;animation:abBoing 6.5s ease-in-out infinite 1.5s}
.ab-hcon{position:relative;z-index:2;display:flex;align-items:center;justify-content:space-between;gap:1.5rem;flex-wrap:wrap}
.ab-hleft{flex:1;min-width:0}
.ab-htag{display:inline-flex;align-items:center;gap:.4rem;background:rgba(255,255,255,.2);backdrop-filter:blur(8px);border:1px solid rgba(255,255,255,.3);border-radius:50px;padding:.3rem .875rem;font-size:.7rem;font-weight:700;color:white;letter-spacing:.06em;text-transform:uppercase;margin-bottom:.75rem}
.ab-htit{font-size:2rem;font-weight:800;color:white;line-height:1.15;letter-spacing:-.02em;margin-bottom:.45rem;margin-top:0}
.ab-htit span{background:linear-gradient(90deg,#FEF08A,#86EFAC);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.ab-hdesc{font-size:.875rem;color:rgba(255,255,255,.88);font-weight:500}
.ab-hrt{display:flex;align-items:center;gap:1rem;flex-shrink:0}
.ab-hchip{text-align:center;background:rgba(255,255,255,.16);backdrop-filter:blur(12px);border:1px solid rgba(255,255,255,.28);border-radius:16px;padding:.875rem 1.25rem;min-width:96px}
.ab-hcnum{font-size:2rem;font-weight:800;color:white;line-height:1;font-family:'DM Mono',monospace}
.ab-hclbl{font-size:.62rem;color:rgba(255,255,255,.82);font-weight:700;margin-top:.2rem;text-transform:uppercase;letter-spacing:.06em}
.ab-hillo{font-size:5.5rem;filter:drop-shadow(0 7px 24px rgba(0,0,0,.18));animation:abBoing 3s ease-in-out infinite;line-height:1}
.ab-arow{display:flex;height:8px;border-radius:50px;overflow:hidden;gap:2px;margin-top:.875rem;max-width:320px}
.ab-ar-h{background:var(--ab-mn)}.ab-ar-i{background:var(--ab-tl)}.ab-ar-s{background:var(--ab-am)}.ab-ar-a{background:var(--ab-ro)}
.ab-aleg{display:flex;gap:.75rem;font-size:.68rem;font-weight:700;margin-top:.375rem;flex-wrap:wrap}
.ab-al{display:flex;align-items:center;gap:.28rem;color:white;opacity:.9}
.ab-aldot{width:6px;height:6px;border-radius:50%;display:inline-block}

/* ══ STATS ══ */
.ab-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:1rem;margin-bottom:1.5rem}
.ab-sc{background:var(--sf,#fff);border-radius:18px;border:1.5px solid var(--ab-bd);box-shadow:0 3px 16px var(--ab-sh);padding:1.25rem 1.125rem;position:relative;overflow:hidden;transition:all .28s cubic-bezier(.34,1.56,.64,1);animation:abStag .5s ease-out backwards}
.ab-sc:hover{transform:translateY(-5px);box-shadow:0 10px 26px var(--ab-sh)}
.ab-sc::before{content:'';position:absolute;top:0;left:0;right:0;height:3.5px;border-radius:18px 18px 0 0}
.ab-sh::before{background:linear-gradient(90deg,var(--ab-mn),#34D399)}
.ab-si::before{background:linear-gradient(90deg,var(--ab-tl),#38BDF8)}
.ab-ss::before{background:linear-gradient(90deg,var(--ab-am),#FCD34D)}
.ab-sa::before{background:linear-gradient(90deg,var(--ab-ro),#FB7185)}
.ab-sc:nth-child(1){animation-delay:.04s}.ab-sc:nth-child(2){animation-delay:.1s}.ab-sc:nth-child(3){animation-delay:.16s}.ab-sc:nth-child(4){animation-delay:.22s}
.ab-sc-ico{font-size:2rem;margin-bottom:.35rem;display:block;animation:abPop 2.5s ease-in-out infinite}
.ab-sc:nth-child(2) .ab-sc-ico{animation-delay:.3s}.ab-sc:nth-child(3) .ab-sc-ico{animation-delay:.6s}.ab-sc:nth-child(4) .ab-sc-ico{animation-delay:.9s}
.ab-sc-num{font-size:2.25rem;font-weight:800;font-family:'DM Mono',monospace;line-height:1;margin-bottom:.15rem}
.ab-sh .ab-sc-num{color:var(--ab-mn)}.ab-si .ab-sc-num{color:var(--ab-tl)}.ab-ss .ab-sc-num{color:var(--ab-am)}.ab-sa .ab-sc-num{color:var(--ab-ro)}
.ab-sc-lbl{font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;color:var(--txl,var(--ab-txm))}
.ab-sc-bar{position:absolute;bottom:0;left:0;right:0;height:4px;background:var(--ab-bd)}
.ab-sc-fill{height:100%;border-radius:4px;transition:width .9s ease}
.ab-sh .ab-sc-fill{background:linear-gradient(90deg,var(--ab-mn),#34D399)}
.ab-si .ab-sc-fill{background:linear-gradient(90deg,var(--ab-tl),#38BDF8)}
.ab-ss .ab-sc-fill{background:linear-gradient(90deg,var(--ab-am),#FCD34D)}
.ab-sa .ab-sc-fill{background:linear-gradient(90deg,var(--ab-ro),#FB7185)}

/* ══ ALERTS ══ */
.ab-alert{display:flex;align-items:flex-start;gap:.75rem;padding:.875rem 1.25rem;border-radius:14px;margin-bottom:1.25rem;font-weight:700;font-size:.875rem;animation:abSlideD .4s cubic-bezier(.34,1.56,.64,1);border-left:4px solid;flex-direction:column}
.ab-alert-row{display:flex;align-items:center;gap:.75rem}
.ab-aok{background:#ECFDF5;color:#065F46;border-color:#34D399}
.ab-aerr{background:#FEF2F2;color:#991B1B;border-color:#FCA5A5}
.ab-aedt{background:#FFFBEB;color:#92400E;border-color:#FCD34D}
.ab-aic{font-size:1.375rem;flex-shrink:0}
.ab-err-detail{background:#FEF2F2;border:1.5px solid #FECDD3;border-radius:8px;padding:.5rem .875rem;font-size:.72rem;font-family:'DM Mono',monospace;color:#991B1B;word-break:break-all;width:100%;box-sizing:border-box}

/* ══ CARDS ══ */
.ab-card{background:var(--sf,#fff);border-radius:20px;border:1.5px solid var(--ab-bd);box-shadow:0 3px 18px var(--ab-sh);margin-bottom:1.375rem;overflow:hidden;animation:abFadeUp .5s ease-out backwards}
.ab-card.ab-em{border-color:var(--ab-am);box-shadow:0 4px 28px rgba(245,158,11,.18)}
.ab-chd{padding:1rem 1.375rem;display:flex;align-items:center;justify-content:space-between;border-bottom:1.5px solid var(--ab-bd);flex-wrap:wrap;gap:.625rem}
.ab-chdl{display:flex;align-items:center;gap:.75rem}
.ab-cbdg{width:40px;height:40px;min-width:40px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;flex-shrink:0}
.ab-cbdg-t{background:var(--ab-tll)}.ab-cbdg-am{background:#FEF3C7}.ab-cbdg-fi{background:#EDE9FE}
.ab-ctit{font-size:.95rem;font-weight:800;color:var(--tx,var(--ab-tx))}
.ab-csub{font-size:.72rem;color:var(--txl,var(--ab-txm));font-weight:600;margin-top:1px}
.ab-cbdy{padding:1.375rem}

/* ══ FORM ══ */
.ab-gflt{display:grid;grid-template-columns:1fr 1fr auto;gap:1rem;align-items:end}
.ab-gfrm{display:grid;grid-template-columns:repeat(2,1fr);gap:1rem}
.ab-fg{display:flex;flex-direction:column;gap:.4rem}
.ab-flbl{font-size:.71rem;font-weight:800;color:var(--tx,var(--ab-tx));text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:.3rem}
.ab-req{color:var(--ab-ro)}
.ab-fi,.ab-fs{padding:.75rem .9rem;background:var(--ab-tlp);border:1.5px solid var(--ab-bd);border-radius:11px;font-size:max(.875rem,16px);font-family:'Baloo 2',sans-serif;font-weight:600;color:var(--ab-tx);transition:all .2s;outline:none;width:100%;-webkit-appearance:none}
.ab-fi:focus,.ab-fs:focus{border-color:var(--ab-tl);background:white;box-shadow:0 0 0 3px rgba(14,165,233,.1)}
.ab-sprow{display:flex;gap:.5rem;flex-wrap:wrap;margin-top:.5rem}
.ab-sp{display:flex;align-items:center;gap:.3rem;padding:.4rem .875rem;border-radius:50px;border:2px solid transparent;font-size:.8rem;font-weight:700;cursor:pointer;transition:all .2s;background:var(--ab-tlp);color:var(--ab-txd);-webkit-tap-highlight-color:transparent}
.ab-sp:hover{transform:scale(1.05)}
.ab-sH{background:#D1FAE5;color:#065F46;border-color:#34D399}
.ab-sI{background:#DBEAFE;color:#1E40AF;border-color:#60A5FA}
.ab-sS{background:#FEF3C7;color:#92400E;border-color:#FCD34D}
.ab-sA{background:#FEE2E2;color:#991B1B;border-color:#F87171}
.ab-fact{margin-top:1.375rem;display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}
.ab-bsub{display:inline-flex;align-items:center;gap:.5rem;padding:.75rem 1.625rem;border-radius:11px;border:none;font-size:.875rem;font-weight:800;font-family:'Baloo 2',sans-serif;cursor:pointer;transition:all .25s cubic-bezier(.34,1.56,.64,1);-webkit-tap-highlight-color:transparent}
.ab-bsub.ab-sv{background:linear-gradient(135deg,var(--ab-tl),var(--ab-tld));color:white;box-shadow:0 4px 16px rgba(14,165,233,.32)}
.ab-bsub.ab-sv:hover{transform:translateY(-2px);box-shadow:0 8px 22px rgba(14,165,233,.42)}
.ab-bsub.ab-up{background:linear-gradient(135deg,var(--ab-am),var(--ab-amd));color:white;box-shadow:0 4px 16px rgba(245,158,11,.32)}
.ab-bsub.ab-up:hover{transform:translateY(-2px)}
.ab-bsub.ab-fi-btn{background:linear-gradient(135deg,var(--ab-vi),var(--ab-vid));color:white;box-shadow:0 4px 16px rgba(139,92,246,.32)}
.ab-bsub.ab-fi-btn:hover{transform:translateY(-2px)}
.ab-bcan{display:inline-flex;align-items:center;gap:.4rem;padding:.75rem 1.25rem;border-radius:11px;border:1.5px solid var(--bd,var(--ab-bd));font-size:.875rem;font-weight:700;font-family:'Baloo 2',sans-serif;background:var(--sf,#fff);color:var(--txm,var(--ab-txm));text-decoration:none;cursor:pointer;transition:all .22s;-webkit-tap-highlight-color:transparent}
.ab-bcan:hover{border-color:var(--ab-ro);color:var(--ab-ro);background:#FFF1F2}
.ab-breset{display:inline-flex;align-items:center;justify-content:center;padding:.75rem 1rem;border-radius:11px;border:1.5px solid var(--bd,var(--ab-bd));font-size:.95rem;font-weight:800;font-family:'Baloo 2',sans-serif;background:var(--sf,#fff);color:var(--txm,var(--ab-txm));text-decoration:none;cursor:pointer;transition:all .22s;-webkit-tap-highlight-color:transparent}
.ab-breset:hover{border-color:var(--ab-tl);color:var(--ab-txd);background:var(--ab-tll)}

/* ══ TABLE ══ */
.ab-ttop{padding:1rem 1.375rem;background:linear-gradient(135deg,var(--ab-tlxd),var(--ab-tld));display:flex;align-items:center;justify-content:space-between;gap:.875rem;flex-wrap:wrap}
.ab-ttl{display:flex;align-items:center;gap:.5rem;color:white;font-size:.975rem;font-weight:800;flex-wrap:wrap}
.ab-tcnt{background:rgba(255,255,255,.22);padding:.15rem .7rem;border-radius:50px;font-size:.72rem;font-weight:800;color:white}
.ab-dpill{display:inline-flex;align-items:center;gap:.3rem;background:rgba(255,255,255,.18);border:1.5px solid rgba(255,255,255,.3);border-radius:50px;padding:.15rem .7rem;font-size:.7rem;color:white;font-weight:700}
.ab-sw{position:relative}
.ab-sw::before{content:'🔍';position:absolute;left:.75rem;top:50%;transform:translateY(-50%);font-size:.75rem;pointer-events:none}
.ab-si-input{padding:.525rem .875rem .525rem 2.25rem;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:.825rem;font-family:'Baloo 2',sans-serif;font-weight:600;outline:none;width:230px;transition:all .2s}
.ab-si-input::placeholder{color:rgba(255,255,255,.65)}.ab-si-input:focus{background:rgba(255,255,255,.28);border-color:white}
.ab-tscr{overflow-x:auto;-webkit-overflow-scrolling:touch;max-height:560px;overflow-y:auto}
.ab-tscr::-webkit-scrollbar{width:6px;height:6px}.ab-tscr::-webkit-scrollbar-track{background:var(--ab-tlp)}.ab-tscr::-webkit-scrollbar-thumb{background:var(--ab-tl);border-radius:50px}
.ab-tscr table{width:100%;border-collapse:collapse;min-width:640px}
.ab-tscr thead{position:sticky;top:0;z-index:5}
.ab-tscr thead tr{background:var(--ab-tll);border-bottom:2px solid var(--ab-bd)}
.ab-tscr th{padding:.7rem 1rem;text-align:left;font-size:.67rem;font-weight:800;color:var(--ab-tlxd);text-transform:uppercase;letter-spacing:.07em;white-space:nowrap}
.ab-tscr tbody tr{border-bottom:1.5px solid var(--ab-bd);transition:background .15s}
.ab-tscr tbody tr:hover{background:var(--ab-tlp)}.ab-tscr tbody tr:last-child{border-bottom:none}
.ab-tscr td{padding:.8rem 1rem;font-size:.825rem;font-weight:600;color:var(--ab-tx);vertical-align:middle}
.ab-tno{font-family:'DM Mono',monospace;font-size:.72rem;color:var(--txl,var(--ab-txm));width:32px}
.ab-tnm strong{font-weight:800;font-size:.875rem;display:block}
.ab-tnm small{font-size:.68rem;color:var(--txl,var(--ab-txm));font-family:'DM Mono',monospace}
.ab-tdt{font-family:'DM Mono',monospace;font-size:.76rem;font-weight:600;color:var(--ab-txd)}
.ab-badge{display:inline-flex;align-items:center;gap:.28rem;padding:.25rem .75rem;border-radius:50px;font-size:.72rem;font-weight:800;white-space:nowrap;border:1.5px solid transparent}
.ab-bH{background:#DCFCE7;color:#166534;border-color:#86EFAC}
.ab-bI{background:#DBEAFE;color:#1E40AF;border-color:#93C5FD}
.ab-bS{background:#FEF3C7;color:#92400E;border-color:#FCD34D}
.ab-bA{background:#FEE2E2;color:#991B1B;border-color:#FCA5A5}
.ab-acts{display:flex;gap:.375rem}
.ab-ab{display:inline-flex;align-items:center;gap:.25rem;padding:.36rem .75rem;border-radius:8px;font-size:.72rem;font-weight:800;font-family:'Baloo 2',sans-serif;text-decoration:none;border:none;cursor:pointer;transition:all .2s;-webkit-tap-highlight-color:transparent}
.ab-ab:hover{transform:translateY(-2px)}
.ab-abedt{background:#FEF3C7;color:#92400E}.ab-abedt:hover{background:#FCD34D}
.ab-abdl{background:#FEE2E2;color:#991B1B}.ab-abdl:hover{background:#FECACA}

/* ══ MOBILE CARDS ══ */
.ab-mcards{display:none;padding:.875rem}
.ab-mcard{background:var(--sf,#fff);border:1.5px solid var(--ab-bd);border-radius:14px;padding:1rem;margin-bottom:.75rem;box-shadow:0 2px 10px var(--ab-sh)}
.ab-mc-head{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem;margin-bottom:.625rem}
.ab-mc-info{flex:1;min-width:0}
.ab-mc-name{font-size:.9rem;font-weight:800;color:var(--tx,var(--ab-tx));display:block;margin-bottom:.1rem}
.ab-mc-nim{font-size:.7rem;color:var(--txl,var(--ab-txm));font-family:'DM Mono',monospace}
.ab-mc-row{display:flex;align-items:baseline;gap:.5rem;font-size:.8rem;color:var(--ab-txd);margin-bottom:.35rem}
.ab-mc-lbl{font-size:.68rem;color:var(--txl,var(--ab-txm));min-width:60px;flex-shrink:0}
.ab-mc-acts{display:flex;gap:.5rem;padding-top:.75rem;border-top:1.5px solid var(--ab-bd)}
.ab-mc-acts .ab-ab{flex:1;justify-content:center}

/* Empty state */
.ab-empty{text-align:center;padding:3.5rem 1.5rem}
.ab-emico{font-size:4.5rem;margin-bottom:.75rem;animation:abBoing 2.5s ease-in-out infinite;display:block}
.ab-emtit{font-size:1.05rem;font-weight:800;margin-bottom:.3rem;color:var(--tx,var(--ab-tx))}
.ab-emsub{font-size:.825rem;color:var(--txl,var(--ab-txm));font-weight:600}

/* ══ RESPONSIVE ══ */
@media(min-width:769px) and (max-width:1024px){
    .ab-stats{grid-template-columns:repeat(2,1fr);gap:.875rem}
    .ab-gfrm{grid-template-columns:repeat(2,1fr)}
    .ab-gflt{grid-template-columns:1fr 1fr}
    .ab-gflt>div:last-child{grid-column:span 2;display:flex;gap:.5rem}
    .ab-bsub.ab-fi-btn,.ab-breset{flex:1;justify-content:center}
    .ab-hero{padding:1.75rem}
    .ab-htit{font-size:1.875rem}
    .ab-hcon{flex-direction:column;align-items:flex-start;gap:1rem}
    .ab-hrt{align-self:flex-end}
    .ab-hillo{font-size:4.5rem}
}
@media(max-width:768px){
    .ab-hero{border-radius:18px;padding:1.625rem 1.375rem;margin-bottom:1.25rem}
    .ab-hcon{flex-direction:column;align-items:flex-start;gap:1rem}
    .ab-hrt{align-self:flex-end;gap:.875rem}
    .ab-htit{font-size:1.75rem}
    .ab-hillo{font-size:4rem}
    .ab-hchip{min-width:88px;padding:.8rem 1rem}
    .ab-hcnum{font-size:1.875rem}
    .ab-arow{max-width:100%}
    .ab-stats{grid-template-columns:repeat(2,1fr);gap:.875rem}
    .ab-gfrm{grid-template-columns:1fr}
    .ab-gflt{grid-template-columns:1fr}
    .ab-gflt>div:last-child{flex-direction:row;gap:.5rem}
    .ab-bsub.ab-fi-btn{flex:1;justify-content:center}
    .ab-cbdy{padding:1.125rem}
    .ab-chd{padding:.875rem 1.125rem}
    .ab-fact{gap:.625rem}
    .ab-bsub,.ab-bcan{width:100%;justify-content:center}
    .ab-ttop{flex-direction:column;align-items:flex-start;padding:.875rem 1.125rem;gap:.75rem}
    .ab-sw{width:100%}
    .ab-si-input{width:100%}
    .ab-tscr{display:none}
    .ab-mcards{display:block}
}
@media(max-width:480px){
    .ab-hero{padding:1.375rem 1rem;border-radius:16px}
    .ab-htag{display:none}
    .ab-htit{font-size:1.5rem}
    .ab-hillo{display:none}
    .ab-hrt{gap:.625rem}
    .ab-hchip{min-width:80px;padding:.7rem .875rem}
    .ab-hcnum{font-size:1.75rem}
    .ab-hclbl{font-size:.58rem}
    .ab-stats{gap:.625rem;margin-bottom:1.25rem}
    .ab-sc{padding:1rem .875rem;border-radius:14px}
    .ab-sc-num{font-size:2rem}
    .ab-sc-ico{font-size:1.75rem}
    .ab-cbdy{padding:1rem}
    .ab-chd{padding:.75rem 1rem}
    .ab-sprow{gap:.375rem}
    .ab-sp{font-size:.75rem;padding:.375rem .75rem}
}
@supports(padding:max(0px)){
    .ab-hero{padding-left:max(1.375rem,env(safe-area-inset-left));padding-right:max(1.375rem,env(safe-area-inset-right))}
}
</style>

<!-- Dekorasi latar -->
<div class="ab-bgd">
    <div class="ab-fe ab-f1">✅</div>
    <div class="ab-fe ab-f2">📋</div>
    <div class="ab-fe ab-f3">📝</div>
    <div class="ab-fe ab-f4">👨‍🎓</div>
    <div class="ab-fe ab-f5">🏫</div>
</div>

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

<!-- ══ HERO ══ -->
<div class="ab-hero">
    <div class="ab-hbl ab-hbl1"></div>
    <div class="ab-hbl ab-hbl2"></div>
    <div class="ab-hbl ab-hbl3"></div>
    <div class="ab-hcon">
        <div class="ab-hleft">
            <div class="ab-htag">✅ Manajemen Kehadiran</div>
            <h1 class="ab-htit">Rekap <span>Absensi</span><br>Hari Ini! 🎒</h1>
            <p class="ab-hdesc">Catat kehadiran siswa dengan mudah &amp; cepat — akurat setiap hari 📅</p>
            <?php if ($totalAbs > 0):
                $ph = round($hadir / $totalAbs * 100, 1);
                $pi = round($izin  / $totalAbs * 100, 1);
                $ps = round($sakit / $totalAbs * 100, 1);
                $pa = round($alpha / $totalAbs * 100, 1);
            ?>
            <div class="ab-arow">
                <div class="ab-ar-h" style="flex:<?=$hadir?>;min-width:<?=$hadir>0?'4px':'0'?>"></div>
                <div class="ab-ar-i" style="flex:<?=$izin?>;min-width:<?=$izin>0?'4px':'0'?>"></div>
                <div class="ab-ar-s" style="flex:<?=$sakit?>;min-width:<?=$sakit>0?'4px':'0'?>"></div>
                <div class="ab-ar-a" style="flex:<?=$alpha?>;min-width:<?=$alpha>0?'4px':'0'?>"></div>
            </div>
            <div class="ab-aleg">
                <div class="ab-al"><div class="ab-aldot" style="background:#10B981"></div>Hadir <?=$ph?>%</div>
                <div class="ab-al"><div class="ab-aldot" style="background:#0EA5E9"></div>Izin <?=$pi?>%</div>
                <div class="ab-al"><div class="ab-aldot" style="background:#F59E0B"></div>Sakit <?=$ps?>%</div>
                <div class="ab-al"><div class="ab-aldot" style="background:#F43F5E"></div>Alpha <?=$pa?>%</div>
            </div>
            <?php endif; ?>
        </div>
        <div class="ab-hrt">
            <div class="ab-hillo">📋</div>
            <div>
                <div class="ab-hchip">
                    <div class="ab-hcnum"><?=$totalAbs?></div>
                    <div class="ab-hclbl">Total Absen</div>
                </div>
                <div class="ab-hchip" style="margin-top:.625rem">
                    <div class="ab-hcnum" style="font-size:1.1rem;letter-spacing:-.01em"><?=date('d/m/Y', strtotime($fTgl))?></div>
                    <div class="ab-hclbl">Filter Aktif</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══ STAT CARDS ══ -->
<div class="ab-stats">
    <?php foreach ([
        ['ab-sh','✅',$hadir,'Hadir'],
        ['ab-si','📝',$izin,'Izin'],
        ['ab-ss','🏥',$sakit,'Sakit'],
        ['ab-sa','❌',$alpha,'Alpha']
    ] as $i => [$cls,$ico,$val,$lbl]): ?>
    <div class="ab-sc <?=$cls?>" style="animation-delay:<?=($i*.07)+.04?>s">
        <span class="ab-sc-ico"><?=$ico?></span>
        <div class="ab-sc-num"><?=$val?></div>
        <div class="ab-sc-lbl"><?=$lbl?></div>
        <div class="ab-sc-bar">
            <div class="ab-sc-fill" data-pct="<?=$totalAbs>0?round($val/$totalAbs*100,1):0?>" style="width:0%"></div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ══ ALERTS ══ -->
<?php
$okMsg  = ['simpan'=>'✅ Absensi berhasil disimpan!','update'=>'✏️ Absensi berhasil diperbarui!','hapus'=>'🗑️ Absensi berhasil dihapus!'];
$errMsg = ['duplicate'=>'⚠️ Absensi siswa pada tanggal ini sudah ada!','insert_failed'=>'❌ Gagal menyimpan data!','update_failed'=>'❌ Gagal memperbarui data!','delete_failed'=>'❌ Gagal menghapus data!','empty'=>'⚠️ Semua field wajib harus diisi!'];
if (isset($_GET['success']) && isset($okMsg[$_GET['success']])): ?>
<div class="ab-alert ab-aok" id="ab-alertBox">
    <div class="ab-alert-row"><span class="ab-aic">✅</span><strong><?=$okMsg[$_GET['success']]?></strong></div>
</div>
<?php endif; if (isset($_GET['error'])): ?>
<div class="ab-alert ab-aerr" id="ab-alertBox">
    <div class="ab-alert-row">
        <span class="ab-aic">❌</span>
        <strong><?=htmlspecialchars($errMsg[$_GET['error']] ?? 'Terjadi kesalahan.')?></strong>
    </div>
    <?php if (!empty($_GET['msg'])): ?>
    <div class="ab-err-detail">⚠️ MySQL: <?=htmlspecialchars(urldecode($_GET['msg']))?></div>
    <?php endif; ?>
</div>
<?php endif; if ($editData): ?>
<div class="ab-alert ab-aedt">
    <div class="ab-alert-row">
        <span class="ab-aic">✏️</span>
        <strong>Mode Edit Aktif</strong>&nbsp;—&nbsp;sedang mengedit data absensi.&nbsp;
        <a href="absensi.php" style="color:inherit;font-weight:900;text-decoration:underline">✖ Batal</a>
    </div>
</div>
<?php endif; ?>

<!-- ══ FILTER ══ -->
<div class="ab-card" style="animation-delay:.04s">
    <div class="ab-chd">
        <div class="ab-chdl">
            <div class="ab-cbdg ab-cbdg-fi">🔍</div>
            <div>
                <div class="ab-ctit">Filter Data Absensi</div>
                <div class="ab-csub">Tampilkan data berdasarkan tanggal &amp; kelas</div>
            </div>
        </div>
    </div>
    <div class="ab-cbdy">
        <form method="GET" action="absensi.php">
        <div class="ab-gflt">
            <div class="ab-fg">
                <label class="ab-flbl">📅 Tanggal</label>
                <input type="date" name="tanggal" class="ab-fi" value="<?=htmlspecialchars($fTgl)?>">
            </div>
            <div class="ab-fg">
                <label class="ab-flbl">🏫 Kelas</label>
                <?php if ($hKls && $kelas_list): ?>
                <select name="kelas" class="ab-fs">
                    <option value="">Semua Kelas</option>
                    <?php
                    // Ambil dari query baru agar tidak perlu data_seek
                    $klRes = mysqli_query($conn, "SELECT DISTINCT kelas FROM siswa WHERE kelas IS NOT NULL AND kelas!='' ORDER BY kelas");
                    while ($k = mysqli_fetch_assoc($klRes)):
                    ?>
                    <option value="<?=htmlspecialchars($k['kelas'])?>" <?=$fKls===$k['kelas']?'selected':''?>>
                        <?=htmlspecialchars($k['kelas'])?>
                    </option>
                    <?php endwhile; ?>
                </select>
                <?php else: ?>
                <input type="text" name="kelas" class="ab-fi" value="<?=htmlspecialchars($fKls)?>" placeholder="Nama kelas...">
                <?php endif; ?>
            </div>
            <div class="ab-fg" style="flex-direction:row;gap:.5rem;align-items:flex-end">
                <button type="submit" class="ab-bsub ab-fi-btn" style="white-space:nowrap">🔍 Filter</button>
                <a href="absensi.php" class="ab-breset" title="Reset">✕</a>
            </div>
        </div>
        </form>
    </div>
</div>

<!-- ══ FORM ABSENSI ══ -->
<div class="ab-card <?=$editData?'ab-em':''?>" id="ab-fcard" style="animation-delay:.09s">
    <div class="ab-chd">
        <div class="ab-chdl">
            <div class="ab-cbdg <?=$editData?'ab-cbdg-am':'ab-cbdg-t'?>"><?=$editData?'✏️':'➕'?></div>
            <div>
                <div class="ab-ctit"><?=$editData?'Edit Data Absensi':'Tambah Absensi Baru'?></div>
                <div class="ab-csub"><?=$editData?'Perbarui catatan kehadiran':'Catat kehadiran siswa hari ini'?></div>
            </div>
        </div>
        <?php if ($editData): ?><a href="absensi.php" class="ab-bcan">✖ Batal Edit</a><?php endif; ?>
    </div>
    <div class="ab-cbdy">
        <form method="POST" action="absensi.php">
        <?php if ($editData): ?><input type="hidden" name="id" value="<?=intval($editData['id'])?>"> <?php endif; ?>
        <input type="hidden" name="_fkls" value="<?=htmlspecialchars($fKls)?>">
        <div class="ab-gfrm">
            <div class="ab-fg">
                <label class="ab-flbl">📅 Tanggal <span class="ab-req">*</span></label>
                <input type="date" name="tanggal" class="ab-fi" required
                    value="<?=htmlspecialchars($editData ? $editData['tanggal'] : $fTgl)?>">
            </div>

            <div class="ab-fg">
                <label class="ab-flbl">👨‍🎓 Siswa <span class="ab-req">*</span></label>
                <select name="siswa_id" class="ab-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="ab-fg">
                <label class="ab-flbl">📊 Status <span class="ab-req">*</span></label>
                <select name="status" class="ab-fs" id="ab-statusSel" required onchange="abUpdPills()">
                    <option value="Hadir" <?=(!$editData || $editData['status']==='Hadir')?'selected':''?>>✅ Hadir</option>
                    <option value="Izin"  <?=($editData && $editData['status']==='Izin')?'selected':''?>>📝 Izin</option>
                    <option value="Sakit" <?=($editData && $editData['status']==='Sakit')?'selected':''?>>🏥 Sakit</option>
                    <option value="Alpha" <?=($editData && $editData['status']==='Alpha')?'selected':''?>>❌ Alpha</option>
                </select>
                <div class="ab-sprow" id="ab-sprow">
                    <div class="ab-sp" data-v="Hadir" onclick="abPickStatus('Hadir')">✅ Hadir</div>
                    <div class="ab-sp" data-v="Izin"  onclick="abPickStatus('Izin')">📝 Izin</div>
                    <div class="ab-sp" data-v="Sakit" onclick="abPickStatus('Sakit')">🏥 Sakit</div>
                    <div class="ab-sp" data-v="Alpha" onclick="abPickStatus('Alpha')">❌ Alpha</div>
                </div>
            </div>

            <div class="ab-fg">
                <label class="ab-flbl">
                    📝 Keterangan
                    <span style="color:var(--txl,var(--ab-txm));font-size:.7rem;font-weight:600;text-transform:none">(opsional)</span>
                </label>
                <input type="text" name="keterangan" class="ab-fi" placeholder="Keterangan tambahan..."
                    value="<?=$editData ? htmlspecialchars($editData['keterangan'] ?? '') : ''?>">
            </div>
        </div>
        <div class="ab-fact">
            <button type="submit" name="<?=$editData?'update':'simpan'?>" value="1"
                class="ab-bsub <?=$editData?'ab-up':'ab-sv'?>">
                <?=$editData?'💾 Update Data':'✅ Simpan Absensi'?>
            </button>
            <?php if ($editData): ?><a href="absensi.php" class="ab-bcan">✖ Batal</a><?php endif; ?>
        </div>
        </form>
    </div>
</div>

<!-- ══ DATA TABLE ══ -->
<div class="ab-card" style="animation-delay:.14s">
    <div class="ab-ttop">
        <div class="ab-ttl">
            <span style="font-size:1.2rem">📋</span>
            Data Absensi
            <span class="ab-tcnt"><?=$dataCount?> data</span>
            <span class="ab-dpill">📅 <?=date('d/m/Y', strtotime($fTgl))?></span>
        </div>
        <div class="ab-sw">
            <input type="text" class="ab-si-input" id="ab-si" placeholder="Cari nama siswa…" onkeyup="abSrch()">
        </div>
    </div>

    <?php if ($dataCount > 0): ?>

    <!-- Desktop: tabel -->
    <div class="ab-tscr">
        <table id="ab-tbl">
        <thead><tr>
            <th>No</th>
            <th>Tanggal</th>
            <?php if ($hNisn || $hNis): ?><th>NISN/NIS</th><?php endif; ?>
            <th>Nama Siswa</th>
            <?php if ($hKls): ?><th>Kelas</th><?php endif; ?>
            <th>Status</th>
            <th>Keterangan</th>
            <th>Aksi</th>
        </tr></thead>
        <tbody>
        <?php $no = 1; foreach ($dataRows as $d):
            $st  = $d['status'];
            $ico = ['Hadir'=>'✅','Izin'=>'📝','Sakit'=>'🏥','Alpha'=>'❌'][$st] ?? '•';
            $bc  = ['Hadir'=>'ab-bH','Izin'=>'ab-bI','Sakit'=>'ab-bS','Alpha'=>'ab-bA'][$st] ?? 'ab-bH';
            $nim = ($d['nisn'] ?? '') ?: ($d['nis'] ?? '');
        ?>
        <tr>
            <td class="ab-tno"><?=$no++?></td>
            <td class="ab-tdt">📅 <?=date('d/m/Y', strtotime($d['tanggal']))?></td>
            <?php if ($hNisn || $hNis): ?>
            <td><span style="font-family:'DM Mono',monospace;font-size:.74rem"><?=htmlspecialchars($nim) ?: '-'?></span></td>
            <?php endif; ?>
            <td class="ab-tnm"><strong><?=htmlspecialchars($d['nama_siswa'])?></strong></td>
            <?php if ($hKls): ?><td style="font-weight:700"><?=htmlspecialchars($d['kelas'] ?? '—')?></td><?php endif; ?>
            <td><span class="ab-badge <?=$bc?>"><?=$ico?> <?=$st?></span></td>
            <td style="color:var(--ab-txd);max-width:150px">
                <?=!empty($d['keterangan']) ? htmlspecialchars($d['keterangan']) : '<span style="color:var(--txl,var(--ab-txm))">—</span>'?>
            </td>
            <td>
                <div class="ab-acts">
                    <a href="?edit=<?=$d['id']?>&tanggal=<?=urlencode($fTgl)?>&kelas=<?=urlencode($fKls)?>" class="ab-ab ab-abedt">✏️ Edit</a>
                    <button class="ab-ab ab-abdl" onclick="abHapus(<?=$d['id']?>,'<?=htmlspecialchars(addslashes($d['nama_siswa']), ENT_QUOTES)?>')">🗑️</button>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
        </table>
    </div>

    <!-- Mobile: cards -->
    <div class="ab-mcards">
    <?php foreach ($dataRows as $d):
        $st  = $d['status'];
        $ico = ['Hadir'=>'✅','Izin'=>'📝','Sakit'=>'🏥','Alpha'=>'❌'][$st] ?? '•';
        $bc  = ['Hadir'=>'ab-bH','Izin'=>'ab-bI','Sakit'=>'ab-bS','Alpha'=>'ab-bA'][$st] ?? 'ab-bH';
        $nim = ($d['nisn'] ?? '') ?: ($d['nis'] ?? '');
    ?>
    <div class="ab-mcard">
        <div class="ab-mc-head">
            <div class="ab-mc-info">
                <span class="ab-mc-name"><?=htmlspecialchars($d['nama_siswa'])?></span>
                <?php if ($nim): ?><span class="ab-mc-nim"><?=htmlspecialchars($nim)?></span><?php endif; ?>
            </div>
            <span class="ab-badge <?=$bc?>"><?=$ico?> <?=$st?></span>
        </div>
        <div class="ab-mc-row">
            <span class="ab-mc-lbl">Tanggal</span>
            <span style="font-family:'DM Mono',monospace;font-size:.78rem"><?=date('d/m/Y', strtotime($d['tanggal']))?></span>
        </div>
        <?php if ($hKls && !empty($d['kelas'])): ?>
        <div class="ab-mc-row">
            <span class="ab-mc-lbl">Kelas</span>
            <span style="font-weight:700"><?=htmlspecialchars($d['kelas'])?></span>
        </div>
        <?php endif; ?>
        <?php if (!empty($d['keterangan'])): ?>
        <div class="ab-mc-row">
            <span class="ab-mc-lbl">Ket.</span>
            <span><?=htmlspecialchars($d['keterangan'])?></span>
        </div>
        <?php endif; ?>
        <div class="ab-mc-acts">
            <a href="?edit=<?=$d['id']?>&tanggal=<?=urlencode($fTgl)?>&kelas=<?=urlencode($fKls)?>" class="ab-ab ab-abedt">✏️ Edit</a>
            <button class="ab-ab ab-abdl" onclick="abHapus(<?=$d['id']?>,'<?=htmlspecialchars(addslashes($d['nama_siswa']), ENT_QUOTES)?>')">🗑️ Hapus</button>
        </div>
    </div>
    <?php endforeach; ?>
    </div>

    <?php else: ?>
    <div class="ab-empty">
        <span class="ab-emico">📭</span>
        <div class="ab-emtit">Belum ada data absensi</div>
        <div class="ab-emsub">Tambahkan absensi untuk <?=date('d/m/Y', strtotime($fTgl))?> menggunakan form di atas 👆</div>
    </div>
    <?php endif; ?>
</div>

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

<script>
/* ── Status pills ── */
const abPilCls = {'Hadir':'ab-sH','Izin':'ab-sI','Sakit':'ab-sS','Alpha':'ab-sA'};
function abPickStatus(v) {
    document.getElementById('ab-statusSel').value = v;
    abUpdPills();
}
function abUpdPills() {
    const v = document.getElementById('ab-statusSel').value;
    document.querySelectorAll('.ab-sp').forEach(p => {
        p.className = 'ab-sp';
        if (p.dataset.v === v) p.classList.add(abPilCls[v] || '');
    });
}

/* ── Stat bars & init ── */
window.addEventListener('DOMContentLoaded', () => {
    setTimeout(() => {
        document.querySelectorAll('.ab-sc-fill').forEach(el => {
            el.style.width = (el.dataset.pct || 0) + '%';
        });
    }, 450);
    abUpdPills();
    <?php if ($editData): ?>
    document.getElementById('ab-fcard')?.scrollIntoView({behavior:'smooth', block:'start'});
    <?php endif; ?>
});

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

/* ── Hapus ── */
function abHapus(id, nama) {
    if (confirm('🗑️ Hapus absensi milik "' + nama + '"?\n\nData tidak dapat dikembalikan!'))
        location.href = 'absensi.php?hapus=' + id + '&tanggal=<?=urlencode($fTgl)?>&kelas=<?=urlencode($fKls)?>';
}

/* ── Auto-hide alert ── */
const abAlert = document.getElementById('ab-alertBox');
if (abAlert) setTimeout(() => {
    abAlert.style.transition = 'opacity .5s, transform .5s';
    abAlert.style.opacity    = '0';
    abAlert.style.transform  = 'translateY(-10px)';
    setTimeout(() => abAlert.remove(), 500);
}, 5000);
</script>