<?php
/**
 * Kwitansi Pembayaran SPP
 * URL: index.php?page=kwitansi&id=PEMBAYARAN_ID        (kwitansi satu transaksi)
 *      index.php?page=kwitansi&tagihan_id=TAGIHAN_ID   (rekap semua transaksi tagihan)
 *      index.php?page=kwitansi&id=X&print=a5           (auto-print A5)
 *      index.php?page=kwitansi&id=X&print=a6           (auto-print A6)
 */

// ── Auth ──────────────────────────────────────────────────────────
if (!isset($_SESSION['admin_id'])) {
    header('Location: index.php?page=login'); exit;
}

// ── Deteksi ukuran cetak ──────────────────────────────────────────
$printSize  = strtolower(trim($_GET['print'] ?? ''));
$validSizes = ['a5', 'a6'];
if (!in_array($printSize, $validSizes)) $printSize = '';
$autoPrint  = ($printSize !== '');

// ── Ambil data sekolah ────────────────────────────────────────────
$setting = [];
try {
    $sRows = $pdo->query("SELECT kunci,nilai FROM pengaturan")->fetchAll();
    foreach ($sRows as $sr) $setting[$sr['kunci']] = $sr['nilai'];
} catch (Exception $e) {}

$namaSekolah   = $setting['nama_sekolah']   ?? 'SPP Sekolah';
$alamatSekolah = $setting['alamat_sekolah'] ?? '';
$telpSekolah   = $setting['telp_sekolah']   ?? '';
$namaKepsek    = $setting['nama_kepsek']    ?? '';
$nipKepsek     = $setting['nip_kepsek']     ?? '';
$tahunAjaran   = $setting['tahun_ajaran']   ?? date('Y').'/'.(date('Y')+1);

$rootDir  = str_replace('\\', '/', dirname(__DIR__));
$logoFile = $setting['logo_sekolah'] ?? '';
$logoUrl  = ($logoFile && file_exists($rootDir.'/uploads/logo/'.$logoFile))
            ? 'uploads/logo/'.$logoFile : null;

// ── Mode: single pembayaran atau semua transaksi satu tagihan ─────
$bayarId   = (int)($_GET['id']         ?? 0);
$tagihanId = (int)($_GET['tagihan_id'] ?? 0);

$pembayaranList = [];
$tagihan = null;
$siswa   = null;

$selectFields = "p.*,
    COALESCE(p.tanggal_bayar, p.created_at) AS tgl_bayar,
    t.id AS t_id, t.bulan, t.tahun, t.nominal, t.status AS status_tagihan,
    s.nama, s.nis, s.kelas, s.jurusan, s.alamat, s.no_hp,
    a.nama_lengkap AS nama_admin";

if ($bayarId) {
    $st = $pdo->prepare(
        "SELECT $selectFields
         FROM pembayaran p
         JOIN tagihan_spp t ON p.tagihan_id = t.id
         JOIN siswa s       ON p.siswa_id   = s.id
         LEFT JOIN admin a  ON p.admin_id   = a.id
         WHERE p.id = ? LIMIT 1"
    );
    $st->execute([$bayarId]);
    $row = $st->fetch();
    if ($row) {
        $pembayaranList[] = $row;
        $tagihan = [
            'id'     => $row['t_id'],
            'bulan'  => $row['bulan'],
            'tahun'  => $row['tahun'],
            'nominal'=> $row['nominal'],
            'status' => $row['status_tagihan'],
        ];
        $siswa = [
            'nama'    => $row['nama'],
            'nis'     => $row['nis'],
            'kelas'   => $row['kelas'],
            'jurusan' => $row['jurusan'],
            'alamat'  => $row['alamat'],
            'no_hp'   => $row['no_hp'],
        ];
    }
} elseif ($tagihanId) {
    $st = $pdo->prepare(
        "SELECT $selectFields
         FROM pembayaran p
         JOIN tagihan_spp t ON p.tagihan_id = t.id
         JOIN siswa s       ON p.siswa_id   = s.id
         LEFT JOIN admin a  ON p.admin_id   = a.id
         WHERE p.tagihan_id = ?
         ORDER BY COALESCE(p.tanggal_bayar, p.created_at) ASC"
    );
    $st->execute([$tagihanId]);
    $rows = $st->fetchAll();
    if ($rows) {
        $pembayaranList = $rows;
        $r0 = $rows[0];
        $tagihan = [
            'id'     => $tagihanId,
            'bulan'  => $r0['bulan'],
            'tahun'  => $r0['tahun'],
            'nominal'=> $r0['nominal'],
            'status' => $r0['status_tagihan'],
        ];
        $siswa = [
            'nama'    => $r0['nama'],
            'nis'     => $r0['nis'],
            'kelas'   => $r0['kelas'],
            'jurusan' => $r0['jurusan'],
            'alamat'  => $r0['alamat'],
            'no_hp'   => $r0['no_hp'],
        ];
    }
}

if (empty($pembayaranList)) {
    echo '<div style="font-family:sans-serif;text-align:center;padding:60px;color:#888">
            <h3>Data pembayaran tidak ditemukan</h3>
            <a href="javascript:history.back()" style="color:#4F6EF7">← Kembali</a>
          </div>';
    exit;
}

$totalBayar = array_sum(array_column($pembayaranList, 'jumlah_bayar'));
$sisaBayar  = max(0, (int)$tagihan['nominal'] - $totalBayar);
$isLunas    = ($tagihan['status'] === 'lunas');

// ── Nomor kwitansi ────────────────────────────────────────────────
if ($bayarId) {
    $noKwitansi = 'KW-'.date('Ymd').'-'.str_pad($tagihan['id'],4,'0',STR_PAD_LEFT).'-'.str_pad($bayarId,4,'0',STR_PAD_LEFT);
} else {
    $noKwitansi = 'KW-'.date('Ymd').'-T'.str_pad($tagihanId,4,'0',STR_PAD_LEFT);
}

$tglCetak        = date('d').' '.bulanIndo((int)date('n')).' '.date('Y');
$tglBayarPertama = $pembayaranList[0]['tgl_bayar'];
$tglBayarTampil  = date('d', strtotime($tglBayarPertama))
    .' '.bulanIndo((int)date('m', strtotime($tglBayarPertama)))
    .' '.date('Y', strtotime($tglBayarPertama));

// ── Hitung kolom tabel ────────────────────────────────────────────
$adaKolomRekening = false;
foreach ($pembayaranList as $p) {
    if (!empty($p['no_rekening'])) { $adaKolomRekening = true; break; }
}
$jumlahKolom  = 6 + ($adaKolomRekening ? 1 : 0);
$colspanTotal = $jumlahKolom - 1;

// ── Base URL untuk tombol cetak ───────────────────────────────────
$baseUrl = 'index.php?page=kwitansi&'.($bayarId ? 'id='.$bayarId : 'tagihan_id='.$tagihanId);

// ── Fungsi terbilang ──────────────────────────────────────────────
function terbilang($n) {
    $n = abs((int)$n);
    $satuan = ['','satu','dua','tiga','empat','lima','enam','tujuh','delapan','sembilan',
               'sepuluh','sebelas','dua belas','tiga belas','empat belas','lima belas',
               'enam belas','tujuh belas','delapan belas','sembilan belas'];
    if ($n === 0) return 'nol';
    if ($n < 20)  return $satuan[$n];
    if ($n < 100) {
        $p = (int)($n / 10);
        $s = $n % 10;
        return ($p === 1 ? 'sepuluh' : $satuan[$p].' puluh').($s ? ' '.$satuan[$s] : '');
    }
    if ($n < 1000) {
        $r = (int)($n/100) === 1 ? 'seratus' : terbilang((int)($n/100)).' ratus';
        return $r.($n%100 ? ' '.terbilang($n%100) : '');
    }
    if ($n < 1000000) {
        $r = (int)($n/1000) === 1 ? 'seribu' : terbilang((int)($n/1000)).' ribu';
        return $r.($n%1000 ? ' '.terbilang($n%1000) : '');
    }
    if ($n < 1000000000) {
        $r = terbilang((int)($n/1000000)).' juta';
        return $r.($n%1000000 ? ' '.terbilang($n%1000000) : '');
    }
    $r = terbilang((int)($n/1000000000)).' miliar';
    return $r.($n%1000000000 ? ' '.terbilang($n%1000000000) : '');
}
$terbilangBayar = ucfirst(terbilang($totalBayar)).' rupiah';
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Kwitansi SPP — <?= e($siswa['nama']) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,wght@9..40,400;9..40,500;9..40,600;9..40,700&family=DM+Mono:wght@400;500&family=Fraunces:opsz,wght@9..144,600;9..144,700&display=swap" rel="stylesheet">
<style>
/* ═══════════════════════════════════
   SCREEN STYLES
═══════════════════════════════════ */
:root {
  --navy:   #1E2D4E;
  --indigo: #4F6EF7;
  --green:  #16A34A;
  --text:   #1A2035;
  --text2:  #5A6A8A;
  --text3:  #9AAAC8;
  --border: #E2E8F4;
  --bg:     #F4F6FB;
}

* { box-sizing:border-box; margin:0; padding:0; }
body {
  font-family:'DM Sans',sans-serif;
  background: var(--bg);
  color: var(--text);
  min-height: 100vh;
  padding: 20px;
}

/* ── Toolbar ── */
.toolbar {
  max-width: 800px; margin: 0 auto 20px;
  display: flex; align-items: center; justify-content: space-between;
  flex-wrap: wrap; gap: 10px;
}
.toolbar-left { display:flex;align-items:center;gap:8px;flex-wrap:wrap; }
.btn {
  display:inline-flex;align-items:center;gap:7px;
  padding:9px 18px;border-radius:8px;font-size:13px;
  font-weight:600;cursor:pointer;border:none;
  font-family:'DM Sans',sans-serif;transition:all .18s;
  text-decoration:none;
}
.btn-print-a5 {
  background:linear-gradient(135deg,#16A34A,#22C55E);
  color:#fff;box-shadow:0 4px 14px rgba(34,197,94,.35);
}
.btn-print-a5:hover { filter:brightness(1.07);transform:translateY(-1px); }
.btn-print-a6 {
  background:linear-gradient(135deg,#4F6EF7,#6B8EFF);
  color:#fff;box-shadow:0 4px 14px rgba(79,110,247,.35);
}
.btn-print-a6:hover { filter:brightness(1.07);transform:translateY(-1px); }
.btn-back {
  background:#fff;color:var(--text2);
  border:1.5px solid var(--border);
}
.btn-back:hover { background:var(--bg);color:var(--text); }
.btn svg { width:15px;height:15px; }

.kw-mode-badge {
  font-size:11.5px;
  background:#EFF6FF;color:#1E40AF;
  border:1px solid #BFDBFE;
  border-radius:99px;padding:4px 12px;
  font-weight:600;
}

/* ── Kwitansi wrapper ── */
.kwitansi-wrap {
  max-width: 800px; margin: 0 auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(30,45,78,.12);
  overflow: hidden;
}

/* ── Header sekolah ── */
.kw-header {
  background: linear-gradient(135deg, var(--navy) 0%, #2E4478 100%);
  padding: 24px 32px 20px;
  display: flex; align-items: center; gap: 18px;
  position: relative; overflow: hidden;
}
.kw-header::before {
  content:''; position:absolute; top:-40px; right:-40px;
  width:160px;height:160px;border-radius:50%;
  background:rgba(79,110,247,.2); pointer-events:none;
}
.kw-header::after {
  content:''; position:absolute; bottom:-30px; left:30%;
  width:120px;height:120px;border-radius:50%;
  background:rgba(96,165,250,.12); pointer-events:none;
}
.kw-logo {
  width:64px;height:64px;border-radius:14px;
  background:rgba(255,255,255,.15);
  display:flex;align-items:center;justify-content:center;
  overflow:hidden;flex-shrink:0;position:relative;z-index:1;
  border:2px solid rgba(255,255,255,.2);
}
.kw-logo img { width:100%;height:100%;object-fit:contain;padding:5px; }
.kw-logo-fallback { color:rgba(255,255,255,.7); }
.kw-logo-fallback svg { width:32px;height:32px; }
.kw-sekolah { flex:1; position:relative;z-index:1; }
.kw-nama-sekolah {
  font-family:'Fraunces',serif;
  font-size:20px;font-weight:700;color:#fff;
  letter-spacing:-.2px;line-height:1.2;
}
.kw-alamat { font-size:11.5px;color:rgba(255,255,255,.6);margin-top:4px;line-height:1.5; }
.kw-badge {
  position:relative;z-index:1;
  background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);
  border-radius:10px;padding:10px 16px;text-align:center;flex-shrink:0;
}
.kw-badge-label { font-size:9.5px;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:rgba(255,255,255,.5); }
.kw-badge-val { font-family:'DM Mono',monospace;font-size:13px;font-weight:500;color:#fff;margin-top:2px; }

/* ── Judul kwitansi ── */
.kw-title-bar {
  background: linear-gradient(90deg, #EEF1FF, #F0F4FF);
  border-bottom: 2px solid #C7D2FE;
  padding: 14px 32px;
  display: flex; align-items: center; justify-content: space-between;
}
.kw-title {
  font-family:'Fraunces',serif;
  font-size:18px;font-weight:700;color:var(--navy);
  letter-spacing:.5px;text-transform:uppercase;
}
.kw-no { font-family:'DM Mono',monospace;font-size:13px;color:var(--indigo);font-weight:500; }

/* ── Status badge ── */
.kw-status {
  display:inline-flex;align-items:center;gap:5px;
  padding:4px 12px;border-radius:99px;
  font-size:12px;font-weight:700;
}
.kw-status.lunas   { background:#DCFCE7;color:#15803D;border:1px solid #BBF7D0; }
.kw-status.cicilan { background:#FEF3C7;color:#B45309;border:1px solid #FDE68A; }
.kw-status.belum   { background:#FEE2E2;color:#B91C1C;border:1px solid #FECACA; }

/* ── Body ── */
.kw-body { padding: 24px 32px; }

/* ── Info grid ── */
.kw-info-grid {
  display: grid; grid-template-columns: 1fr 1fr; gap: 0;
  border: 1.5px solid var(--border); border-radius: 10px;
  overflow: hidden; margin-bottom: 22px;
}
.kw-info-row {
  display: flex; align-items: stretch;
  border-bottom: 1px solid var(--border);
}
.kw-info-row:last-child { border-bottom: none; }
.kw-info-cell { flex:1; display:flex; align-items:stretch; }
.kw-info-cell:first-child { border-right: 1px solid var(--border); }
.kw-info-label {
  min-width:130px;flex-shrink:0;
  background:#F8FAFF;
  padding:10px 14px;
  font-size:11.5px;font-weight:700;color:var(--text2);
  text-transform:uppercase;letter-spacing:.5px;
  border-right:1px solid var(--border);
  display:flex;align-items:center;
}
.kw-info-val {
  padding:10px 14px;font-size:13px;color:var(--text);
  font-weight:500;display:flex;align-items:center;flex:1;
}

/* ── Tabel pembayaran ── */
.kw-table-title {
  font-size:12px;font-weight:700;text-transform:uppercase;
  letter-spacing:.7px;color:var(--text2);margin-bottom:8px;
  display:flex;align-items:center;gap:6px;
}
.kw-table-title svg { width:14px;height:14px; }
table.kw-tbl { width:100%;border-collapse:collapse;margin-bottom:16px; }
.kw-tbl thead tr { background:#F0F4FF; }
.kw-tbl th {
  padding:9px 12px;text-align:left;
  font-size:11px;font-weight:700;text-transform:uppercase;
  letter-spacing:.6px;color:var(--text2);
  border-bottom:2px solid #C7D2FE;
}
.kw-tbl td { padding:10px 12px;font-size:13px;color:var(--text);border-bottom:1px solid var(--border); }
.kw-tbl tbody tr:last-child td { border-bottom:none; }
.kw-tbl .num { font-family:'DM Mono',monospace;font-weight:500;letter-spacing:-.3px; }
.kw-tbl-total td {
  padding:10px 12px;background:#EEF1FF;font-weight:700;
  font-size:13px;border-top:2px solid #C7D2FE;
}

/* ── Terbilang box ── */
.kw-terbilang {
  background: linear-gradient(135deg,#F0FDF4,#DCFCE7);
  border: 1.5px solid #BBF7D0; border-radius:10px;
  padding: 12px 16px; margin-bottom: 22px;
  display:flex;align-items:flex-start;gap:10px;
}
.kw-terbilang-label { font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:#16A34A;flex-shrink:0;padding-top:2px; }
.kw-terbilang-val { font-size:13.5px;font-weight:600;color:#15803D;font-style:italic;line-height:1.5; }

/* ── Keterangan sisa ── */
.kw-sisa {
  background:#FEF3C7;border:1.5px solid #FDE68A;
  border-radius:10px;padding:10px 16px;margin-bottom:22px;
  display:flex;align-items:center;gap:8px;font-size:13px;
}

/* ── Tanda tangan ── */
.kw-ttd { display:flex;justify-content:flex-end;margin-top:8px; }
.kw-ttd-box { text-align:center; }
.kw-ttd-loc { font-size:12.5px;color:var(--text2); }
.kw-ttd-jabatan { font-size:13px;font-weight:600;color:var(--text);margin-top:2px; }
.kw-ttd-space { height:64px; }
.kw-ttd-nama { font-size:13.5px;font-weight:700;color:var(--text);border-top:1.5px solid var(--border);padding-top:5px; }
.kw-ttd-nip { font-size:11px;color:var(--text3);margin-top:2px;font-family:'DM Mono',monospace; }

/* ── Footer kwitansi ── */
.kw-footer {
  background:#F8FAFF;border-top:1.5px solid var(--border);
  padding:12px 32px;
  display:flex;align-items:center;justify-content:space-between;
  font-size:11px;color:var(--text3);
}
.kw-footer-brand { display:flex;align-items:center;gap:5px;font-weight:600;color:var(--text2); }
.kw-footer-brand svg { width:12px;height:12px; }

/* ── Watermark lunas ── */
.kw-watermark {
  position:absolute;top:50%;left:50%;
  transform:translate(-50%,-50%) rotate(-35deg);
  font-family:'Fraunces',serif;
  font-size:96px;font-weight:700;
  color:rgba(34,197,94,.07);
  letter-spacing:8px;
  pointer-events:none;white-space:nowrap;user-select:none;
}

/* ── Ukuran cetak badge di toolbar ── */
.print-size-info {
  font-size:11.5px;background:#F0FDF4;color:#15803D;
  border:1px solid #BBF7D0;border-radius:99px;
  padding:4px 12px;font-weight:600;
  display:flex;align-items:center;gap:5px;
}

/* ═══════════════════════════════════
   PRINT BASE (shared)
═══════════════════════════════════ */
@media print {
  body { background:#fff;padding:0; }
  .toolbar { display:none !important; }
  .kwitansi-wrap { box-shadow:none;border-radius:0;max-width:100%;margin:0; }
  * { -webkit-print-color-adjust:exact;print-color-adjust:exact; }
}

/* ═══════════════════════════════════
   PRINT: A5 Portrait (148×210mm)
   Aktif saat ?print=a5
═══════════════════════════════════ */
<?php if ($printSize === 'a5' || $printSize === ''): /* default fallback A5 jika tidak ada print param */ ?>
@media print {
  @page { size: A5 portrait; margin: 8mm 10mm; }

  .kw-header { padding:14px 20px 12px; gap:14px; }
  .kw-logo   { width:48px;height:48px;border-radius:10px; }
  .kw-nama-sekolah { font-size:14px; }
  .kw-alamat { font-size:10px; }
  .kw-badge  { padding:8px 12px; }
  .kw-badge-label { font-size:8px; }
  .kw-badge-val   { font-size:11px; }
  .kw-title-bar { padding:9px 20px; }
  .kw-title { font-size:13px; }
  .kw-no    { font-size:11px; }
  .kw-body  { padding:14px 20px; }

  .kw-info-grid { grid-template-columns:1fr; margin-bottom:12px; }
  .kw-info-row  { flex-direction:column; }
  .kw-info-cell:first-child { border-right:none;border-bottom:1px solid #E2E8F4; }
  .kw-info-label { min-width:100px;padding:6px 10px;font-size:9.5px; }
  .kw-info-val   { padding:6px 10px;font-size:11px; }

  .kw-table-title { font-size:10px;margin-bottom:5px; }
  .kw-tbl th { font-size:9px;padding:5px 8px; }
  .kw-tbl td { font-size:10.5px;padding:6px 8px; }
  .kw-tbl-total td { font-size:11px;padding:6px 8px; }
  .kw-terbilang { padding:8px 12px;margin-bottom:14px;gap:8px; }
  .kw-terbilang-label { font-size:9px; }
  .kw-terbilang-val   { font-size:11px; }
  .kw-sisa { font-size:11px;padding:8px 12px;margin-bottom:12px; }
  .kw-ttd-space { height:40px; }
  .kw-ttd-loc { font-size:11px; }
  .kw-ttd-jabatan { font-size:11px; }
  .kw-ttd-nama { font-size:11px; }
  .kw-ttd-nip  { font-size:9px; }
  .kw-footer { padding:8px 20px;font-size:10px; }
  .kw-watermark { font-size:80px; }
}
<?php endif ?>

/* ═══════════════════════════════════
   PRINT: A6 Portrait (105×148mm)
   Aktif saat ?print=a6
═══════════════════════════════════ */
<?php if ($printSize === 'a6'): ?>
@media print {
  @page { size: A6 portrait; margin: 5mm 7mm; }

  .kw-header { padding:9px 13px 8px;gap:9px; }
  .kw-logo   { width:34px;height:34px;border-radius:7px; }
  .kw-nama-sekolah { font-size:10.5px; }
  .kw-alamat { font-size:8px;margin-top:2px; }
  .kw-badge  { padding:5px 9px; }
  .kw-badge-label { font-size:7px;letter-spacing:.6px; }
  .kw-badge-val   { font-size:9px;margin-top:1px; }
  .kw-title-bar { padding:6px 13px; }
  .kw-title { font-size:9.5px;letter-spacing:.2px; }
  .kw-no    { font-size:8.5px; }
  .kw-status { font-size:8px;padding:2px 6px; }
  .kw-body  { padding:9px 13px; }

  .kw-info-grid { grid-template-columns:1fr;margin-bottom:9px; }
  .kw-info-row  { flex-direction:column; }
  .kw-info-cell:first-child { border-right:none;border-bottom:1px solid #E2E8F4; }
  .kw-info-label { min-width:75px;padding:4px 8px;font-size:7.5px; }
  .kw-info-val   { padding:4px 8px;font-size:9px; }

  .kw-table-title { font-size:7.5px;margin-bottom:3px; }
  .kw-tbl th { font-size:7px;padding:3px 5px; }
  .kw-tbl td { font-size:8.5px;padding:4px 5px; }
  .kw-tbl-total td { font-size:9px;padding:4px 5px; }
  .kw-terbilang { padding:5px 9px;margin-bottom:9px;gap:5px; }
  .kw-terbilang-label { font-size:7.5px; }
  .kw-terbilang-val   { font-size:8.5px; }
  .kw-sisa { font-size:8px;padding:5px 9px;margin-bottom:9px; }
  .kw-ttd-space { height:24px; }
  .kw-ttd-loc { font-size:8.5px; }
  .kw-ttd-jabatan { font-size:8.5px; }
  .kw-ttd-nama { font-size:8.5px; }
  .kw-ttd-nip  { font-size:7.5px; }
  .kw-footer { padding:5px 13px;font-size:7.5px; }
  .kw-watermark { font-size:52px; }
}
<?php endif ?>
</style>

<?php if ($autoPrint): ?>
<!-- Auto-print saat dibuka via ?print= -->
<script>window.addEventListener('load', function(){ setTimeout(function(){ window.print(); }, 700); });</script>
<?php endif ?>
</head>
<body>

<!-- ══════════════════════════════════════
     TOOLBAR (screen only)
══════════════════════════════════════ -->
<div class="toolbar">
  <div class="toolbar-left">
    <a href="javascript:history.back()" class="btn btn-back">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
      Kembali
    </a>
    <span style="font-size:13.5px;font-weight:600;color:var(--text)">
      Kwitansi SPP &mdash; <?= e($siswa['nama']) ?>
    </span>
    <span class="kw-mode-badge">
      <?= $bayarId ? '1 transaksi' : count($pembayaranList).' transaksi (rekap)' ?>
    </span>
    <?php if ($bayarId && !empty($tagihan['id'])): ?>
    <a href="index.php?page=kwitansi&tagihan_id=<?= $tagihan['id'] ?>"
       class="btn btn-back" style="font-size:12px">
       📋 Rekap Tagihan
    </a>
    <?php endif ?>
  </div>

  <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
    <!-- Badge status -->
    <?php if ($isLunas): ?>
    <span style="font-size:12px;background:#DCFCE7;color:#15803D;border:1px solid #BBF7D0;border-radius:99px;padding:5px 14px;font-weight:700">
      ✅ LUNAS
    </span>
    <?php elseif ($tagihan['status'] === 'cicilan'): ?>
    <span style="font-size:12px;background:#FEF3C7;color:#B45309;border:1px solid #FDE68A;border-radius:99px;padding:5px 14px;font-weight:700">
      🔄 CICILAN
    </span>
    <?php else: ?>
    <span style="font-size:12px;background:#FEE2E2;color:#B91C1C;border:1px solid #FECACA;border-radius:99px;padding:5px 14px;font-weight:700">
      ⏳ BELUM LUNAS
    </span>
    <?php endif ?>

    <!-- Tombol Cetak A5 -->
    <a href="<?= $baseUrl ?>&print=a5" target="_blank" class="btn btn-print-a5"
       title="Cetak ukuran A5 (148×210mm) — Arsip sekolah">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
      Cetak A5
    </a>

    <!-- Tombol Cetak A6 -->
    <a href="<?= $baseUrl ?>&print=a6" target="_blank" class="btn btn-print-a6"
       title="Cetak ukuran A6 (105×148mm) — Slip siswa">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
      Cetak A6
    </a>
  </div>
</div>

<!-- ══════════════════════════════════════════
     KWITANSI
══════════════════════════════════════════ -->
<div class="kwitansi-wrap" style="position:relative">

  <?php if ($isLunas): ?>
  <div class="kw-watermark">LUNAS</div>
  <?php endif ?>

  <!-- ── Header Sekolah ── -->
  <div class="kw-header">
    <div class="kw-logo">
      <?php if ($logoUrl): ?>
        <img src="<?= e($logoUrl) ?>" alt="Logo">
      <?php else: ?>
        <div class="kw-logo-fallback">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
        </div>
      <?php endif ?>
    </div>
    <div class="kw-sekolah">
      <div class="kw-nama-sekolah"><?= e($namaSekolah) ?></div>
      <?php if ($alamatSekolah): ?>
        <div class="kw-alamat"><?= e($alamatSekolah) ?></div>
      <?php endif ?>
      <?php if ($telpSekolah): ?>
        <div class="kw-alamat">Telp: <?= e($telpSekolah) ?></div>
      <?php endif ?>
    </div>
    <div class="kw-badge">
      <div class="kw-badge-label">No. Kwitansi</div>
      <div class="kw-badge-val"><?= $noKwitansi ?></div>
      <div class="kw-badge-label" style="margin-top:8px">Tanggal Cetak</div>
      <div class="kw-badge-val"><?= $tglCetak ?></div>
    </div>
  </div>

  <!-- ── Judul ── -->
  <div class="kw-title-bar">
    <div style="display:flex;align-items:center;gap:10px">
      <div class="kw-title">Kwitansi Pembayaran SPP</div>
      <span class="kw-status <?= $isLunas ? 'lunas' : ($tagihan['status'] === 'cicilan' ? 'cicilan' : 'belum') ?>">
        <?php if ($isLunas): ?>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg> LUNAS
        <?php elseif ($tagihan['status'] === 'cicilan'): ?>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-3.85"/></svg> CICILAN
        <?php else: ?>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg> BELUM LUNAS
        <?php endif ?>
      </span>
    </div>
    <div class="kw-no"><?= $noKwitansi ?></div>
  </div>

  <!-- ── Body ── -->
  <div class="kw-body">

    <!-- Info Siswa & Tagihan -->
    <div class="kw-info-grid" style="margin-bottom:20px">
      <div class="kw-info-row">
        <div class="kw-info-cell">
          <div class="kw-info-label">Nama Siswa</div>
          <div class="kw-info-val" style="font-weight:700;font-size:14px"><?= e($siswa['nama']) ?></div>
        </div>
        <div class="kw-info-cell">
          <div class="kw-info-label">NIS</div>
          <div class="kw-info-val" style="font-family:'DM Mono',monospace"><?= e($siswa['nis']) ?></div>
        </div>
      </div>
      <div class="kw-info-row">
        <div class="kw-info-cell">
          <div class="kw-info-label">Kelas</div>
          <div class="kw-info-val"><?= e($siswa['kelas'].' '.$siswa['jurusan']) ?></div>
        </div>
        <div class="kw-info-cell">
          <div class="kw-info-label">Tahun Ajaran</div>
          <div class="kw-info-val"><?= e($tahunAjaran) ?></div>
        </div>
      </div>
      <div class="kw-info-row">
        <div class="kw-info-cell">
          <div class="kw-info-label">Periode SPP</div>
          <div class="kw-info-val" style="font-weight:600;color:var(--indigo)">
            <?= bulanIndo((int)$tagihan['bulan']).' '.$tagihan['tahun'] ?>
          </div>
        </div>
        <div class="kw-info-cell">
          <div class="kw-info-label">Nominal SPP</div>
          <div class="kw-info-val" style="font-family:'DM Mono',monospace;font-weight:600"><?= rupiah((int)$tagihan['nominal']) ?></div>
        </div>
      </div>
      <?php if (count($pembayaranList) > 1): ?>
      <div class="kw-info-row">
        <div class="kw-info-cell">
          <div class="kw-info-label">Tgl. Bayar Pertama</div>
          <div class="kw-info-val"><?= $tglBayarTampil ?></div>
        </div>
        <div class="kw-info-cell">
          <div class="kw-info-label">Jumlah Transaksi</div>
          <div class="kw-info-val"><?= count($pembayaranList) ?> kali pembayaran</div>
        </div>
      </div>
      <?php endif ?>
    </div>

    <!-- Detail Pembayaran -->
    <div class="kw-table-title">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>
      Rincian Pembayaran
    </div>

    <table class="kw-tbl">
      <thead>
        <tr>
          <th style="width:28px">#</th>
          <th>Tanggal Bayar</th>
          <th>Metode</th>
          <?php if ($adaKolomRekening): ?><th>No. Rekening / Ref</th><?php endif ?>
          <th>Keterangan</th>
          <th>Petugas</th>
          <th style="text-align:right">Jumlah</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($pembayaranList as $idx => $p):
          $tglP = date('d', strtotime($p['tgl_bayar']))
              .' '.bulanIndo((int)date('m', strtotime($p['tgl_bayar'])))
              .' '.date('Y', strtotime($p['tgl_bayar']));
          $jamP = date('H:i', strtotime($p['tgl_bayar']));
          $metodeBadge = [
            'tunai'    => ['#92400E','#FEF3C7'],
            'transfer' => ['#0369A1','#E0F2FE'],
            'qris'     => ['#5B21B6','#EDE9FE'],
          ];
          $mb = $metodeBadge[$p['metode_bayar']] ?? ['#374151','#F3F4F6'];
        ?>
        <tr>
          <td style="text-align:center;color:var(--text3);font-size:12px"><?= $idx+1 ?></td>
          <td>
            <div style="font-weight:500"><?= $tglP ?></div>
            <div style="font-size:11px;color:var(--text3)"><?= $jamP ?> WIB</div>
          </td>
          <td>
            <span style="display:inline-block;padding:2px 9px;border-radius:99px;font-size:11.5px;font-weight:700;background:<?= $mb[1] ?>;color:<?= $mb[0] ?>">
              <?= ucfirst($p['metode_bayar']) ?>
            </span>
          </td>
          <?php if ($adaKolomRekening): ?>
          <td style="font-family:'DM Mono',monospace;font-size:12px;color:var(--text2)"><?= e($p['no_rekening'] ?? '–') ?></td>
          <?php endif ?>
          <td style="font-size:12.5px;color:var(--text2)"><?= e($p['keterangan'] ?? '–') ?></td>
          <td style="font-size:12px;color:var(--text2)"><?= e($p['nama_admin'] ?? '–') ?></td>
          <td class="num" style="text-align:right;color:var(--green);font-weight:600"><?= rupiah((int)$p['jumlah_bayar']) ?></td>
        </tr>
        <?php endforeach ?>
      </tbody>
      <tr class="kw-tbl-total">
        <td colspan="<?= $colspanTotal ?>" style="text-align:right;color:var(--text2);font-size:12px">TOTAL DIBAYAR</td>
        <td style="text-align:right;color:var(--green);font-family:'DM Mono',monospace;font-size:15px"><?= rupiah($totalBayar) ?></td>
      </tr>
    </table>

    <!-- Terbilang -->
    <div class="kw-terbilang">
      <div class="kw-terbilang-label">Terbilang:</div>
      <div class="kw-terbilang-val">"<?= $terbilangBayar ?>"</div>
    </div>

    <!-- Sisa (jika belum lunas) -->
    <?php if (!$isLunas && $sisaBayar > 0): ?>
    <div class="kw-sisa">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#D97706" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
      <span style="color:#B45309">
        <strong>Sisa tunggakan:</strong>
        <span style="font-family:'DM Mono',monospace;font-weight:700"> <?= rupiah($sisaBayar) ?></span>
        &nbsp;&mdash;&nbsp; Harap segera dilunasi
      </span>
    </div>
    <?php endif ?>

    <!-- Tanda Tangan -->
    <div class="kw-ttd">
      <div class="kw-ttd-box" style="min-width:220px">
        <div class="kw-ttd-loc">Bekasi, <?= $tglCetak ?>,</div>
        <div class="kw-ttd-jabatan">Bendahara</div>
        <div class="kw-ttd-space"></div>
        <div class="kw-ttd-nama">Hj. Tihani Arfah</div>
        <div class="kw-ttd-nip">&nbsp;</div>
      </div>
    </div>

  </div><!-- end kw-body -->

  <!-- ── Footer ── -->
  <div class="kw-footer">
    <div class="kw-footer-brand">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
      <?= e($namaSekolah) ?> &mdash; Sistem Pembayaran SPP
    </div>
    <div>Dicetak: <?= $tglCetak ?> &nbsp;|&nbsp; <?= $noKwitansi ?><?php if ($printSize): ?> &nbsp;|&nbsp; <?= strtoupper($printSize) ?><?php endif ?></div>
  </div>

</div><!-- end kwitansi-wrap -->

</body>
</html>