<?php
/* ════════════════════════════════════════
   Struktur kelas: kelas (X/XI/XII) + jurusan — diambil dinamis dari DB
   ════════════════════════════════════════ */
$daftarJurusan = [];
try {
    $kelasDB = $pdo->query(
        "SELECT tingkat, nama_kelas FROM kelas WHERE status='aktif'
         ORDER BY FIELD(tingkat,'X','XI','XII'), nama_kelas"
    )->fetchAll(PDO::FETCH_ASSOC);
    foreach ($kelasDB as $row) $daftarJurusan[$row['tingkat']][] = $row['nama_kelas'];
} catch (Exception $e) {
    $daftarJurusan = ['X'=>['1','2','3','4'],'XI'=>['A-1','A-2','B-1','B-2'],'XII'=>['IPA 1','IPA 2','IPS 1','IPS 2']];
}

/* ════ Tambahkan kolom semester & tahun_ajaran ke tagihan_spp jika belum ada ════ */
try {
    $cols = $pdo->query("SHOW COLUMNS FROM tagihan_spp")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('semester', $cols)) {
        $pdo->exec("ALTER TABLE tagihan_spp ADD COLUMN `semester` TINYINT UNSIGNED DEFAULT NULL COMMENT '1=Ganjil, 2=Genap' AFTER `tahun`");
    }
    if (!in_array('tahun_ajaran', $cols)) {
        $pdo->exec("ALTER TABLE tagihan_spp ADD COLUMN `tahun_ajaran` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'Contoh: 2024/2025' AFTER `semester`");
    }
    /* Backfill data lama: isi semester & tahun_ajaran dari bulan+tahun jika masih NULL */
    $pdo->exec("UPDATE tagihan_spp SET
        semester     = IF(bulan BETWEEN 7 AND 12, 1, 2),
        tahun_ajaran = IF(bulan BETWEEN 7 AND 12,
                         CONCAT(tahun,'/',tahun+1),
                         CONCAT(tahun-1,'/',tahun))
        WHERE semester IS NULL OR tahun_ajaran IS NULL");
} catch (Exception $e) { /* tabel belum ada — abaikan */ }

require_once 'layout/header.php';

/* ════ Ambil data tahun ajaran & semester untuk filter ════ */
$tahunAjaranList = [];
try {
    $tahunAjaranList = $pdo->query(
        "SELECT DISTINCT tahun_ajaran FROM tagihan_spp
         WHERE tahun_ajaran IS NOT NULL ORDER BY tahun_ajaran DESC"
    )->fetchAll(PDO::FETCH_COLUMN);
    /* Tambahkan dari pengaturan jika belum ada */
    $taSet = '';
    try { $taSet = (string)$pdo->query("SELECT nilai FROM pengaturan WHERE kunci='tahun_ajaran' LIMIT 1")->fetchColumn(); } catch(Exception $e){}
    if ($taSet && !in_array($taSet, $tahunAjaranList)) array_unshift($tahunAjaranList, $taSet);
    if (empty($tahunAjaranList)) {
        $y = (int)date('Y');
        $m = (int)date('n');
        $tahunAjaranList = $m >= 7 ? ["$y/".($y+1)] : [($y-1)."/$y"];
    }
} catch (Exception $e) { $tahunAjaranList = [date('Y').'/'.(date('Y')+1)]; }

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

    /* ════ Generate tagihan massal — kini dengan semester & tahun_ajaran ════ */
    if ($act==='generate_bulk') {
        $bulan        = (int)$_POST['bulan'];
        $tahun        = (int)$_POST['tahun'];
        $nominal      = (int)$_POST['nominal'];
        $semester     = (int)$_POST['semester'];      // 1 = Ganjil, 2 = Genap
        $tahunAjaran  = trim($_POST['tahun_ajaran_gen'] ?? '');
        $filterKelasG = trim($_POST['filter_kelas_gen']   ?? '');
        $filterJurG   = trim($_POST['filter_jurusan_gen'] ?? '');

        /* Validasi */
        if (!$bulan || !$tahun || !$nominal || !$semester || !$tahunAjaran) {
            $_SESSION['toast'] = '❌ Lengkapi semua field sebelum generate';
            redirect('index.php?page=tagihan');
        }

        /* Ambil siswa aktif sesuai filter kelas */
        $sqlSiswa  = "SELECT id FROM siswa WHERE status='aktif'";
        $parSiswa  = [];
        if ($filterKelasG) { $sqlSiswa .= " AND kelas=?";   $parSiswa[] = $filterKelasG; }
        if ($filterJurG)   { $sqlSiswa .= " AND jurusan=?"; $parSiswa[] = $filterJurG; }
        $siswas = $pdo->prepare($sqlSiswa);
        $siswas->execute($parSiswa);
        $siswas = $siswas->fetchAll();

        $n = 0;
        foreach ($siswas as $s) {
            try {
                $pdo->prepare(
                    "INSERT IGNORE INTO tagihan_spp
                     (siswa_id, bulan, tahun, nominal, semester, tahun_ajaran)
                     VALUES (?,?,?,?,?,?)"
                )->execute([$s['id'], $bulan, $tahun, $nominal, $semester, $tahunAjaran]);
                $n++;
            } catch(Exception $e) {}
        }
        $semLabel = $semester === 1 ? 'Ganjil' : 'Genap';
        $klsLabel = $filterKelasG ? " (Kelas {$filterKelasG}".($filterJurG?" {$filterJurG}":'').')' : '';
        $_SESSION['toast'] = "✅ {$n} tagihan berhasil digenerate — Semester {$semLabel} {$tahunAjaran}{$klsLabel}";
        redirect('index.php?page=tagihan&bulan='.$bulan.'&tahun='.$tahun.'&semester='.$semester.'&tahun_ajaran='.rawurlencode($tahunAjaran));
    }

    if ($act==='edit_nominal') {
        $id      = (int)$_POST['tagihan_id'];
        $nominal = (int)$_POST['nominal'];
        if ($id > 0 && $nominal > 0) {
            $pdo->prepare("UPDATE tagihan_spp SET nominal=? WHERE id=?")->execute([$nominal, $id]);
            $_SESSION['toast'] = "✅ Nominal berhasil diperbarui";
        } else {
            $_SESSION['toast'] = "❌ Nominal tidak valid";
        }
    } elseif ($act==='edit_nominal_bulk') {
        $ids     = $_POST['tagihan_ids'] ?? [];
        $nominal = (int)$_POST['nominal_bulk'];
        $n = 0;
        if ($nominal > 0 && !empty($ids)) {
            $stmt = $pdo->prepare("UPDATE tagihan_spp SET nominal=? WHERE id=?");
            foreach ($ids as $id) { $stmt->execute([$nominal, (int)$id]); $n++; }
            $_SESSION['toast'] = "✅ {$n} nominal tagihan berhasil diperbarui";
        }
    }

    redirect('index.php?page=tagihan'
        .'&bulan='.($_POST['bulan_redirect']??date('n'))
        .'&tahun='.($_POST['tahun_redirect']??date('Y'))
        .'&semester='.($_POST['semester_redirect']??'')
        .'&tahun_ajaran='.rawurlencode($_POST['ta_redirect']??''));
}

/* ════ Filter params ════ */
$bulan       = (int)($_GET['bulan']        ?? date('n'));
$tahun       = (int)($_GET['tahun']        ?? date('Y'));
$semester    = (int)($_GET['semester']     ?? 0);
$tahunAjaran = trim($_GET['tahun_ajaran']  ?? '');
$status      = $_GET['status']             ?? '';
$kelas       = trim($_GET['kelas']         ?? '');
$jurusan     = trim(str_replace('+', ' ', $_GET['jurusan'] ?? ''));

/* Jika tahun_ajaran belum diset, ambil dari pengaturan atau generate otomatis */
if (!$tahunAjaran) {
    $tahunAjaran = $tahunAjaranList[0] ?? '';
}

/* ════ Query tagihan ════ */
$sql    = "SELECT t.*, s.nama, s.nis, s.kelas, s.jurusan
           FROM tagihan_spp t
           JOIN siswa s ON t.siswa_id = s.id
           WHERE t.bulan=? AND t.tahun=?";
$params = [$bulan, $tahun];
if ($semester)    { $sql .= " AND t.semester=?";     $params[] = $semester; }
if ($tahunAjaran) { $sql .= " AND t.tahun_ajaran=?"; $params[] = $tahunAjaran; }
if ($status)      { $sql .= " AND t.status=?";       $params[] = $status; }
if ($kelas)       { $sql .= " AND s.kelas=?";        $params[] = $kelas; }
if ($jurusan)     { $sql .= " AND s.jurusan=?";      $params[] = $jurusan; }
$sql .= " ORDER BY s.kelas, s.jurusan, s.nama";
$stmt = $pdo->prepare($sql); $stmt->execute($params);
$tagihans = $stmt->fetchAll();

$toast = $_SESSION['toast']??''; unset($_SESSION['toast']);

$totalLunas = 0; $totalBelum = 0; $totalCicil = 0;
foreach ($tagihans as $_t) {
    if($_t['status']==='lunas')           $totalLunas++;
    elseif($_t['status']==='belum_bayar') $totalBelum++;
    elseif($_t['status']==='cicilan')     $totalCicil++;
}

/* ════ Hitung jumlah tagihan per kelas+jurusan untuk badge ════ */
$kelasCounts   = [];
$jurusanCounts = [];
$parBadge = [$bulan, $tahun];
$sqlBadge = "SELECT s.kelas, s.jurusan, COUNT(*) as total
             FROM tagihan_spp t JOIN siswa s ON t.siswa_id=s.id
             WHERE t.bulan=? AND t.tahun=?";
if ($semester)    { $sqlBadge .= " AND t.semester=?";     $parBadge[] = $semester; }
if ($tahunAjaran) { $sqlBadge .= " AND t.tahun_ajaran=?"; $parBadge[] = $tahunAjaran; }
if ($status)      { $sqlBadge .= " AND t.status=?";       $parBadge[] = $status; }
$sqlBadge .= " GROUP BY s.kelas, s.jurusan";
$stmtK = $pdo->prepare($sqlBadge);
$stmtK->execute($parBadge);
foreach ($stmtK->fetchAll() as $row) {
    $kelasCounts[$row['kelas']] = ($kelasCounts[$row['kelas']] ?? 0) + $row['total'];
    $jurusanCounts[$row['kelas'].'|'.$row['jurusan']] = $row['total'];
}

/* ════ Statistik per semester untuk tab summary ════ */
$semesterStats = [];
try {
    $stSem = $pdo->query(
        "SELECT semester, tahun_ajaran, COUNT(*) as total,
                SUM(CASE WHEN status='lunas' THEN 1 ELSE 0 END) as lunas,
                SUM(CASE WHEN status='belum_bayar' THEN 1 ELSE 0 END) as belum
         FROM tagihan_spp
         WHERE tahun_ajaran IS NOT NULL
         GROUP BY semester, tahun_ajaran
         ORDER BY tahun_ajaran DESC, semester ASC"
    )->fetchAll();
    foreach ($stSem as $r) {
        $semesterStats[$r['tahun_ajaran']][$r['semester']] = $r;
    }
} catch (Exception $e) {}

/* ════ Nominal default dari pengaturan ════ */
$nominalDefault     = 200000;
$nominalDariSetting = false;
try {
    $rowNominal = $pdo->query("SELECT nilai FROM pengaturan WHERE kunci='nominal_spp' LIMIT 1")->fetch();
    if ($rowNominal && (int)$rowNominal['nilai'] > 0) {
        $nominalDefault     = (int)$rowNominal['nilai'];
        $nominalDariSetting = true;
    }
} catch(Exception $e) {}

/* Helper semester */
function semLabel(int $s): string { return $s === 1 ? '1 (Ganjil)' : '2 (Genap)'; }
function semIcon(int $s): string  { return $s === 1 ? '📗' : '📘'; }
/* Bulan tiap semester */
$bulanSemester = [
    1 => [7,8,9,10,11,12],   // Ganjil: Juli — Desember
    2 => [1,2,3,4,5,6],      // Genap:  Januari — Juni
];

$baseUrl = 'index.php?page=tagihan'
         .'&bulan='.rawurlencode($bulan)
         .'&tahun='.rawurlencode($tahun)
         .'&semester='.rawurlencode($semester)
         .'&tahun_ajaran='.rawurlencode($tahunAjaran)
         .($status ? '&status='.rawurlencode($status) : '');
?>
<?php if($toast): ?><script>window.onload=()=>showToast('<?= addslashes($toast) ?>')</script><?php endif ?>

<style>
/* ══ Generate card premium ══ */
.gen-card {
  background: linear-gradient(135deg, #0F766E 0%, #0D9488 60%, #14B8A6 100%);
  border-radius: 16px; padding: 20px 22px; margin-bottom: 16px;
  position: relative; overflow: hidden;
  box-shadow: 0 4px 20px rgba(13,148,136,.25);
}
.gen-card::before {
  content:''; position:absolute; right:-40px; top:-40px;
  width:150px; height:150px; border-radius:50%;
  background:rgba(255,255,255,.08); pointer-events:none;
}
.gen-card::after {
  content:''; position:absolute; right:60px; bottom:-50px;
  width:110px; height:110px; border-radius:50%;
  background:rgba(255,255,255,.05); pointer-events:none;
}
.gen-card-title {
  font-size:13px; font-weight:700; color:rgba(255,255,255,.85);
  text-transform:uppercase; letter-spacing:.06em;
  margin-bottom:14px; display:flex; align-items:center; gap:7px;
}
.gen-field-wrap {
  display:flex; gap:8px; flex-wrap:wrap; align-items:flex-end;
  position:relative; z-index:1;
}
.gen-field { display:flex; flex-direction:column; gap:4px; }
.gen-label {
  font-size:10.5px; font-weight:700; color:rgba(255,255,255,.7);
  text-transform:uppercase; letter-spacing:.06em;
}
.gen-select, .gen-input {
  height:38px; padding:0 12px;
  background:rgba(255,255,255,.15); border:1.5px solid rgba(255,255,255,.25);
  border-radius:9px; color:#fff; font-size:13px; font-family:'DM Sans',sans-serif;
  outline:none; cursor:pointer; transition:border-color .15s, background .15s;
  -webkit-appearance:none; appearance:none;
}
.gen-select:focus, .gen-input:focus {
  border-color:rgba(255,255,255,.6); background:rgba(255,255,255,.22);
}
.gen-select option { background:#0F766E; color:#fff; }
.gen-input::placeholder { color:rgba(255,255,255,.5); }

/* Semester pill selector */
.sem-selector { display:flex; gap:6px; }
.sem-pill {
  display:inline-flex; align-items:center; gap:5px;
  padding:0 14px; height:38px; border-radius:9px; font-size:13px; font-weight:600;
  border:1.5px solid rgba(255,255,255,.25); background:rgba(255,255,255,.12);
  color:#fff; cursor:pointer; transition:all .15s;
  font-family:'DM Sans',sans-serif;
}
.sem-pill:hover { background:rgba(255,255,255,.22); border-color:rgba(255,255,255,.5); }
.sem-pill.active { background:#fff; color:#0D9488; border-color:#fff; box-shadow:0 2px 8px rgba(0,0,0,.15); }
.sem-pill input { display:none; }

/* Semester info strip */
.sem-info-strip {
  background:rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.2);
  border-radius:8px; padding:8px 12px; margin-top:12px;
  font-size:12px; color:rgba(255,255,255,.85); display:flex; align-items:center; gap:8px;
  flex-wrap:wrap; position:relative; z-index:1;
}
.sem-info-badge {
  background:rgba(255,255,255,.2); border-radius:6px;
  padding:2px 8px; font-size:11px; font-weight:700; color:#fff;
}

/* ══ Semester summary tabs ══ */
.sem-summary-wrap {
  display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:16px;
}
.sem-summary-card {
  background:var(--surface); border:1.5px solid var(--border);
  border-radius:12px; padding:13px 15px;
  display:flex; align-items:center; gap:12px;
  transition:border-color .15s, box-shadow .15s; cursor:pointer;
  text-decoration:none;
}
.sem-summary-card:hover  { border-color:#0D9488; box-shadow:0 2px 10px rgba(13,148,136,.12); }
.sem-summary-card.active { border-color:#0D9488; background:#F0FDFA; box-shadow:0 2px 10px rgba(13,148,136,.15); }
.sem-summary-icon {
  width:40px; height:40px; border-radius:10px; flex-shrink:0;
  display:flex; align-items:center; justify-content:center; font-size:20px;
}
.sem-summary-label { font-size:11px; color:var(--text3); font-weight:600; text-transform:uppercase; letter-spacing:.05em; }
.sem-summary-val   { font-size:15px; font-weight:700; color:var(--text); margin-top:2px; }
.sem-summary-meta  { font-size:11px; color:var(--text2); margin-top:2px; }
.sem-progress-wrap { margin-top:6px; }
.sem-progress-bar  { height:5px; background:var(--border); border-radius:99px; overflow:hidden; }
.sem-progress-fill { height:100%; border-radius:99px; background:linear-gradient(90deg,#10B981,#0D9488); transition:width .4s; }

/* ══ View Toggle ══ */
.view-toggle { display:flex;gap:4px;background:var(--surface2,#f1f5f9);border-radius:10px;padding:3px;flex-shrink:0; }
.view-toggle button { display:flex;align-items:center;gap:5px;padding:5px 11px;border:none;border-radius:8px;background:transparent;color:var(--text3);font-size:12px;font-weight:500;cursor:pointer;transition:all .18s ease;white-space:nowrap;font-family:inherit; }
.view-toggle button.active { background:var(--surface,#fff);color:#0D9488;box-shadow:0 1px 4px rgba(0,0,0,.08); }
#tagihan-view-table { display:flex;flex-direction:column; }
#tagihan-view-cards { display:none;flex-direction:column; }
.tagihan-table-scroll-wrap { flex:1;overflow-y:auto;overflow-x:auto;max-height:540px;scrollbar-width:thin;scrollbar-color:var(--border) transparent; }
.tagihan-table-scroll-wrap::-webkit-scrollbar { width:5px;height:5px; }
.tagihan-table-scroll-wrap::-webkit-scrollbar-thumb { background:var(--border);border-radius:99px; }
.tagihan-table-scroll-wrap thead th { position:sticky;top:0;z-index:2;background:var(--surface2,#f8fafc);box-shadow:0 1px 0 var(--border); }
.tagihan-cards-scroll-wrap { flex:1;max-height:540px;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:var(--border) transparent; }
.tagihan-cards-scroll-wrap::-webkit-scrollbar { width:5px; }
.tagihan-cards-scroll-wrap::-webkit-scrollbar-thumb { background:var(--border);border-radius:99px; }
.tagihan-cards { display:grid;grid-template-columns:repeat(auto-fill,minmax(270px,1fr));gap:12px;padding:16px; }
.tagihan-card { background:var(--surface,#fff);border:1.5px solid var(--border);border-radius:16px;overflow:hidden;display:flex;flex-direction:column;transition:box-shadow .18s,transform .18s;animation:tagCardIn .22s ease both;position:relative; }
.tagihan-card:hover { box-shadow:0 6px 22px rgba(0,0,0,.09);transform:translateY(-2px); }
@keyframes tagCardIn { from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)} }
.tagihan-card-bar   { height:4px;width:100%; }
.tagihan-card-check { position:absolute;top:12px;left:12px;width:18px;height:18px;cursor:pointer;accent-color:#0D9488;z-index:2; }
.tagihan-card-body  { padding:14px 15px;display:flex;flex-direction:column;gap:10px;flex:1; }
.tagihan-card-top   { display:flex;align-items:flex-start;gap:10px;padding-left:26px; }
.tagihan-card-name  { font-weight:700;font-size:13.5px;color:var(--text);line-height:1.25;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; }
.tagihan-card-nis   { font-size:11px;color:var(--text3);font-family:monospace; }
.tagihan-card-hr    { border:none;border-top:1px solid var(--border);margin:0; }
.tagihan-card-rows  { display:flex;flex-direction:column;gap:7px; }
.tagihan-card-row   { display:flex;align-items:center;justify-content:space-between;font-size:12.5px; }
.tagihan-card-row-label { display:flex;align-items:center;gap:5px;color:var(--text3);font-size:12px; }
.tagihan-card-nominal { font-family:'DM Mono',monospace;font-weight:700;font-size:16px;color:var(--text);letter-spacing:-.3px; }
.tagihan-card-footer { display:flex;gap:6px;padding:10px 14px 13px;border-top:1px solid var(--border);background:var(--surface2,#f8fafc); }
.tagihan-card-footer>* { flex:1; }

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

/* ══ Pager ══ */
.tagihan-pager { display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;padding:12px 16px;border-top:1px solid var(--border);background:var(--surface2,#f8fafc);flex-shrink:0; }
.tagihan-pager-info { font-size:12.5px;color:var(--text2); }
.tagihan-pager-btns { display:flex;gap:4px;align-items:center;flex-wrap:wrap; }
.tagihan-pager-btn { min-width:34px;height:34px;padding:0 10px;border:1.5px solid var(--border);border-radius:8px;background:var(--surface,#fff);color:var(--text);font-size:12.5px;font-weight:500;cursor:pointer;font-family:inherit;transition:all .15s;display:inline-flex;align-items:center;justify-content:center; }
.tagihan-pager-btn:hover:not(.disabled):not(.active) { background:var(--surface2);border-color:#0D9488;color:#0D9488; }
.tagihan-pager-btn.active  { background:#0D9488;color:#fff;border-color:#0D9488;font-weight:700; }
.tagihan-pager-btn.disabled { opacity:.38;cursor:not-allowed; }
.tagihan-pager-ellipsis { font-size:13px;color:var(--text3);padding:0 3px;user-select:none; }

@media (max-width:640px) {
  .gen-field-wrap  { flex-direction:column; }
  .gen-field       { width:100%; }
  .gen-select, .gen-input { width:100%; box-sizing:border-box; }
  .sem-summary-wrap { grid-template-columns:1fr; }
  .tagihan-cards   { grid-template-columns:1fr 1fr;gap:10px;padding:12px; }
}
@media (max-width:420px) { .tagihan-cards { grid-template-columns:1fr; } }
</style>

<!-- Modal Edit Nominal -->
<div id="modalEditNominal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center">
  <div style="background:#fff;border-radius:20px;padding:28px;width:360px;max-width:90vw;box-shadow:0 20px 60px rgba(0,0,0,0.3)">
    <div style="font-weight:700;font-size:18px;color:#134E4A;margin-bottom:6px">✏️ Edit Nominal</div>
    <div id="modalNamaSiswa" style="font-size:13px;color:#6B7280;margin-bottom:20px"></div>
    <form method="POST" action="index.php?page=tagihan">
      <input type="hidden" name="action" value="edit_nominal">
      <input type="hidden" name="tagihan_id"        id="inputTagihanId">
      <input type="hidden" name="bulan_redirect"    value="<?= $bulan ?>">
      <input type="hidden" name="tahun_redirect"    value="<?= $tahun ?>">
      <input type="hidden" name="semester_redirect" value="<?= $semester ?>">
      <input type="hidden" name="ta_redirect"       value="<?= e($tahunAjaran) ?>">
      <div style="margin-bottom:16px">
        <label style="font-size:13px;font-weight:600;color:#374151;display:block;margin-bottom:6px">Nominal SPP (Rp)</label>
        <input type="number" name="nominal" id="inputNominal" required min="1000" step="1000"
               style="width:100%;padding:12px 14px;border:2px solid #0D9488;border-radius:12px;font-size:15px;font-family:'DM Sans',sans-serif;box-sizing:border-box;outline:none">
      </div>
      <div style="display:flex;gap:10px">
        <button type="button" onclick="tutupModal()"
                style="flex:1;padding:12px;border:2px solid #0D9488;border-radius:12px;background:#fff;color:#134E4A;font-weight:700;cursor:pointer;font-size:14px">Batal</button>
        <button type="submit"
                style="flex:1;padding:12px;border:none;border-radius:12px;background:#0D9488;color:#fff;font-weight:700;cursor:pointer;font-size:14px">💾 Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Page Header -->
<div class="page-header">
  <div>
    <div class="page-header-title">📋 Tagihan SPP</div>
    <div class="page-header-sub">Kelola tagihan SPP per bulan, semester &amp; tahun ajaran</div>
  </div>
</div>

<!-- ════ GENERATE CARD PREMIUM ════ -->
<div class="gen-card">
  <div class="gen-card-title">⚡ Generate Tagihan SPP</div>
  <form method="POST" id="formGenerate" onsubmit="return konfirmasiGenerate()">
    <input type="hidden" name="action" value="generate_bulk">
    <input type="hidden" name="semester" id="hidSemester" value="<?= $semester ?: 1 ?>">

    <div class="gen-field-wrap">

      <!-- Semester selector -->
      <div class="gen-field">
        <div class="gen-label">Semester</div>
        <div class="sem-selector">
          <label class="sem-pill <?= (!$semester || $semester===1) ? 'active' : '' ?>" id="semPill1" onclick="setSemester(1)">
            <input type="radio" name="_sem_ui" value="1" <?= (!$semester||$semester===1)?'checked':'' ?>>
            📗 Ganjil
          </label>
          <label class="sem-pill <?= $semester===2 ? 'active' : '' ?>" id="semPill2" onclick="setSemester(2)">
            <input type="radio" name="_sem_ui" value="2" <?= $semester===2?'checked':'' ?>>
            📘 Genap
          </label>
        </div>
      </div>

      <!-- Tahun Ajaran -->
      <div class="gen-field" style="min-width:140px">
        <div class="gen-label">Tahun Ajaran</div>
        <select name="tahun_ajaran_gen" id="selTahunAjaran" class="gen-select" onchange="syncBulanTahun()">
          <?php foreach($tahunAjaranList as $ta): ?>
          <option value="<?= e($ta) ?>" <?= $tahunAjaran===$ta?'selected':'' ?>><?= e($ta) ?></option>
          <?php endforeach ?>
          <option value="_custom">+ Ketik Manual...</option>
        </select>
        <input type="text" id="inputTahunAjaranCustom" class="gen-input" name="_ta_custom"
               placeholder="2025/2026" style="display:none;margin-top:4px;width:120px">
      </div>

      <!-- Bulan -->
      <div class="gen-field">
        <div class="gen-label">Bulan</div>
        <select name="bulan" id="selBulanGen" class="gen-select">
          <?php for($b=1;$b<=12;$b++): ?>
          <option value="<?= $b ?>" <?= $bulan===$b?'selected':'' ?>><?= bulanIndo($b) ?></option>
          <?php endfor ?>
        </select>
      </div>

      <!-- Tahun -->
      <div class="gen-field">
        <div class="gen-label">Tahun</div>
        <select name="tahun" id="selTahunGen" class="gen-select">
          <?php for($y=date('Y')+1;$y>=2020;$y--): ?>
          <option value="<?= $y ?>" <?= $tahun===$y?'selected':'' ?>><?= $y ?></option>
          <?php endfor ?>
        </select>
      </div>

      <!-- Nominal -->
      <div class="gen-field" style="flex:1;min-width:140px">
        <div class="gen-label">Nominal SPP (Rp)</div>
        <input type="number" name="nominal" class="gen-input" id="inputNominalGenerate"
               value="<?= $nominalDefault ?>" required min="1000" step="1000"
               placeholder="Nominal SPP" style="width:100%;box-sizing:border-box">
      </div>

      <!-- Filter kelas (opsional) -->
      <div class="gen-field">
        <div class="gen-label">Kelas <span style="color:rgba(255,255,255,.5);font-size:9px">(opsional)</span></div>
        <select name="filter_kelas_gen" id="selKelasGen" class="gen-select" onchange="syncJurusanGen()">
          <option value="">Semua Kelas</option>
          <?php foreach(array_keys($daftarJurusan) as $tk): ?>
          <option value="<?= $tk ?>">Kelas <?= $tk ?></option>
          <?php endforeach ?>
        </select>
      </div>

      <div class="gen-field" id="wrapJurusanGen">
        <div class="gen-label">Rombel <span style="color:rgba(255,255,255,.5);font-size:9px">(opsional)</span></div>
        <select name="filter_jurusan_gen" id="selJurusanGen" class="gen-select">
          <option value="">Semua Rombel</option>
        </select>
      </div>

      <!-- Tombol generate -->
      <div class="gen-field" style="align-self:flex-end">
        <button type="submit" class="btn"
                style="height:38px;background:#fff;color:#0D9488;font-weight:700;border:none;padding:0 20px;font-size:13.5px;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,.15)">
          ⚡ Generate
        </button>
      </div>
    </div>

    <!-- Info strip: bulan-bulan yang termasuk semester ini -->
    <div class="sem-info-strip" id="semInfoStrip"></div>
  </form>
</div>

<!-- ════ SUMMARY SEMESTER ════ -->
<?php if(!empty($semesterStats)): ?>
<?php $taForSummary = $tahunAjaran ?: ($tahunAjaranList[0] ?? ''); ?>
<?php if(isset($semesterStats[$taForSummary])): ?>
<div class="sem-summary-wrap">
  <?php foreach([1,2] as $sm):
    $sd = $semesterStats[$taForSummary][$sm] ?? null;
    $smLbl = $sm===1?'Ganjil':'Genap';
    $smIco = $sm===1?'📗':'📘';
    $smBg  = $sm===1?'#ECFDF5':'#EFF6FF';
    $smClr = $sm===1?'#059669':'#2563EB';
    $pct   = $sd && $sd['total'] > 0 ? round($sd['lunas'] / $sd['total'] * 100) : 0;
    $isActive = (int)$semester === $sm;
    $semUrl = 'index.php?page=tagihan'
            .'&bulan='.rawurlencode($bulan)
            .'&tahun='.rawurlencode($tahun)
            .'&semester='.$sm
            .'&tahun_ajaran='.rawurlencode($taForSummary);
  ?>
  <a href="<?= $semUrl ?>" class="sem-summary-card <?= $isActive?'active':'' ?>" style="border-left:4px solid <?= $smClr ?>">
    <div class="sem-summary-icon" style="background:<?= $smBg ?>;font-size:22px"><?= $smIco ?></div>
    <div style="flex:1;min-width:0">
      <div class="sem-summary-label">Semester <?= $smLbl ?> <?= e($taForSummary) ?></div>
      <?php if($sd): ?>
        <div class="sem-summary-val" style="color:<?= $smClr ?>"><?= $sd['total'] ?> tagihan</div>
        <div class="sem-summary-meta">✅ <?= $sd['lunas'] ?> lunas &nbsp;·&nbsp; ⏳ <?= $sd['belum'] ?> belum</div>
        <div class="sem-progress-wrap">
          <div class="sem-progress-bar">
            <div class="sem-progress-fill" style="width:<?= $pct ?>%;background:<?= $smClr ?>"></div>
          </div>
          <div style="font-size:10.5px;color:var(--text3);margin-top:3px"><?= $pct ?>% lunas</div>
        </div>
      <?php else: ?>
        <div class="sem-summary-val" style="color:var(--text3)">Belum ada tagihan</div>
        <div class="sem-summary-meta" style="color:var(--text3)">Generate untuk semester ini</div>
      <?php endif ?>
    </div>
    <?php if($isActive): ?>
    <div style="color:<?= $smClr ?>;flex-shrink:0">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
    </div>
    <?php endif ?>
  </a>
  <?php endforeach ?>
</div>
<?php endif ?>
<?php endif ?>

<!-- Edit Nominal Massal -->
<?php if(!empty($tagihans)): ?>
<div class="card" style="background:#F0FDFA;border:1.5px solid #99F6E4;margin-bottom:16px">
  <div class="card-title" style="color:#134E4A">✏️ Edit Nominal Massal</div>
  <form method="POST" onsubmit="return konfirmasiBulkEdit()">
    <input type="hidden" name="action"            value="edit_nominal_bulk">
    <input type="hidden" name="bulan_redirect"    value="<?= $bulan ?>">
    <input type="hidden" name="tahun_redirect"    value="<?= $tahun ?>">
    <input type="hidden" name="semester_redirect" value="<?= $semester ?>">
    <input type="hidden" name="ta_redirect"       value="<?= e($tahunAjaran) ?>">
    <div class="form-row" style="align-items:end">
      <div class="form-group" style="flex:2">
        <label>Nominal Baru (Rp) — berlaku untuk tagihan yang dicentang</label>
        <input type="number" name="nominal_bulk" id="nominalBulk" min="1000" step="1000" placeholder="Contoh: 250000" required>
      </div>
      <div class="form-group" style="margin-bottom:16px">
        <button type="submit" class="btn btn-primary" style="width:100%;background:#0D9488">💾 Update Nominal Terpilih</button>
      </div>
    </div>
    <div id="hiddenCheckboxes"></div>
  </form>
</div>
<?php endif ?>

<!-- Stats mini -->
<?php if(!empty($tagihans)): ?>
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px">
  <div style="background:#D1FAE5;border-radius:12px;padding:14px 16px;display:flex;align-items:center;gap:10px">
    <span style="font-size:22px">✅</span>
    <div>
      <div style="font-size:20px;font-weight:700;color:#065F46"><?= $totalLunas ?></div>
      <div style="font-size:11px;color:#059669;font-weight:600">Lunas</div>
    </div>
  </div>
  <div style="background:#FEF3C7;border-radius:12px;padding:14px 16px;display:flex;align-items:center;gap:10px">
    <span style="font-size:22px">🔄</span>
    <div>
      <div style="font-size:20px;font-weight:700;color:#92400E"><?= $totalCicil ?></div>
      <div style="font-size:11px;color:#D97706;font-weight:600">Cicilan</div>
    </div>
  </div>
  <div style="background:#FFE4EE;border-radius:12px;padding:14px 16px;display:flex;align-items:center;gap:10px">
    <span style="font-size:22px">⏳</span>
    <div>
      <div style="font-size:20px;font-weight:700;color:#9B1C4C"><?= $totalBelum ?></div>
      <div style="font-size:11px;color:#E11D48;font-weight:600">Belum Bayar</div>
    </div>
  </div>
</div>
<?php endif ?>

<!-- Filter Kelas -->
<div style="display:flex;flex-direction:column;gap:6px;margin-bottom:16px">
  <div class="kelas-filter-wrap">
    <a href="<?= $baseUrl ?>&kelas=&jurusan=" class="kelas-btn <?= (!$kelas&&!$jurusan)?'active':'' ?>">🏫 Semua Kelas</a>
    <?php foreach($daftarJurusan as $tkt=>$jList):
      $jmlTkt = $kelasCounts[$tkt] ?? 0;
    ?>
    <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($tkt) ?>&jurusan=" class="kelas-btn <?= ($kelas===$tkt)?'active':'' ?>">
      Kelas <?= $tkt ?>
      <?php if($jmlTkt): ?><span class="kelas-btn-count"><?= $jmlTkt ?></span><?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php if($kelas && isset($daftarJurusan[$kelas])): ?>
  <div class="kelas-filter-wrap" style="background:var(--surface,#fff);border-color:#0D9488;border-left-width:4px">
    <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=" class="kelas-btn <?= !$jurusan?'active':'' ?>">Semua <?= e($kelas) ?></a>
    <?php foreach($daftarJurusan[$kelas] as $j):
      $jmlJ = $jurusanCounts[$kelas.'|'.$j] ?? 0;
    ?>
    <a href="<?= $baseUrl ?>&kelas=<?= rawurlencode($kelas) ?>&jurusan=<?= rawurlencode($j) ?>" class="kelas-btn <?= ($jurusan===$j)?'active':'' ?>">
      <?= e($kelas) ?> <?= e($j) ?>
      <?php if($jmlJ): ?><span class="kelas-btn-count"><?= $jmlJ ?></span><?php endif ?>
    </a>
    <?php endforeach ?>
  </div>
  <?php endif ?>
</div>

<!-- TABLE/CARD WRAPPER -->
<div class="card" style="padding:0;overflow:hidden">
  <!-- Header bar -->
  <div style="padding:13px 16px;border-bottom:1px solid var(--border);display:flex;gap:10px;flex-wrap:wrap;align-items:center;flex-shrink:0">
    <div style="font-weight:700;font-size:14px;color:var(--text);display:flex;align-items:center;gap:8px;flex-wrap:wrap">
      📋 Tagihan <?= bulanIndo($bulan) ?> <?= $tahun ?>
      <?php if($semester): ?>
        <span style="background:<?= $semester===1?'#ECFDF5':'#EFF6FF' ?>;color:<?= $semester===1?'#059669':'#2563EB' ?>;border-radius:7px;padding:2px 9px;font-size:11.5px;font-weight:700;border:1px solid <?= $semester===1?'#6EE7B7':'#BFDBFE' ?>">
          <?= $semester===1?'📗':'📘' ?> Sem <?= $semester===1?'Ganjil':'Genap' ?>
        </span>
      <?php endif ?>
      <?php if($tahunAjaran): ?>
        <span style="background:#EDE9FE;color:#7C3AED;border-radius:7px;padding:2px 9px;font-size:11.5px;font-weight:700;border:1px solid #C4B5FD">
          📅 <?= e($tahunAjaran) ?>
        </span>
      <?php endif ?>
      <?php if(!empty($tagihans)): ?>
        <span class="pill" style="background:#F0FDFA;color:#0D9488;border:1px solid #99F6E4;font-size:11px"><?= count($tagihans) ?> tagihan</span>
      <?php endif ?>
    </div>
    <div style="flex:1"></div>
    <?php if(!empty($tagihans)): ?>
    <div style="display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--text2)">
      Tampil
      <select id="tagihanPerPage" onchange="tagihanOnPerPage(this.value)"
              style="padding:4px 8px;border:1.5px solid var(--border);border-radius:7px;font-size:12px;background:var(--surface,#fff);color:var(--text);font-family:inherit;cursor:pointer">
        <option value="10">10</option><option value="20">20</option><option value="50">50</option><option value="100">100</option>
      </select>/ hal
    </div>
    <button type="button" id="btnPilihSemua" onclick="pilihSemua()"
            style="padding:6px 12px;border:1.5px solid #0D9488;border-radius:8px;background:#F0FDFA;color:#134E4A;font-size:12px;font-weight:600;cursor:pointer">
      ☑️ Pilih Semua
    </button>
    <?php endif ?>
    <div class="view-toggle">
      <button id="tagihan-btn-table" class="active" onclick="tagihanSwitchView('table')">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18"/></svg>
        <span class="toggle-label">Tabel</span>
      </button>
      <button id="tagihan-btn-cards" onclick="tagihanSwitchView('cards')">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="8" height="8" rx="1.5"/><rect x="13" y="3" width="8" height="8" rx="1.5"/><rect x="3" y="13" width="8" height="8" rx="1.5"/><rect x="13" y="13" width="8" height="8" rx="1.5"/></svg>
        <span class="toggle-label">Kartu</span>
      </button>
    </div>
    <!-- Filter bulan/tahun/semester/status -->
    <form method="GET" action="index.php" style="display:flex;gap:8px;flex-wrap:wrap">
      <input type="hidden" name="page"        value="tagihan">
      <input type="hidden" name="kelas"       value="<?= e($kelas) ?>">
      <input type="hidden" name="jurusan"     value="<?= e($jurusan) ?>">
      <input type="hidden" name="tahun_ajaran" value="<?= e($tahunAjaran) ?>">
      <select name="semester" onchange="this.form.submit()"
              style="padding:7px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);cursor:pointer;font-family:inherit">
        <option value="">Sem. Semua</option>
        <option value="1" <?= $semester===1?'selected':'' ?>>📗 Sem. Ganjil</option>
        <option value="2" <?= $semester===2?'selected':'' ?>>📘 Sem. Genap</option>
      </select>
      <select name="bulan" onchange="this.form.submit()"
              style="padding:7px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);cursor:pointer;font-family:inherit">
        <?php for($b=1;$b<=12;$b++): ?>
        <option value="<?= $b ?>" <?= $bulan===$b?'selected':'' ?>><?= bulanIndo($b) ?></option>
        <?php endfor ?>
      </select>
      <select name="tahun" onchange="this.form.submit()"
              style="padding:7px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);cursor:pointer;font-family:inherit">
        <?php for($y=date('Y')+1;$y>=2020;$y--): ?>
        <option value="<?= $y ?>" <?= $tahun===$y?'selected':'' ?>><?= $y ?></option>
        <?php endfor ?>
      </select>
      <select name="status" onchange="this.form.submit()"
              style="padding:7px 10px;border:1.5px solid var(--border);border-radius:8px;font-size:12.5px;background:var(--surface);color:var(--text);cursor:pointer;font-family:inherit">
        <option value=""            <?= !$status?'selected':'' ?>>Semua Status</option>
        <option value="belum_bayar" <?= $status==='belum_bayar'?'selected':'' ?>>Belum Bayar</option>
        <option value="lunas"       <?= $status==='lunas'?'selected':'' ?>>Lunas</option>
        <option value="cicilan"     <?= $status==='cicilan'?'selected':'' ?>>Cicilan</option>
      </select>
    </form>
  </div>

  <?php
    $statusBarColor = ['lunas'=>'#10B981','cicilan'=>'#F59E0B','belum_bayar'=>'#F43F5E'];
    $statusIcon     = ['lunas'=>'✅','cicilan'=>'🔄','belum_bayar'=>'⏳'];
    $statusLabel    = ['lunas'=>'Lunas','cicilan'=>'Cicilan','belum_bayar'=>'Belum Bayar'];
    $badgeMap       = ['lunas'=>'badge-success','cicilan'=>'badge-warning','belum_bayar'=>'badge-danger'];
  ?>

  <!-- TABLE VIEW -->
  <div id="tagihan-view-table">
    <div class="tagihan-table-scroll-wrap">
      <table>
        <thead>
          <tr>
            <th style="width:36px"><input type="checkbox" id="checkAll" onchange="toggleAll(this)" style="cursor:pointer"></th>
            <th>#</th><th>Siswa</th><th>Kelas</th><th>Semester</th><th>Nominal</th><th>Status</th><th>Aksi</th>
          </tr>
        </thead>
        <tbody id="tagihan-tbody">
        <?php if(empty($tagihans)): ?>
          <tr><td colspan="8">
            <div class="empty-state">
              <div class="empty-state-icon">📋</div>
              <h4>Belum ada tagihan</h4>
              <p>Gunakan form Generate di atas untuk membuat tagihan</p>
            </div>
          </td></tr>
        <?php else: foreach($tagihans as $i=>$t):
          $bClass = $badgeMap[$t['status']] ?? 'badge-danger';
          $sIcon  = $statusIcon[$t['status']] ?? '⏳';
          $tSem   = (int)($t['semester'] ?? 0);
          $tTa    = $t['tahun_ajaran'] ?? '';
        ?>
          <tr data-trow="<?= $i ?>">
            <td><input type="checkbox" class="row-check" value="<?= $t['id'] ?>" onchange="updateHiddenCheckboxes()" style="cursor:pointer"></td>
            <td><div style="width:26px;height:26px;border-radius:8px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--text2)"><?= $i+1 ?></div></td>
            <td>
              <div style="font-weight:600;font-size:13.5px"><?= e($t['nama']) ?></div>
              <div style="font-size:11px;color:var(--text3)"><?= e($t['nis']) ?></div>
            </td>
            <td>
              <span class="pill pill-purple" style="font-size:11px"><?= e($t['kelas']) ?></span>
              <?php if(!empty($t['jurusan'])): ?><span class="pill pill-blue" style="font-size:11px"><?= e($t['jurusan']) ?></span><?php endif ?>
            </td>
            <td>
              <?php if($tSem): ?>
              <div style="display:flex;flex-direction:column;gap:2px">
                <span style="background:<?= $tSem===1?'#ECFDF5':'#EFF6FF' ?>;color:<?= $tSem===1?'#059669':'#2563EB' ?>;border-radius:6px;padding:2px 8px;font-size:11px;font-weight:700;display:inline-block">
                  <?= $tSem===1?'📗 Ganjil':'📘 Genap' ?>
                </span>
                <?php if($tTa): ?><span style="font-size:11px;color:var(--text3)"><?= e($tTa) ?></span><?php endif ?>
              </div>
              <?php else: ?><span style="color:var(--text3);font-size:12px">—</span><?php endif ?>
            </td>
            <td><span style="font-family:'DM Mono',monospace;font-weight:700;color:var(--text);font-size:14px"><?= rupiah($t['nominal']) ?></span></td>
            <td><span class="badge <?= $bClass ?>"><?= $sIcon ?> <?= ucfirst(str_replace('_',' ',$t['status'])) ?></span></td>
            <td>
              <div style="display:flex;gap:6px;flex-wrap:wrap">
                <button type="button" onclick="bukaModalEdit(<?= $t['id'] ?>, '<?= addslashes($t['nama']) ?>', <?= $t['nominal'] ?>)"
                        style="padding:5px 10px;border:1.5px solid #0D9488;border-radius:8px;background:#F0FDFA;color:#134E4A;font-size:12px;font-weight:600;cursor:pointer">✏️ Edit</button>
                <?php if($t['status']!=='lunas'): ?>
                <a href="index.php?page=pembayaran&siswa_id=<?= $t['siswa_id'] ?>&bulan=<?= $t['bulan'] ?>&tahun=<?= $t['tahun'] ?>">
                  <button class="btn btn-primary btn-sm">💳 Bayar</button>
                </a>
                <?php else: ?>
                  <span style="color:var(--text3);font-size:12px;font-weight:500">✅ Lunas</span>
                <?php endif ?>
              </div>
            </td>
          </tr>
        <?php endforeach; endif ?>
        </tbody>
      </table>
    </div>
    <div id="pager-tagihan-table"></div>
  </div>

  <!-- CARD VIEW -->
  <div id="tagihan-view-cards">
    <?php if(empty($tagihans)): ?>
      <div style="padding:32px"><div class="empty-state"><div class="empty-state-icon">📋</div><h4>Belum ada tagihan</h4><p>Gunakan form Generate di atas</p></div></div>
    <?php else: ?>
    <div class="tagihan-cards-scroll-wrap">
      <div class="tagihan-cards" id="tagihan-cards-grid">
        <?php foreach($tagihans as $i=>$t):
          $st = $t['status']; $barClr = $statusBarColor[$st]??'#94A3B8';
          $sIcon = $statusIcon[$st]??'⏳'; $sLabel=$statusLabel[$st]??ucfirst(str_replace('_',' ',$st));
          $bClass=$badgeMap[$st]??'badge-danger';
          $tSem=(int)($t['semester']??0); $tTa=$t['tahun_ajaran']??'';
        ?>
        <div class="tagihan-card" data-tcard="<?= $i ?>" style="animation-delay:<?= $i*28 ?>ms">
          <div class="tagihan-card-bar" style="background:<?= $barClr ?>"></div>
          <div class="tagihan-card-body">
            <input type="checkbox" class="tagihan-card-check row-check" value="<?= $t['id'] ?>" onchange="updateHiddenCheckboxes()">
            <div class="tagihan-card-top">
              <div style="width:26px;height:26px;border-radius:7px;background:var(--surface2);display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;color:var(--text2);flex-shrink:0"><?= $i+1 ?></div>
              <div style="flex:1;min-width:0">
                <div class="tagihan-card-name"><?= e($t['nama']) ?></div>
                <div class="tagihan-card-nis"><?= e($t['nis']) ?></div>
              </div>
              <span class="badge <?= $bClass ?>" style="font-size:10.5px;padding:2px 7px;flex-shrink:0"><?= $sIcon ?> <?= $sLabel ?></span>
            </div>
            <hr class="tagihan-card-hr">
            <div class="tagihan-card-rows">
              <div class="tagihan-card-row">
                <span class="tagihan-card-row-label">🏫 Kelas</span>
                <div style="display:flex;gap:4px">
                  <span class="pill pill-purple" style="font-size:11px;padding:2px 8px"><?= e($t['kelas']) ?></span>
                  <?php if(!empty($t['jurusan'])): ?><span class="pill pill-blue" style="font-size:11px;padding:2px 8px"><?= e($t['jurusan']) ?></span><?php endif ?>
                </div>
              </div>
              <?php if($tSem): ?>
              <div class="tagihan-card-row">
                <span class="tagihan-card-row-label">📚 Semester</span>
                <div style="display:flex;flex-direction:column;align-items:flex-end;gap:2px">
                  <span style="background:<?= $tSem===1?'#ECFDF5':'#EFF6FF' ?>;color:<?= $tSem===1?'#059669':'#2563EB' ?>;border-radius:6px;padding:2px 8px;font-size:11px;font-weight:700">
                    <?= $tSem===1?'📗 Ganjil':'📘 Genap' ?>
                  </span>
                  <?php if($tTa): ?><span style="font-size:10.5px;color:var(--text3)"><?= e($tTa) ?></span><?php endif ?>
                </div>
              </div>
              <?php endif ?>
              <div class="tagihan-card-row">
                <span class="tagihan-card-row-label">💳 Nominal SPP</span>
                <span class="tagihan-card-nominal"><?= rupiah($t['nominal']) ?></span>
              </div>
              <div class="tagihan-card-row">
                <span class="tagihan-card-row-label">📅 Periode</span>
                <span style="font-size:12px;color:var(--text2)"><?= bulanIndo($t['bulan']).' '.$t['tahun'] ?></span>
              </div>
            </div>
          </div>
          <div class="tagihan-card-footer">
            <button type="button" onclick="bukaModalEdit(<?= $t['id'] ?>, '<?= addslashes($t['nama']) ?>', <?= $t['nominal'] ?>)"
                    style="padding:7px;border:1.5px solid #0D9488;border-radius:9px;background:#F0FDFA;color:#134E4A;font-size:11.5px;font-weight:600;cursor:pointer;text-align:center">✏️ Edit</button>
            <?php if($t['status']!=='lunas'): ?>
            <a href="index.php?page=pembayaran&siswa_id=<?= $t['siswa_id'] ?>&bulan=<?= $t['bulan'] ?>&tahun=<?= $t['tahun'] ?>" style="display:flex">
              <button class="btn btn-primary btn-sm" style="width:100%;font-size:11.5px">💳 Bayar</button>
            </a>
            <?php else: ?>
            <div style="display:flex;align-items:center;justify-content:center;background:#D1FAE5;border-radius:9px;font-size:12px;font-weight:600;color:#065F46">✅ Lunas</div>
            <?php endif ?>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <div id="pager-tagihan-cards"></div>
    <?php endif; ?>
  </div>
</div>

<script>
/* ════ Data semester & bulan ════ */
const bulanSemester = {
  1: [7,8,9,10,11,12],
  2: [1,2,3,4,5,6]
};
const bulanNama = ['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'];
const daftarJurusan = <?= json_encode(
    array_map(fn($jList) => array_values($jList), $daftarJurusan),
    JSON_UNESCAPED_UNICODE
) ?>;

/* ════ Set semester aktif ════ */
function setSemester(s) {
  document.getElementById('hidSemester').value = s;
  document.getElementById('semPill1').classList.toggle('active', s===1);
  document.getElementById('semPill2').classList.toggle('active', s===2);
  syncBulanTahun();
}

/* ════ Sync bulan/tahun saat semester / tahun ajaran berubah ════ */
function syncBulanTahun() {
  var s  = parseInt(document.getElementById('hidSemester').value) || 1;
  var ta = getAktifTahunAjaran();
  if (!ta) return;

  var parts = ta.split('/');
  var tAwal = parseInt(parts[0]);
  var tAkhir = parseInt(parts[1]);

  /* Bulan pertama semester ini */
  var bulanList = bulanSemester[s];
  var selBulan  = document.getElementById('selBulanGen');
  selBulan.innerHTML = '';
  bulanList.forEach(function(b) {
    var opt = document.createElement('option');
    opt.value = b;
    opt.textContent = bulanNama[b];
    selBulan.appendChild(opt);
  });
  selBulan.value = bulanList[0];

  /* Tahun: semester ganjil pakai tAwal, genap pakai tAkhir */
  var tahunTarget = (s === 1) ? tAwal : tAkhir;
  var selTahun = document.getElementById('selTahunGen');
  if (selTahun) selTahun.value = String(tahunTarget);

  /* Update info strip */
  updateSemInfo(s, ta);
}

function getAktifTahunAjaran() {
  var sel = document.getElementById('selTahunAjaran');
  if (sel.value === '_custom') {
    return document.getElementById('inputTahunAjaranCustom').value.trim();
  }
  return sel.value;
}

function updateSemInfo(s, ta) {
  var strip  = document.getElementById('semInfoStrip');
  var bList  = bulanSemester[s];
  var bNama  = bList.map(function(b){ return bulanNama[b]; }).join(', ');
  var smLbl  = s===1 ? 'Ganjil' : 'Genap';
  strip.innerHTML =
    '<span class="sem-info-badge">' + (s===1?'📗':'📘') + ' Semester ' + smLbl + '</span>'
    + '<span>Tahun Ajaran <strong>' + (ta||'—') + '</strong></span>'
    + '<span>·</span>'
    + '<span>Bulan: <strong>' + bNama + '</strong></span>';
}

/* ════ Pilih "Ketik Manual" ════ */
document.getElementById('selTahunAjaran').addEventListener('change', function() {
  var inp = document.getElementById('inputTahunAjaranCustom');
  if (this.value === '_custom') { inp.style.display=''; inp.focus(); }
  else { inp.style.display='none'; syncBulanTahun(); }
});

/* ════ Sync jurusan di form generate ════ */
function syncJurusanGen() {
  var kelas = document.getElementById('selKelasGen').value;
  var sel   = document.getElementById('selJurusanGen');
  var opts  = daftarJurusan[kelas] || [];
  sel.innerHTML = '<option value="">Semua Rombel</option>';
  opts.forEach(function(j) {
    var opt = document.createElement('option');
    opt.value = j; opt.textContent = kelas + ' ' + j;
    sel.appendChild(opt);
  });
}

/* ════ Konfirmasi generate ════ */
function konfirmasiGenerate() {
  var ta = getAktifTahunAjaran();
  if (!ta) { alert('⚠️ Pilih atau isi Tahun Ajaran terlebih dahulu'); return false; }
  if (!/^\d{4}\/\d{4}$/.test(ta)) { alert('⚠️ Format tahun ajaran harus seperti: 2024/2025'); return false; }
  if (document.getElementById('selTahunAjaran').value === '_custom') {
    document.getElementById('selTahunAjaran').insertAdjacentHTML('afterend',
      '<input type="hidden" name="tahun_ajaran_gen" value="'+ta+'">');
    document.getElementById('selTahunAjaran').name = '_ta_orig';
  }
  var s    = parseInt(document.getElementById('hidSemester').value);
  var kels = document.getElementById('selKelasGen').value;
  var smLbl = s===1?'Ganjil':'Genap';
  var klsLbl = kels ? ' (Kelas '+kels+')' : ' (Semua Kelas)';
  return confirm('Generate tagihan Semester '+smLbl+' TA '+ta+klsLbl+'?\nTagihan duplikat per siswa per bulan akan dilewati (INSERT IGNORE).');
}

/* ════ Init sync ════ */
(function() {
  var initSem = <?= $semester ?: 1 ?>;
  var initTa  = '<?= e($tahunAjaran) ?>';
  updateSemInfo(initSem, initTa);
  syncJurusanGen();
})();

/* ════ State paginasi ════ */
var tagihanPerPage = parseInt(localStorage.getItem('tagihan_per_page') || '10');
(function() { var s=document.getElementById('tagihanPerPage'); if(s) s.value=String(tagihanPerPage); })();
window.tagihanOnPerPage = function(v) { tagihanPerPage=parseInt(v); localStorage.setItem('tagihan_per_page',v); renderTagihanTable(0); renderTagihanCards(0); };

/* ════ View Toggle ════ */
(function() {
  var saved = localStorage.getItem('tagihan_view')||'table';
  applyView(saved);
  function applyView(m) {
    var isTbl = m==='table';
    document.getElementById('tagihan-view-table').style.display = isTbl?'flex':'none';
    document.getElementById('tagihan-view-cards').style.display = isTbl?'none':'flex';
    document.getElementById('tagihan-btn-table').classList.toggle('active', isTbl);
    document.getElementById('tagihan-btn-cards').classList.toggle('active',!isTbl);
    updateHiddenCheckboxes();
  }
  window.tagihanSwitchView = function(m) { localStorage.setItem('tagihan_view',m); applyView(m); renderTagihanTable(0); renderTagihanCards(0); };
})();

/* ════ Render + pager ════ */
function renderTagihanTable(p) {
  var rows=document.querySelectorAll('#tagihan-tbody tr[data-trow]'); var total=rows.length; if(!total) return;
  var start=p*tagihanPerPage;
  rows.forEach(function(r,i){ r.style.display=(i>=start&&i<start+tagihanPerPage)?'':'none'; });
  var tw=document.querySelector('.tagihan-table-scroll-wrap'); if(tw&&p>0) tw.scrollTop=0;
  buildTagihanPager('pager-tagihan-table',total,tagihanPerPage,p,renderTagihanTable);
}
function renderTagihanCards(p) {
  var cards=document.querySelectorAll('#tagihan-cards-grid .tagihan-card[data-tcard]'); var total=cards.length; if(!total) return;
  var start=p*tagihanPerPage;
  cards.forEach(function(c,i){ c.style.display=(i>=start&&i<start+tagihanPerPage)?'':'none'; });
  var sw=document.querySelector('.tagihan-cards-scroll-wrap'); if(sw&&p>0) sw.scrollTop=0;
  buildTagihanPager('pager-tagihan-cards',total,tagihanPerPage,p,renderTagihanCards);
}
function buildTagihanPager(id,total,pp,cur,cb) {
  var w=document.getElementById(id); if(!w) return;
  var tp=Math.ceil(total/pp); if(tp<=1){w.innerHTML='';return;}
  var from=cur*pp+1, to=Math.min((cur+1)*pp,total);
  var h='<div class="tagihan-pager"><span class="tagihan-pager-info">Menampilkan <b>'+from+'–'+to+'</b> dari <b>'+total+'</b> tagihan</span><div class="tagihan-pager-btns">';
  h+='<button class="tagihan-pager-btn'+(cur===0?' disabled':'')+'" data-p="'+(cur-1)+'"'+(cur===0?' disabled':'')+'>&#8249; Prev</button>';
  var s=Math.max(0,cur-2),e=Math.min(tp-1,cur+2);
  if(s>0){h+='<button class="tagihan-pager-btn" data-p="0">1</button>';if(s>1)h+='<span class="tagihan-pager-ellipsis">…</span>';}
  for(var i=s;i<=e;i++) h+='<button class="tagihan-pager-btn'+(i===cur?' active':'')+'" data-p="'+i+'">'+(i+1)+'</button>';
  if(e<tp-1){if(e<tp-2)h+='<span class="tagihan-pager-ellipsis">…</span>';h+='<button class="tagihan-pager-btn" data-p="'+(tp-1)+'">'+tp+'</button>';}
  h+='<button class="tagihan-pager-btn'+(cur===tp-1?' disabled':'')+'" data-p="'+(cur+1)+'"'+(cur===tp-1?' disabled':'')+'>Next &#8250;</button>';
  h+='</div></div>';
  w.innerHTML=h;
  w.querySelectorAll('.tagihan-pager-btn:not(.disabled)').forEach(function(b){ b.addEventListener('click',function(){cb(parseInt(this.dataset.p));}); });
}
renderTagihanTable(0); renderTagihanCards(0);

/* ════ Modal Edit Nominal ════ */
function bukaModalEdit(id,nama,nominal) {
  document.getElementById('inputTagihanId').value=id;
  document.getElementById('inputNominal').value=nominal;
  document.getElementById('modalNamaSiswa').textContent='👤 '+nama;
  document.getElementById('modalEditNominal').style.display='flex';
}
function tutupModal() { document.getElementById('modalEditNominal').style.display='none'; }
document.getElementById('modalEditNominal').addEventListener('click',function(e){ if(e.target===this) tutupModal(); });

/* ════ Checkbox massal ════ */
function toggleAll(cb) {
  document.querySelectorAll('#tagihan-tbody tr[data-trow]:not([style*="display: none"]) .row-check').forEach(function(c){ c.checked=cb.checked; });
  updateHiddenCheckboxes();
}
function pilihSemua() {
  var vc=document.querySelectorAll('#tagihan-tbody tr[data-trow]:not([style*="display: none"]) .row-check, #tagihan-cards-grid .tagihan-card[data-tcard]:not([style*="display: none"]) .row-check');
  var all=[...vc].every(function(c){return c.checked;});
  vc.forEach(function(c){c.checked=!all;});
  var ca=document.getElementById('checkAll'); if(ca) ca.checked=!all;
  updateHiddenCheckboxes();
}
function updateHiddenCheckboxes() {
  var c=document.getElementById('hiddenCheckboxes'); if(!c) return;
  c.innerHTML='';
  document.querySelectorAll('.row-check:checked').forEach(function(x){ var i=document.createElement('input'); i.type='hidden'; i.name='tagihan_ids[]'; i.value=x.value; c.appendChild(i); });
  var total=document.querySelectorAll('#tagihan-tbody tr[data-trow]:not([style*="display: none"]) .row-check').length;
  var checked=document.querySelectorAll('#tagihan-tbody tr[data-trow]:not([style*="display: none"]) .row-check:checked').length;
  var ca=document.getElementById('checkAll'); if(ca){ca.checked=total>0&&checked===total;ca.indeterminate=checked>0&&checked<total;}
}
function konfirmasiBulkEdit() {
  var ch=document.querySelectorAll('.row-check:checked').length;
  if(ch===0){alert('Pilih minimal 1 tagihan terlebih dahulu!');return false;}
  return confirm('Update nominal untuk '+ch+' tagihan?');
}
</script>

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