<?php
// Parameter
$tipe      = isset($_GET['tipe'])      ? $_GET['tipe']      : 'bulanan';
$bulan     = (int)(isset($_GET['bulan'])  ? $_GET['bulan']  : date('n'));
$tahun     = (int)(isset($_GET['tahun'])  ? $_GET['tahun']  : date('Y'));
$tglDari   = isset($_GET['tgl_dari'])   ? $_GET['tgl_dari']   : date('Y-m-01');
$tglSampai = isset($_GET['tgl_sampai']) ? $_GET['tgl_sampai'] : date('Y-m-d');
$kelas     = isset($_GET['kelas'])     ? $_GET['kelas']     : '';
$metode    = isset($_GET['metode'])    ? $_GET['metode']    : '';
$viewMode  = isset($_GET['view'])      ? $_GET['view']      : 'semua';
$siswaId   = (int)(isset($_GET['siswa_id']) ? $_GET['siswa_id'] : 0);

// AJAX cari siswa
if (isset($_GET['_ajax']) && $_GET['_ajax'] === 'cari_siswa') {
    header('Content-Type: application/json');
    $q = isset($_GET['q']) ? trim($_GET['q']) : '';
    if (strlen($q) < 2) { echo '[]'; exit; }
    try {
        $st = $pdo->prepare("SELECT id,nis,nama,kelas,jurusan,foto FROM siswa WHERE (nama LIKE ? OR nis LIKE ?) AND status='aktif' ORDER BY nama LIMIT 12");
        $st->execute(array("%$q%", "%$q%"));
        echo json_encode($st->fetchAll(PDO::FETCH_ASSOC));
    } catch(Exception $e) { echo '[]'; }
    exit;
}

// Info sekolah
$setting = array();
try {
    $sRows = $pdo->query("SELECT kunci,nilai FROM pengaturan")->fetchAll();
    foreach ($sRows as $sr) $setting[$sr['kunci']] = $sr['nilai'];
} catch(Exception $e) {}
$namaSekolah   = isset($setting['nama_sekolah'])   ? $setting['nama_sekolah']   : 'SPP Sekolah';
$alamatSekolah = isset($setting['alamat_sekolah']) ? $setting['alamat_sekolah'] : '';
$namaKepsek    = isset($setting['nama_kepsek'])    ? $setting['nama_kepsek']    : '';
$nipKepsek     = isset($setting['nip_kepsek'])     ? $setting['nip_kepsek']     : '';
$namaBendahara = isset($setting['nama_bendahara']) ? $setting['nama_bendahara'] : '';
$nipBendahara  = isset($setting['nip_bendahara'])  ? $setting['nip_bendahara']  : '';
$noTelepon     = isset($setting['telp_sekolah'])   ? $setting['telp_sekolah']   : '';
$emailSekolah  = isset($setting['email_sekolah'])  ? $setting['email_sekolah']  : '';
$websiteSekolah= isset($setting['website'])        ? $setting['website']        : '';
$npsn          = isset($setting['npsn'])           ? $setting['npsn']           : '';
$nssSekolah    = isset($setting['nss'])            ? $setting['nss']            : '';
$rootDir       = str_replace('\\', '/', dirname(__DIR__));
$logoFile      = isset($setting['logo_sekolah'])   ? $setting['logo_sekolah']   : '';
$logoUrl       = ($logoFile && file_exists($rootDir.'/uploads/logo/'.$logoFile)) ? 'uploads/logo/'.$logoFile : null;
$capFile       = isset($setting['cap_sekolah'])  ? $setting['cap_sekolah']  : '';
$capUrl        = ($capFile  && file_exists($rootDir.'/uploads/logo/'.$capFile))  ? 'uploads/logo/'.$capFile  : null;
$ttdFile       = isset($setting['ttd_kepsek'])   ? $setting['ttd_kepsek']   : '';
$ttdUrl        = ($ttdFile  && file_exists($rootDir.'/uploads/logo/'.$ttdFile))  ? 'uploads/logo/'.$ttdFile  : null;

// Base join & where untuk transaksi
$baseJoin = "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  = " WHERE 1=1";
$params = array();
if ($tipe === 'harian') {
    $where .= " AND DATE(COALESCE(p.tanggal_bayar, p.created_at)) BETWEEN ? AND ?";
    $params[] = $tglDari; $params[] = $tglSampai;
} elseif ($tipe === 'bulanan') {
    $where .= " AND MONTH(COALESCE(p.tanggal_bayar, p.created_at))=? AND YEAR(COALESCE(p.tanggal_bayar, p.created_at))=?";
    $params[] = $bulan; $params[] = $tahun;
} else {
    $where .= " AND YEAR(COALESCE(p.tanggal_bayar, p.created_at))=?";
    $params[] = $tahun;
}
if ($kelas)  { $where .= " AND s.kelas=?";       $params[] = $kelas; }
if ($metode) { $where .= " AND p.metode_bayar=?"; $params[] = $metode; }

// Data transaksi (hanya mode transaksi)
$transaksi = array();
if ($viewMode === 'transaksi') {
    try {
        $st = $pdo->prepare(
            "SELECT p.id, p.jumlah_bayar, p.metode_bayar, p.keterangan,
                    COALESCE(p.tanggal_bayar, p.created_at) AS tgl_bayar,
                    t.bulan AS t_bulan, t.tahun AS t_tahun, t.nominal AS t_nominal, t.status AS t_status,
                    s.nama, s.nis, s.kelas, s.jurusan,
                    a.nama_lengkap AS nama_admin
             $baseJoin $where ORDER BY COALESCE(p.tanggal_bayar, p.created_at) DESC LIMIT 500"
        );
        $st->execute($params);
        $transaksi = $st->fetchAll();
    } catch(Exception $e) {}
}
$totalNominal = array_sum(array_column($transaksi, 'jumlah_bayar'));

function _met2($arr, $m) {
    return array_filter($arr, function($r) use($m) { return $r['metode_bayar'] == $m; });
}
$totalTunai    = array_sum(array_column(_met2($transaksi,'tunai'),    'jumlah_bayar'));
$totalTransfer = array_sum(array_column(_met2($transaksi,'transfer'), 'jumlah_bayar'));
$totalQris     = array_sum(array_column(_met2($transaksi,'qris'),     'jumlah_bayar'));
$jmlTunai      = count(_met2($transaksi,'tunai'));
$jmlTransfer   = count(_met2($transaksi,'transfer'));
$jmlQris       = count(_met2($transaksi,'qris'));
$totalSiswaAktif = 0;
try { $totalSiswaAktif = (int)$pdo->query("SELECT COUNT(*) FROM siswa WHERE status='aktif'")->fetchColumn(); } catch(Exception $e){}

// Rekap kelas (transaksi)
$rekapKelas = array();
if ($viewMode === 'transaksi') {
    try {
        $stK = $pdo->prepare("SELECT s.kelas, COUNT(DISTINCT s.id) as jml_siswa, COUNT(p.id) as jml_bayar, COALESCE(SUM(p.jumlah_bayar),0) as total $baseJoin $where GROUP BY s.kelas ORDER BY s.kelas");
        $stK->execute($params);
        $rekapKelas = $stK->fetchAll();
    } catch(Exception $e){}
    // Rekap harian
    $rekapHarian = array();
    if ($tipe === 'bulanan') {
        try {
            $stH = $pdo->prepare("SELECT DATE(COALESCE(p.tanggal_bayar, p.created_at)) as tgl, COUNT(p.id) as jml, SUM(p.jumlah_bayar) as total $baseJoin $where GROUP BY DATE(COALESCE(p.tanggal_bayar, p.created_at)) ORDER BY tgl ASC");
            $stH->execute($params);
            $rekapHarian = $stH->fetchAll();
        } catch(Exception $e){}
    }
    $rekapBulanan = array();
    if ($tipe === 'tahunan') {
        try {
            $stB = $pdo->prepare("SELECT MONTH(COALESCE(p.tanggal_bayar, p.created_at)) as bln, COUNT(p.id) as jml, SUM(p.jumlah_bayar) as total $baseJoin $where GROUP BY MONTH(COALESCE(p.tanggal_bayar, p.created_at)) ORDER BY bln ASC");
            $stB->execute($params);
            $rekapBulanan = $stB->fetchAll();
        } catch(Exception $e){}
    }
} else {
    $rekapHarian  = array();
    $rekapBulanan = array();
}

// Data semua siswa per kelas (mode semua)
$groupedKelas     = array();
$statSemuaLunas   = 0;
$statSemuaBelum   = 0;
$statSemuaCicilan = 0;

if ($viewMode === 'semua') {
    try {
        // Query sederhana tanpa GROUP BY bermasalah
        $sqlSemua  = "SELECT s.id AS siswa_id, s.nis, s.nama, s.kelas, s.jurusan,
                             t.id AS tagihan_id, t.bulan AS t_bulan, t.tahun AS t_tahun,
                             t.nominal AS t_nominal, t.status AS t_status
                      FROM siswa s
                      LEFT JOIN tagihan_spp t ON t.siswa_id = s.id
                           AND t.bulan = ? AND t.tahun = ?
                      WHERE s.status = 'aktif'";
        $parSemua = array($bulan, $tahun);
        if ($kelas) { $sqlSemua .= " AND s.kelas = ?"; $parSemua[] = $kelas; }
        $sqlSemua .= " ORDER BY s.kelas, s.jurusan, s.nama";

        $stSemua = $pdo->prepare($sqlSemua);
        $stSemua->execute($parSemua);
        $rowsSemua = $stSemua->fetchAll();

        // Ambil data pembayaran per tagihan
        $tagIds = array();
        foreach ($rowsSemua as $r) {
            if ($r['tagihan_id']) $tagIds[] = (int)$r['tagihan_id'];
        }
        $bayarMap = array();
        if (!empty($tagIds)) {
            $inClause = implode(',', $tagIds);
            try {
                $stByr = $pdo->query(
                    "SELECT tagihan_id, SUM(jumlah_bayar) as total_bayar,
                            MAX(COALESCE(tanggal_bayar,created_at)) as tgl_terakhir,
                            GROUP_CONCAT(DISTINCT metode_bayar SEPARATOR ',') as metode_list
                     FROM pembayaran WHERE tagihan_id IN ($inClause)
                     GROUP BY tagihan_id"
                );
                foreach ($stByr->fetchAll() as $br) {
                    $bayarMap[$br['tagihan_id']] = $br;
                }
            } catch(Exception $e){}
        }

        // Kelompokkan per kelas
        foreach ($rowsSemua as $r) {
            $key = $r['kelas'].'__'.($r['jurusan'] ? $r['jurusan'] : '');
            if (!isset($groupedKelas[$key])) {
                $groupedKelas[$key] = array(
                    'kelas'   => $r['kelas'],
                    'jurusan' => $r['jurusan'] ? $r['jurusan'] : '',
                    'siswa'   => array(),
                    'lunas'   => 0, 'cicilan' => 0, 'belum' => 0, 'notag' => 0,
                );
            }
            // Gabungkan data bayar
            $tid = $r['tagihan_id'];
            $br  = ($tid && isset($bayarMap[$tid])) ? $bayarMap[$tid] : null;
            $r['sudah_bayar']       = $br ? (float)$br['total_bayar'] : 0;
            $r['tgl_bayar_terakhir']= $br ? $br['tgl_terakhir'] : null;
            $r['metode_list']       = $br ? $br['metode_list'] : null;
            $groupedKelas[$key]['siswa'][] = $r;

            $st2 = $r['t_status'];
            if (!$tid)                  { $groupedKelas[$key]['notag']++;   }
            elseif ($st2 === 'lunas')   { $groupedKelas[$key]['lunas']++;   $statSemuaLunas++;   }
            elseif ($st2 === 'cicilan') { $groupedKelas[$key]['cicilan']++; $statSemuaCicilan++; }
            else                        { $groupedKelas[$key]['belum']++;   $statSemuaBelum++;   }
        }

        // Urutkan kelas
        $ordK = array('X'=>0,'XI'=>1,'XII'=>2);
        uksort($groupedKelas, function($a, $b) use($ordK) {
            $pa = explode('__', $a); $pb = explode('__', $b);
            $oa = isset($ordK[$pa[0]]) ? $ordK[$pa[0]] : 9;
            $ob = isset($ordK[$pb[0]]) ? $ordK[$pb[0]] : 9;
            if ($oa !== $ob) return $oa - $ob;
            return strcmp($a, $b);
        });

    } catch(Exception $e) { $groupedKelas = array(); }
}
$totalSiswaGrouped = 0;
foreach ($groupedKelas as $gd) $totalSiswaGrouped += count($gd['siswa']);

// Tagihan SPP per siswa
$kartSiswaInfo  = null;
$kartTagihan    = array();
$kartTotalTagih = 0;
$kartTotalBayar = 0;
$kartTotalSisa  = 0;

if ($viewMode === 'kartu_siswa' && $siswaId > 0) {
    try {
        $s2 = $pdo->prepare("SELECT id, nis, nama, kelas, jurusan, no_hp, alamat, foto, status, tahun_ajaran FROM siswa WHERE id=? LIMIT 1");
        $s2->execute(array($siswaId));
        $kartSiswaInfo = $s2->fetch();
    } catch(Exception $e){}
    if ($kartSiswaInfo) {
        try {
            $stT = $pdo->prepare(
                "SELECT t.id, t.bulan, t.tahun, t.nominal, t.status,
                        COALESCE(t.semester,0) AS semester,
                        COALESCE(t.tahun_ajaran,'') AS tahun_ajaran,
                        COALESCE(SUM(p.jumlah_bayar),0) AS sudah_bayar,
                        MAX(COALESCE(p.tanggal_bayar,p.created_at)) AS tgl_bayar_terakhir,
                        GROUP_CONCAT(p.metode_bayar ORDER BY p.id SEPARATOR ',') AS metode_list
                 FROM tagihan_spp t
                 LEFT JOIN pembayaran p ON p.tagihan_id = t.id
                 WHERE t.siswa_id = ?
                 GROUP BY t.id, t.bulan, t.tahun, t.nominal, t.status, t.semester, t.tahun_ajaran
                 ORDER BY t.tahun ASC, t.bulan ASC"
            );
            $stT->execute(array($siswaId));
            $kartTagihan = $stT->fetchAll();
        } catch(Exception $e){ $kartTagihan = array(); }
        foreach ($kartTagihan as &$tg) {
            $tg['sisa'] = max(0, (int)$tg['nominal'] - (float)$tg['sudah_bayar']);
            $kartTotalTagih += (int)$tg['nominal'];
            $kartTotalBayar += (float)$tg['sudah_bayar'];
        }
        unset($tg);
        $kartTotalSisa = max(0, $kartTotalTagih - $kartTotalBayar);
    }
}

// Judul periode
if ($tipe === 'harian') {
    $judulPeriode = date('d M Y', strtotime($tglDari));
    if ($tglDari !== $tglSampai) $judulPeriode .= ' s/d '.date('d M Y', strtotime($tglSampai));
} elseif ($tipe === 'bulanan') {
    $judulPeriode = bulanIndo($bulan).' '.$tahun;
} else {
    $judulPeriode = 'Tahun '.$tahun;
}

/* ── Fungsi cetak kop surat resmi ── */
function cetakKopSurat($setting, $logoUrl, $namaSekolah, $alamatSekolah, $noTelepon, $judulLaporan, $subJudul, $tglCetak) {
    $namaYayasan = isset($setting['nama_yayasan']) ? $setting['nama_yayasan'] : '';
    $akreditasi  = isset($setting['akreditasi'])   ? $setting['akreditasi']   : '';
    $noAkred     = isset($setting['no_akreditasi'])? $setting['no_akreditasi']: '';
    $emailSek    = isset($setting['email_sekolah'])? $setting['email_sekolah']: '';
    $websiteSek  = isset($setting['website'])      ? $setting['website']      : '';
    $npsn        = isset($setting['npsn'])         ? $setting['npsn']         : '';

    $baris1 = $alamatSekolah;
    if ($noTelepon) $baris1 .= ($baris1 ? ' Telp. ' : 'Telp. ').$noTelepon;
    $kontak = [];
    if ($emailSek)  $kontak[] = $emailSek;
    if ($websiteSek)$kontak[] = $websiteSek;
    if ($npsn)      $kontak[] = 'NPSN: '.$npsn;
    ob_start();
?>
<table style="width:100%;border-collapse:collapse;margin-bottom:0">
  <tr>
    <td style="width:110px;text-align:center;vertical-align:middle;padding:0 10px 0 0">
      <?php if($logoUrl): ?>
      <img src="<?= e($logoUrl) ?>" style="width:100px;height:100px;object-fit:contain">
      <?php else: ?>
      <div style="width:100px;height:100px;border-radius:50%;border:3px solid #1a1a1a;display:flex;align-items:center;justify-content:center;margin:0 auto;background:#fff">
        <svg width="50" height="50" viewBox="0 0 24 24" fill="none" stroke="#1a1a1a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="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 ?>
    </td>
    <td style="text-align:center;vertical-align:middle;padding:2px 0;line-height:1.25">
      <?php if($namaYayasan): ?>
      <div style="font-size:13pt;font-weight:700;color:#1a1a1a;font-family:Georgia,serif;font-style:italic;margin-bottom:2px"><?= e($namaYayasan) ?></div>
      <?php endif ?>
      <div style="font-size:22pt;font-weight:900;color:#1a1a1a;font-family:Georgia,serif;letter-spacing:.3px;line-height:1;text-transform:uppercase"><?= e($namaSekolah) ?></div>
      <?php if($akreditasi): ?>
      <div style="font-size:13pt;font-weight:900;color:#1a1a1a;font-family:Georgia,serif;letter-spacing:.4px;text-transform:uppercase;margin-top:3px">STATUS TERAKREDITASI <?= e($akreditasi) ?></div>
      <?php endif ?>
      <?php if($noAkred): ?>
      <div style="font-size:10pt;font-weight:700;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:4px">No. Akreditasi : <?= e($noAkred) ?></div>
      <?php endif ?>
      <?php if($baris1): ?>
      <div style="font-size:10pt;font-weight:700;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:2px"><?= e($baris1) ?></div>
      <?php endif ?>
      <?php if($kontak): ?>
      <div style="font-size:9pt;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:1px"><?= implode(' &nbsp;|&nbsp; ', array_map('e', $kontak)) ?></div>
      <?php endif ?>
    </td>
    <td style="width:110px"></td>
  </tr>
</table>
<div style="margin-top:8px;border-top:6px solid #1a1a1a"></div>
<div style="margin-top:2px;border-top:2px solid #1a1a1a;margin-bottom:10px"></div>
<div style="text-align:center;margin:6px 0 4px">
  <div style="font-size:14pt;font-weight:900;color:#1a1a1a;text-transform:uppercase;letter-spacing:3px;text-decoration:underline;text-underline-offset:4px;font-family:Georgia,serif"><?= $judulLaporan ?></div>
  <?php if($subJudul): ?>
  <div style="font-size:11pt;color:#1a1a1a;margin-top:5px;font-weight:700;font-family:Arial,sans-serif"><?= $subJudul ?></div>
  <?php endif ?>
  <div style="font-size:9pt;color:#333;margin-top:3px;font-family:Arial,sans-serif">Tanggal Cetak: <?= $tglCetak ?></div>
</div>
<div style="border-top:1px solid #888;margin-top:6px;margin-bottom:14px"></div>
<?php
    return ob_get_clean();
}

$tglCetak      = date('d ').bulanIndo((int)date('n')).date(' Y');
$transaksiJson  = json_encode(array_values($transaksi));
$allGkeys       = array_keys($groupedKelas);
$firstKey       = isset($allGkeys[0]) ? $allGkeys[0] : '';

require_once 'layout/header.php';
$ICO = array();
if (file_exists(dirname(__FILE__).'/config/icons.php')) require_once 'config/icons.php';
?>
<style>
.mode-tabs{display:flex;gap:4px;background:var(--surface2);border-radius:12px;padding:4px;margin-bottom:16px;flex-wrap:wrap}
.mode-tab{padding:8px 16px;border-radius:9px;font-size:13px;font-weight:600;text-decoration:none;color:var(--text2);transition:all .15s;display:flex;align-items:center;gap:6px;white-space:nowrap}
.mode-tab.active{background:var(--surface);color:#22C55E;box-shadow:0 2px 8px rgba(0,0,0,.1)}
.lap-view-toggle{display:flex;gap:3px;background:var(--surface2);border-radius:10px;padding:3px;flex-shrink:0}
.lap-view-toggle button{display:flex;align-items:center;gap:5px;padding:6px 11px;border:none;border-radius:8px;background:transparent;color:var(--text3);font-size:12px;font-weight:500;cursor:pointer;transition:all .18s;font-family:inherit}
.lap-view-toggle button.active{background:var(--surface);color:#22C55E;box-shadow:0 1px 4px rgba(0,0,0,.09)}
.lap-scroll-wrap{overflow-x:auto;overflow-y:auto;max-height:500px;border:1px solid var(--border);border-radius:10px 10px 0 0;scrollbar-width:thin}
.lap-scroll-wrap::-webkit-scrollbar{width:5px;height:5px}
.lap-scroll-wrap::-webkit-scrollbar-thumb{background:var(--border);border-radius:99px}
.lap-scroll-wrap thead th{position:sticky;top:0;z-index:3;background:var(--surface2)!important;box-shadow:0 2px 0 var(--border)}
.lap-table-footer{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;padding:10px 14px;background:var(--surface2);border:1px solid var(--border);border-top:2px solid var(--border);border-radius:0 0 10px 10px}
.lap-pag-wrap{display:flex;align-items:center;gap:6px;flex-wrap:wrap}
.lap-pag-btn{min-width:32px;height:32px;padding:0 8px;border:1px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text2);font-size:12px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;font-family:inherit;transition:all .15s}
.lap-pag-btn:hover:not(:disabled):not(.active){background:var(--surface2)}
.lap-pag-btn.active{background:#22C55E;color:#fff;border-color:#22C55E;font-weight:700}
.lap-pag-btn:disabled{opacity:.35;cursor:not-allowed}
.lap-pag-ellipsis{min-width:24px;height:32px;display:inline-flex;align-items:center;justify-content:center;font-size:12px;color:var(--text3)}
.lap-per-page{padding:5px 8px;border:1px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text2);font-size:12px;font-family:inherit;cursor:pointer}
.lap-pag-info{font-size:11.5px;color:var(--text3);white-space:nowrap}
.lap-cards-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px}
.lap-card{background:var(--surface);border:1.5px solid var(--border);border-radius:14px;overflow:hidden;display:flex;flex-direction:column;transition:box-shadow .2s,transform .2s}
.lap-card:hover{box-shadow:0 6px 22px rgba(0,0,0,.09);transform:translateY(-2px)}
.lap-card-bar{height:4px;flex-shrink:0}
.lap-card-body{padding:13px 14px;display:flex;flex-direction:column;gap:9px;flex:1}
.lap-card-top{display:flex;align-items:center;gap:10px}
.lap-card-ava{width:38px;height:38px;border-radius:11px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:15px;color:#fff}
.lap-card-name{font-size:13px;font-weight:700;color:var(--text);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.lap-card-sub{font-size:10.5px;color:var(--text3);margin-top:1px}
.lap-card-amount{margin-left:auto;font-family:'DM Mono',monospace;font-weight:700;font-size:13px;color:#16A34A;white-space:nowrap;flex-shrink:0}
.lap-card-hr{border:none;border-top:1px solid var(--border);margin:0}
.lap-card-rows{display:flex;flex-direction:column;gap:6px}
.lap-card-row{display:flex;align-items:center;justify-content:space-between;font-size:11.5px;gap:6px}
.lap-card-lbl{display:flex;align-items:center;gap:4px;color:var(--text3);flex-shrink:0}
.lap-card-val{color:var(--text2);text-align:right;min-width:0}
.lap-metode-pill{display:inline-flex;align-items:center;padding:2px 9px;border-radius:99px;font-size:10.5px;font-weight:600}
.lap-card-footer{padding:7px 14px;background:var(--surface2);border-top:1px solid var(--border);display:flex;align-items:center;gap:6px}
.lap-card-num{width:22px;height:22px;border-radius:6px;background:var(--border);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:var(--text3)}
.stat-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin-bottom:18px}
.stat-box{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:13px 15px}
.stat-val{font-family:'DM Mono',monospace;font-size:16px;font-weight:700;line-height:1;margin-bottom:4px}
.stat-val small{font-size:11px;opacity:.7;font-weight:400}
.stat-lbl{font-size:11.5px;color:var(--text3);font-weight:500}
.section-title{display:flex;align-items:center;gap:7px;font-size:13.5px;font-weight:700;color:var(--text);margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border)}
.section-hdr{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid var(--border);flex-wrap:wrap}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{padding:9px 11px;text-align:left;font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:var(--text3);border-bottom:2px solid var(--border);background:var(--surface2);white-space:nowrap}
.tbl td{padding:9px 11px;border-bottom:1px solid var(--border);vertical-align:middle}
.tbl tbody tr:hover td{background:var(--surface2)}
.tbl .alt td{background:rgba(99,130,165,.035)}
.tbl .total td{padding:10px 11px;background:var(--indigo-light,#EEF2FF)!important;border-top:2px solid var(--border)}
.bdg{display:inline-block;padding:2px 8px;border-radius:99px;font-size:11px;font-weight:600;white-space:nowrap}
.bdg-tunai{background:#FEF3C7;color:#92400E}
.bdg-transfer{background:#E0F2FE;color:#0369A1}
.bdg-qris{background:#EDE9FE;color:#5B21B6}
.chip{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:99px;font-size:11.5px;font-weight:700;white-space:nowrap}
.chip-lunas{background:#D1FAE5;color:#065F46}
.chip-cicilan{background:#FEF3C7;color:#92400E}
.chip-belum{background:#FEE2E2;color:#991B1B}
.chip-notag{background:#F1F5F9;color:#64748B}
.ttd-wrap{display:flex;justify-content:space-around;flex-wrap:wrap;gap:20px;margin-top:28px;padding-top:20px;border-top:1px solid var(--border)}
.ttd-box{text-align:center;min-width:180px}
.ttd-title{font-size:12px;color:var(--text2)}
.ttd-jabatan{font-size:13px;font-weight:600;color:var(--text);margin-top:2px}
.ttd-space{height:70px}
.ttd-nama{font-size:13.5px;font-weight:700;color:var(--text);border-bottom:1.5px solid var(--border);padding-bottom:5px;margin-bottom:4px}
.ttd-nip{font-size:11.5px;color:var(--text3);margin-top:3px;font-family:'DM Mono',monospace}
/* Kelas tab layout */
.ktab-wrap{display:grid;grid-template-columns:220px 1fr;background:var(--surface);border:1.5px solid var(--border);border-radius:14px;overflow:hidden;min-height:420px}
.ktab-panel{background:var(--surface2);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden}
.ktab-hdr{padding:11px 14px;font-size:12.5px;font-weight:700;color:var(--text);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:6px;flex-shrink:0}
.ktab-list{overflow-y:auto;flex:1;scrollbar-width:thin}
.ktab-list::-webkit-scrollbar{width:4px}
.ktab-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:99px}
.ktab-group{padding:5px 14px 4px;font-size:9.5px;font-weight:800;color:var(--text3);text-transform:uppercase;letter-spacing:.07em;background:var(--surface2);border-bottom:1px solid var(--border)}
.ktab-item{padding:11px 14px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .12s}
.ktab-item:hover{background:var(--surface)}
.ktab-item.active{background:var(--surface);border-left:3px solid #4F6EF7;padding-left:11px}
.ktab-content{overflow:hidden;display:flex;flex-direction:column}
.ktab-pane{display:none;flex-direction:column;flex:1}
.ktab-pane.active{display:flex}
.ktab-pane-hdr{padding:14px 16px;background:var(--surface2);border-bottom:1px solid var(--border);flex-shrink:0}
.pane-chip{padding:3px 10px;border-radius:99px;font-size:11.5px;font-weight:600;border:1.5px solid var(--border);background:var(--surface);color:var(--text3);cursor:pointer;font-family:inherit;transition:all .15s;white-space:nowrap}
.pane-chip:hover{border-color:var(--border);color:var(--text)}
.pane-chip.on{background:#1E2D4E;color:#fff;border-color:#1E2D4E}
/* Kartu search */
.ksearch-drop{display:none;position:absolute;top:calc(100% + 6px);left:0;right:0;z-index:9999;background:#fff;border:1.5px solid #E2E8F0;border-radius:12px;box-shadow:0 12px 40px rgba(0,0,0,.2);max-height:300px;overflow-y:auto;overflow-x:hidden}
.ksearch-item{display:flex;align-items:center;gap:10px;padding:10px 14px;cursor:pointer;border-bottom:1px solid #F1F5F9;transition:background .12s}
.ksearch-item:last-child{border-bottom:none}
.ksearch-item:hover{background:#F8FAFC}
/* Perkelas panel kartu */
.perkelas-wrap{background:var(--surface);border:1.5px solid var(--border);border-radius:14px;overflow:hidden;position:sticky;top:16px;max-height:calc(100vh - 80px);display:flex;flex-direction:column}
.perkelas-hdr{padding:12px 14px;border-bottom:1px solid var(--border);font-size:13px;font-weight:700;color:var(--text);display:flex;align-items:center;gap:7px;background:var(--surface2);flex-shrink:0}
.perkelas-list{overflow-y:auto;flex:1;scrollbar-width:thin}
.perkelas-list::-webkit-scrollbar{width:4px}
.perkelas-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:99px}
.perkelas-grp{padding:5px 14px 4px;font-size:9.5px;font-weight:800;color:var(--text3);text-transform:uppercase;letter-spacing:.07em;background:var(--surface2);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:2}
.perkelas-item{padding:10px 14px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .12s;display:block}
.perkelas-item:hover{background:var(--surface2)}
.perkelas-item.active{background:#EEF2FF;border-left:3px solid #4F6EF7;padding-left:11px}
/* Two-col layout */
.kartu-layout{display:grid;grid-template-columns:1fr 300px;gap:16px;align-items:start}
.filter-row{display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end}
.filter-row .form-group{margin:0}
@media (max-width:900px){
  .ktab-wrap{grid-template-columns:1fr}
  .ktab-panel{border-right:none;border-bottom:1px solid var(--border);max-height:240px}
  .kartu-layout{grid-template-columns:1fr}
  .stat-grid{grid-template-columns:1fr 1fr}
}
@media (max-width:480px){
  .stat-grid{grid-template-columns:1fr}
  .lap-cards-grid{grid-template-columns:1fr}
}
@media print{
  /* === PAGE SETUP === */
  @page{size:A4 portrait;margin:12mm 10mm 14mm 10mm}
  @page:first{margin-top:10mm}

  /* === HIDE SCREEN-ONLY ELEMENTS === */
  .sidebar,.topbar,.no-print,
  .mode-tabs,.lap-view-toggle,
  .filter-row,.pane-chip,
  .lap-table-footer,
  .lap-card-scroll-wrap,#lapViewCards,
  .kartu-layout > div:last-child,
  .perkelas-wrap{display:none!important}

  /* === RESET LAYOUT === */
  body{background:#fff!important;color:#000!important;font-size:10pt}
  .content{margin-left:0!important;padding:0!important;max-width:100%!important}
  #areaCetak{width:100%;box-sizing:border-box}
  *{-webkit-print-color-adjust:exact;print-color-adjust:exact;box-sizing:border-box}

  /* ═══════════════════════════════════════════════════════════
     HITAM PUTIH — semua elemen kecuali kop surat & cap/TTD
  ═══════════════════════════════════════════════════════════ */

  /* Reset semua background & warna teks */
  #areaCetak *:not(.print-kop-kelas):not(.print-kop-kelas *):not(.print-ttd-kelas img) {
    background: transparent !important;
    background-color: transparent !important;
    background-image: none !important;
    color: #000 !important;
    border-color: #ccc !important;
    box-shadow: none !important;
    text-shadow: none !important;
  }

  /* Tabel header tetap ada background abu muda agar mudah dibaca */
  .tbl th {
    background: #f0f0f0 !important;
    color: #000 !important;
    border: 1px solid #999 !important;
  }
  .tbl td {
    border: 1px solid #ccc !important;
    color: #000 !important;
  }
  .tbl .alt td { background: #fafafa !important; }
  .tbl .total td { background: #f0f0f0 !important; border-top: 2px solid #999 !important; }

  /* Chip & badge — hitam putih */
  .chip, .bdg, [class*="chip-"], [class*="bdg-"] {
    background: transparent !important;
    border: 1px solid #999 !important;
    color: #000 !important;
    padding: 1px 6px !important;
    border-radius: 3px !important;
  }

  /* Progress bar — hilang */
  [style*="background:"][style*="border-radius:99px"][style*="height:"] {
    background: #ddd !important;
  }

  /* Summary bar kartu siswa */
  .kartu-layout [style*="background"] {
    background: transparent !important;
    border: 1px solid #ccc !important;
  }

  /* Pane header kelas */
  .ktab-pane-hdr {
    background: #f5f5f5 !important;
    border-bottom: 1px solid #ccc !important;
  }

  /* Stat box */
  .stat-box {
    background: transparent !important;
    border: 1px solid #ccc !important;
    border-left: 2px solid #666 !important;
  }
  .stat-val, .stat-lbl { color: #000 !important; }

  /* Footer kelas */
  .ktab-pane > div:last-child {
    background: #f5f5f5 !important;
  }

  /* TTD section — hitam putih kecuali gambar cap & TTD */
  .print-ttd-kelas,
  .print-ttd-kelas > div,
  .print-ttd-kelas div:not([style*="position:absolute"]) {
    background: transparent !important;
    color: #000 !important;
  }
  .print-ttd-kelas div[style*="border-top"],
  .print-ttd-kelas div[style*="border-bottom"] {
    border-color: #555 !important;
  }

  /* Gambar TTD & cap TETAP tampil apa adanya */
  .print-ttd-kelas img,
  .ttd-space img,
  .ttd-wrap img {
    display: block !important;
    opacity: 1 !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }

  /* Kop surat TETAP berwarna/bergambar */
  .print-kop-kelas,
  .print-kop-kelas * {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
  /* Garis kop tetap hitam tebal */
  .print-kop-kelas [style*="border-top:6px"],
  .print-kop-kelas [style*="border-top:2px"] {
    border-color: #000 !important;
  }

  /* === KOP SURAT GLOBAL (disembunyikan) === */
  #kopSurat{display:none!important}
  /* === STAT GRID (disembunyikan) === */
  .stat-grid{display:none!important}
  .print-kop-kelas{display:block!important}
  .print-ttd-kelas{display:block!important}

  /* === KELAS TAB LAYOUT: SETIAP KELAS HALAMAN BARU === */
  .ktab-wrap{
    display:block!important;
    border:none!important;
    border-radius:0!important;
  }
  .ktab-panel{display:none!important}
  .ktab-content{display:block!important;overflow:visible!important}
  .ktab-pane{
    display:block!important;
    page-break-before:always; /* setiap kelas mulai halaman baru */
    break-before:page;
    margin-bottom:0;
    border:none!important;
    border-radius:0!important;
    overflow:visible!important;
  }
  .ktab-pane:first-child{
    page-break-before:auto!important;
    break-before:auto!important;
  }
  .ktab-pane-hdr{
    padding:8px 12px!important;
    background:#F1F5F9!important;
    border-bottom:1px solid #CBD5E1!important;
    break-inside:avoid;
  }
  .ktab-pane-hdr div{font-size:10pt!important}
  .ktab-pane-hdr span{font-size:8pt!important}
  .ktab-pane-hdr > div:nth-child(2){display:none!important}

  /* === TABEL === */
  .lap-scroll-wrap{
    max-height:none!important;
    overflow:visible!important;
    border:none!important;
    border-radius:0!important;
    break-inside:auto;
  }
  .lap-scroll-wrap thead th{
    position:static!important;
    box-shadow:none!important;
  }
  .tbl{
    width:100%!important;
    font-size:8pt!important;
    border-collapse:collapse!important;
  }
  .tbl th{
    padding:5px 6px!important;
    font-size:7pt!important;
    background:#F1F5F9!important;
    color:#334155!important;
    border:1px solid #CBD5E1!important;
    white-space:nowrap;
  }
  .tbl td{
    padding:4px 6px!important;
    border:1px solid #E2E8F0!important;
    font-size:8pt!important;
    vertical-align:middle!important;
    word-break:break-word;
  }
  .tbl .alt td{background:#F8FAFC!important}
  .tbl .total td{
    background:#EEF2FF!important;
    font-size:8.5pt!important;
    border-top:1.5px solid #CBD5E1!important;
  }

  /* Footer kelas (total tagihan dll) */
  .ktab-pane > div:last-child{
    padding:6px 10px!important;
    background:#F8FAFC!important;
    border-top:1px solid #CBD5E1!important;
    font-size:8pt!important;
    break-inside:avoid;
  }

  /* === CHIP & BADGE === */
  .chip,.bdg{
    padding:1px 5px!important;
    font-size:7pt!important;
    border-radius:4px!important;
    print-color-adjust:exact;
  }
  .chip-lunas{background:#D1FAE5!important;color:#065F46!important}
  .chip-cicilan{background:#FEF3C7!important;color:#92400E!important}
  .chip-belum{background:#FEE2E2!important;color:#991B1B!important}
  .chip-notag{background:#F1F5F9!important;color:#475569!important}

  /* === TRANSAKSI VIEW === */
  #lapViewTable{display:block!important}
  #lapViewCards{display:none!important}
  .section-title{font-size:10pt!important;padding-bottom:5px!important;margin-bottom:8px!important}
  .section-hdr{display:none!important}

  /* === TAGIHAN SPP SISWA === */
  .kartu-layout{display:block!important}
  .kartu-layout > div:first-child{width:100%!important}

  /* === TTD GLOBAL (disembunyikan, sudah ada per kelas) === */
  .ttd-wrap{ display:none!important }

  /* === TTD PER KELAS === */
  .print-ttd-kelas {
    break-inside: avoid;
  }
  .print-ttd-kelas > div {
    margin-top:16px!important;
    padding-top:12px!important;
    border-top:1px solid #CBD5E1!important;
  }
  /* Pastikan gambar TTD & cap muncul saat cetak */
  .print-ttd-kelas img,
  .ttd-space img,
  .ttd-wrap img {
    display: block !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}
</style>

<!-- Page Header -->
<div class="page-header no-print">
  <div>
    <div class="page-header-title">Laporan SPP</div>
    <div class="page-header-sub">Laporan pembayaran &mdash; <?= $judulPeriode ?></div>
  </div>
  <div style="display:flex;gap:8px;align-items:center">
    <button onclick="toggleKop()" id="btnKop" class="btn btn-outline" style="display:inline-flex;align-items:center;gap:7px;font-size:13px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
      Preview Kop
    </button>
    <button onclick="window.print()" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:7px;background:linear-gradient(135deg,#16A34A,#22C55E)">
      <svg width="15" height="15" 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 / PDF
    </button>
  </div>
</div>

<!-- Mode Tabs -->
<div class="mode-tabs no-print">
  <a href="index.php?page=laporan&bulan=<?= $bulan ?>&tahun=<?= $tahun ?>&kelas=<?= rawurlencode($kelas) ?>&view=semua"
     class="mode-tab <?= $viewMode==='semua'?'active':'' ?>">
    Status Per Kelas
    <span style="background:rgba(34,197,94,.15);color:#16A34A;border-radius:99px;padding:1px 7px;font-size:10.5px;font-weight:700">Lunas+Belum</span>
  </a>
  <a href="index.php?page=laporan&tipe=<?= $tipe ?>&bulan=<?= $bulan ?>&tahun=<?= $tahun ?>&kelas=<?= rawurlencode($kelas) ?>&view=transaksi"
     class="mode-tab <?= $viewMode==='transaksi'?'active':'' ?>">
    Riwayat Transaksi
  </a>
  <a href="index.php?page=laporan&view=kartu_siswa"
     class="mode-tab <?= $viewMode==='kartu_siswa'?'active':'' ?>">
    Tagihan SPP Siswa
  </a>
</div>

<!-- Filter -->
<div class="card no-print" style="margin-bottom:16px;padding:16px 18px">
  <form method="GET" action="index.php">
    <input type="hidden" name="page" value="laporan">
    <input type="hidden" name="view" value="<?= e($viewMode) ?>">
    <div class="filter-row">
      <?php if ($viewMode === 'transaksi'): ?>
      <div class="form-group" style="margin:0;min-width:120px">
        <label>Tipe</label>
        <select name="tipe" onchange="toggleFilter(this.value)">
          <option value="harian"  <?= $tipe==='harian' ?'selected':''?>>Harian</option>
          <option value="bulanan" <?= $tipe==='bulanan'?'selected':''?>>Bulanan</option>
          <option value="tahunan" <?= $tipe==='tahunan'?'selected':''?>>Tahunan</option>
        </select>
      </div>
      <div id="fHarian" style="display:<?= $tipe==='harian'?'contents':'none' ?>">
        <div class="form-group" style="margin:0"><label>Dari</label><input type="date" name="tgl_dari" value="<?= e($tglDari) ?>"></div>
        <div class="form-group" style="margin:0"><label>Sampai</label><input type="date" name="tgl_sampai" value="<?= e($tglSampai) ?>"></div>
      </div>
      <div id="fTahunan" style="display:<?= $tipe==='tahunan'?'contents':'none' ?>">
        <div class="form-group" style="margin:0"><label>Tahun</label>
          <select name="tahun"><?php for($y=date('Y');$y>=2020;$y--): ?><option value="<?= $y ?>" <?= $tahun===$y?'selected':''?>><?= $y ?></option><?php endfor ?></select>
        </div>
      </div>
      <?php endif ?>
      <div id="fBulanan" style="display:<?= ($tipe==='bulanan'||$viewMode!=='transaksi')?'contents':'none' ?>">
        <div class="form-group" style="margin:0;min-width:110px"><label>Bulan</label>
          <select name="bulan"><?php for($b=1;$b<=12;$b++): ?><option value="<?= $b ?>" <?= $bulan===$b?'selected':''?>><?= bulanIndo($b) ?></option><?php endfor ?></select>
        </div>
        <div class="form-group" style="margin:0;min-width:85px"><label>Tahun</label>
          <select name="tahun"><?php for($y=date('Y');$y>=2020;$y--): ?><option value="<?= $y ?>" <?= $tahun===$y?'selected':''?>><?= $y ?></option><?php endfor ?></select>
        </div>
      </div>
      <div class="form-group" style="margin:0;min-width:105px">
        <label>Kelas</label>
        <select name="kelas">
          <option value="" <?= !$kelas?'selected':''?>>Semua</option>
          <?php foreach(array('X','XI','XII') as $k): ?>
          <option value="<?= $k ?>" <?= $kelas===$k?'selected':''?>>Kelas <?= $k ?></option>
          <?php endforeach ?>
        </select>
      </div>
      <?php if ($viewMode === 'transaksi'): ?>
      <div class="form-group" style="margin:0;min-width:105px">
        <label>Metode</label>
        <select name="metode">
          <option value="" <?= !$metode?'selected':''?>>Semua</option>
          <option value="tunai"    <?= $metode==='tunai'   ?'selected':''?>>Tunai</option>
          <option value="transfer" <?= $metode==='transfer'?'selected':''?>>Transfer</option>
          <option value="qris"     <?= $metode==='qris'    ?'selected':''?>>QRIS</option>
        </select>
      </div>
      <?php endif ?>
      <div style="align-self:flex-end">
        <button type="submit" class="btn btn-primary" style="height:38px">Tampilkan</button>
      </div>
    </div>
  </form>
</div>

<!-- Area Cetak -->
<div id="areaCetak">

<!-- Kop Surat -->
<!-- Kop Surat -->
<div class="print-kop" id="kopSurat" style="display:none;background:#fff;padding:8px 0">

  <table style="width:100%;border-collapse:collapse;margin-bottom:0">
    <tr>
      <!-- Logo kiri -->
      <td style="width:115px;text-align:center;vertical-align:middle;padding:0 12px 0 0">
        <?php if($logoUrl): ?>
        <img src="<?= e($logoUrl) ?>" style="width:105px;height:105px;object-fit:contain" alt="logo">
        <?php else: ?>
        <div style="width:105px;height:105px;border-radius:50%;border:3px solid #1a1a1a;display:flex;align-items:center;justify-content:center;margin:0 auto;background:#fff">
          <svg width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="#1a1a1a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="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 ?>
      </td>

      <!-- Identitas tengah -->
      <td style="text-align:center;vertical-align:middle;padding:2px 0;line-height:1.2">
        <?php
          $namaYayasan = isset($setting['nama_yayasan']) ? $setting['nama_yayasan'] : '';
          $akreditasi  = isset($setting['akreditasi'])   ? $setting['akreditasi']   : '';
          $noAkred     = isset($setting['no_akreditasi'])? $setting['no_akreditasi']: '';
          $noTelepon   = isset($setting['telp_sekolah']) ? $setting['telp_sekolah'] : '';
          $emailSek    = isset($setting['email_sekolah'])? $setting['email_sekolah']: '';
          $websiteSek  = isset($setting['website'])      ? $setting['website']      : '';
          $npsn        = isset($setting['npsn'])         ? $setting['npsn']         : '';
        ?>

        <!-- Nama yayasan: italic bold, ukuran sedang -->
        <?php if($namaYayasan): ?>
        <div style="font-size:14pt;font-weight:700;color:#1a1a1a;font-family:Georgia,serif;font-style:italic;margin-bottom:1px">
          <?= e($namaYayasan) ?>
        </div>
        <?php endif ?>

        <!-- Nama sekolah: sesuai referensi -->
        <div style="font-size:22pt;font-weight:900;color:#1a1a1a;font-family:Georgia,serif;letter-spacing:.3px;line-height:1;text-transform:uppercase">
          <?= e($namaSekolah) ?>
        </div>

        <!-- Status akreditasi: bold serif -->
        <?php if($akreditasi): ?>
        <div style="font-size:14pt;font-weight:900;color:#1a1a1a;font-family:Georgia,serif;letter-spacing:.4px;text-transform:uppercase;margin-top:3px">
          STATUS TERAKREDITASI <?= e($akreditasi) ?>
        </div>
        <?php endif ?>

        <!-- No. Akreditasi + Alamat: lebih kecil, bold -->
        <?php if($noAkred): ?>
        <div style="font-size:10pt;font-weight:700;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:5px">
          No. Akreditasi : <?= e($noAkred) ?>
        </div>
        <?php endif ?>

        <?php
          $barisFull = '';
          if ($alamatSekolah) $barisFull = $alamatSekolah;
          if ($noTelepon)     $barisFull .= ($barisFull ? ' Telp. ' : 'Telp. ').$noTelepon;
          $kontakTambahan = [];
          if ($emailSek)   $kontakTambahan[] = $emailSek;
          if ($websiteSek) $kontakTambahan[] = $websiteSek;
          if ($npsn)       $kontakTambahan[] = 'NPSN: '.$npsn;
        ?>
        <?php if($barisFull): ?>
        <div style="font-size:10pt;font-weight:700;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:2px">
          <?= e($barisFull) ?>
        </div>
        <?php endif ?>
        <?php if($kontakTambahan): ?>
        <div style="font-size:9pt;color:#1a1a1a;font-family:Arial,sans-serif;margin-top:1px">
          <?= implode(' &nbsp;|&nbsp; ', array_map('e', $kontakTambahan)) ?>
        </div>
        <?php endif ?>
        <?php if(!$barisFull && empty($kontakTambahan) && !$namaYayasan && !$akreditasi): ?>
        <div style="font-size:10pt;color:#555;margin-top:2px;font-family:Arial,sans-serif">Sistem Informasi Pembayaran SPP</div>
        <?php endif ?>
      </td>

      <!-- Kanan kosong simetri -->
      <td style="width:115px"></td>
    </tr>
  </table>

  <!-- Garis kop: tebal + tipis seperti gambar referensi -->
  <div style="margin-top:8px;border-top:6px solid #1a1a1a"></div>
  <div style="margin-top:2px;border-top:2px solid #1a1a1a;margin-bottom:12px"></div>

  <!-- Judul laporan -->
  <div style="text-align:center;margin:6px 0 5px">
    <div style="font-size:14pt;font-weight:900;color:#1a1a1a;text-transform:uppercase;letter-spacing:3px;text-decoration:underline;text-underline-offset:4px;font-family:Georgia,serif">
      LAPORAN PEMBAYARAN SPP
    </div>
    <div style="font-size:11pt;color:#1a1a1a;margin-top:5px;font-weight:700;font-family:Arial,sans-serif">
      Periode: <?= $judulPeriode ?>
      <?= $kelas ? ' &nbsp;&mdash;&nbsp; Kelas: '.$kelas : '' ?>
    </div>
    <div style="font-size:9pt;color:#333;margin-top:3px;font-family:Arial,sans-serif">
      Tanggal Cetak: <?= $tglCetak ?>
    </div>
  </div>

  <!-- Garis bawah judul -->
  <div style="border-top:1px solid #888;margin-bottom:16px"></div>

</div>
<?php if ($viewMode === 'semua'): ?>
<!-- ============ MODE: STATUS PER KELAS ============ -->

<!-- Summary -->
<div class="stat-grid">
  <div class="stat-box" style="border-left:4px solid #1E2D4E">
    <div class="stat-val" style="color:#1E2D4E"><?= $totalSiswaGrouped ?></div>
    <div class="stat-lbl">Total Siswa</div>
  </div>
  <div class="stat-box" style="border-left:4px solid #059669">
    <div class="stat-val" style="color:#059669"><?= $statSemuaLunas ?></div>
    <div class="stat-lbl">Sudah Lunas</div>
  </div>
  <?php if ($statSemuaCicilan > 0): ?>
  <div class="stat-box" style="border-left:4px solid #D97706">
    <div class="stat-val" style="color:#D97706"><?= $statSemuaCicilan ?></div>
    <div class="stat-lbl">Cicilan</div>
  </div>
  <?php endif ?>
  <div class="stat-box" style="border-left:4px solid #DC2626">
    <div class="stat-val" style="color:#DC2626"><?= $statSemuaBelum ?></div>
    <div class="stat-lbl">Belum Bayar</div>
  </div>
  <div class="stat-box" style="border-left:4px solid #8B5CF6">
    <div class="stat-val" style="color:#8B5CF6"><?= count($groupedKelas) ?></div>
    <div class="stat-lbl">Kelas/Rombel</div>
  </div>
</div>

<?php if (empty($groupedKelas)): ?>
<div style="background:var(--surface);border:1.5px dashed var(--border);border-radius:12px;padding:40px;text-align:center;color:var(--text3)">
  Tidak ada data untuk periode yang dipilih. Pilih bulan/tahun lalu klik Tampilkan.
</div>
<?php else: ?>

<!-- Tab Kelas Layout -->
<div class="ktab-wrap">

  <!-- Panel kiri: daftar kelas -->
  <div class="ktab-panel">
    <div class="ktab-hdr">Pilih Kelas</div>
    <div class="ktab-list">
      <?php
      $prevTk = '';
      $itemIdx = 0;
      foreach ($groupedKelas as $gkey => $gd):
        $gPct   = count($gd['siswa']) > 0 ? round($gd['lunas'] / count($gd['siswa']) * 100) : 0;
        $gLabel = trim($gd['kelas'].' '.$gd['jurusan']);
        $barClr = $gPct>=80 ? '#059669' : ($gPct>=50 ? '#D97706' : '#DC2626');
        if ($gd['kelas'] !== $prevTk):
          $prevTk = $gd['kelas'];
      ?>
      <div class="ktab-group">Kelas <?= e($gd['kelas']) ?></div>
      <?php endif ?>
      <div class="ktab-item <?= $itemIdx===0?'active':'' ?>"
           data-idx="<?= $itemIdx ?>"
           onclick="ktabPilih(<?= $itemIdx ?>)">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px">
          <span style="font-size:13px;font-weight:700;color:var(--text)"><?= e($gLabel) ?></span>
          <span style="font-size:10.5px;color:var(--text3);background:var(--border);border-radius:99px;padding:1px 6px"><?= count($gd['siswa']) ?></span>
        </div>
        <div style="height:4px;background:var(--border);border-radius:99px;overflow:hidden;margin-bottom:4px">
          <div style="height:100%;border-radius:99px;width:<?= $gPct ?>%;background:<?= $barClr ?>;transition:width .4s"></div>
        </div>
        <div style="display:flex;gap:6px;font-size:10.5px;font-weight:600;flex-wrap:wrap">
          <span style="color:#059669"><?= $gd['lunas'] ?> lunas</span>
          <?php if ($gd['cicilan']>0): ?><span style="color:#D97706"><?= $gd['cicilan'] ?> cicilan</span><?php endif ?>
          <span style="color:#DC2626"><?= $gd['belum'] ?> belum</span>
          <span style="color:var(--text3);margin-left:auto"><?= $gPct ?>%</span>
        </div>
      </div>
      <?php $itemIdx++; endforeach ?>
    </div>
  </div>

  <!-- Panel kanan: tabel siswa -->
  <div class="ktab-content">
    <?php
    $metBdg = array('tunai'=>array('#FEF3C7','#92400E'),'transfer'=>array('#E0F2FE','#0369A1'),'qris'=>array('#EDE9FE','#5B21B6'),'dana'=>array('#DBEAFE','#1251B5'),'gopay'=>array('#CCFBF1','#0369A1'),'ovo'=>array('#EDE9FE','#4C3494'),'shopeepay'=>array('#FFE4E4','#C0392B'),'linkaja'=>array('#FFE4E4','#B91C1C'),'credit_card'=>array('#DBEAFE','#1E40AF'),'bank_transfer'=>array('#DBEAFE','#1E40AF'),'echannel'=>array('#FEF3C7','#92400E'),'permata'=>array('#DBEAFE','#1E40AF'),'bca'=>array('#DBEAFE','#006CB7'),'bni'=>array('#FEF3C7','#92400E'),'bri'=>array('#DBEAFE','#00529C'),'cstore'=>array('#D1FAE5','#065F46'),'midtrans'=>array('#EDE9FE','#5B21B6'));
    $paneIdx = 0;
    foreach ($groupedKelas as $gkey => $gd):
      $gLabel  = trim($gd['kelas'].' '.$gd['jurusan']);
      $gPct    = count($gd['siswa'])>0 ? round($gd['lunas']/count($gd['siswa'])*100) : 0;
      $barClr2 = $gPct>=80 ? '#059669' : ($gPct>=50 ? '#D97706' : '#DC2626');
      $paneId  = 'ktpane'.$paneIdx;
      // Sort siswa: lunas -> cicilan -> belum -> notag -> nama
      $ss = $gd['siswa'];
      usort($ss, function($a, $b) {
        $om = array('lunas'=>0,'cicilan'=>1,'belum_bayar'=>2,''=>3);
        $sa = isset($a['t_status']) ? $a['t_status'] : '';
        $sb = isset($b['t_status']) ? $b['t_status'] : '';
        $oa = isset($om[$sa]) ? $om[$sa] : 3;
        $ob = isset($om[$sb]) ? $om[$sb] : 3;
        if ($oa !== $ob) return $oa - $ob;
        return strcmp($a['nama'], $b['nama']);
      });
      $nomKelas  = 0; $bayarKelas = 0;
      foreach ($ss as $r) { $nomKelas += (int)$r['t_nominal']; $bayarKelas += (float)$r['sudah_bayar']; }
    ?>
    <div class="ktab-pane <?= $paneIdx===0?'active':'' ?>" id="<?= $paneId ?>">

      <!-- Kop per kelas (hanya tampil saat cetak) -->
      <div class="print-kop-kelas" style="display:none;padding:6px 0 10px">
        <?= cetakKopSurat($setting, $logoUrl, $namaSekolah, $alamatSekolah, $noTelepon,
            'LAPORAN PEMBAYARAN SPP',
            'Kelas '.e($gLabel).' &nbsp;&mdash;&nbsp; Periode: '.bulanIndo($bulan).' '.$tahun,
            $tglCetak) ?>
      </div>
      <div class="ktab-pane-hdr">
        <div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:8px;margin-bottom:8px">
          <div>
            <div style="font-size:15px;font-weight:700;color:var(--text)">Kelas <?= e($gLabel) ?></div>
            <div style="font-size:12px;color:var(--text3);margin-top:1px"><?= bulanIndo($bulan) ?> <?= $tahun ?> &nbsp;&middot;&nbsp; <?= count($ss) ?> siswa</div>
          </div>
          <div style="display:flex;gap:5px;flex-wrap:wrap">
            <span style="background:#D1FAE5;color:#065F46;border-radius:99px;padding:3px 10px;font-size:11.5px;font-weight:700"><?= $gd['lunas'] ?> lunas</span>
            <?php if ($gd['cicilan']>0): ?><span style="background:#FEF3C7;color:#92400E;border-radius:99px;padding:3px 10px;font-size:11.5px;font-weight:700"><?= $gd['cicilan'] ?> cicilan</span><?php endif ?>
            <span style="background:#FEE2E2;color:#991B1B;border-radius:99px;padding:3px 10px;font-size:11.5px;font-weight:700"><?= $gd['belum'] ?> belum</span>
          </div>
        </div>
        <div style="height:6px;background:var(--border);border-radius:99px;overflow:hidden;margin-bottom:4px">
          <div style="height:100%;border-radius:99px;width:<?= $gPct ?>%;background:<?= $barClr2 ?>;transition:width .5s"></div>
        </div>
        <div style="display:flex;align-items:center;justify-content:space-between;font-size:11.5px;color:var(--text3)">
          <span><?= $gPct ?>% lunas</span>
          <div style="display:flex;gap:4px" class="no-print">
            <button class="pane-chip on" data-pf="semua" onclick="paneFilter('<?= $paneId ?>','semua',this)">Semua</button>
            <button class="pane-chip" data-pf="lunas"   onclick="paneFilter('<?= $paneId ?>','lunas',this)">Lunas</button>
            <?php if ($gd['cicilan']>0): ?><button class="pane-chip" data-pf="cicilan" onclick="paneFilter('<?= $paneId ?>','cicilan',this)">Cicilan</button><?php endif ?>
            <button class="pane-chip" data-pf="belum"   onclick="paneFilter('<?= $paneId ?>','belum',this)">Belum</button>
          </div>
        </div>
      </div>

      <!-- Tabel siswa -->
      <div class="lap-scroll-wrap" style="border-radius:0;border:none;border-top:1px solid var(--border);max-height:450px">
        <table class="tbl">
          <thead>
            <tr>
              <th style="width:32px">No</th>
              <th style="min-width:150px">Nama Siswa</th>
              <th>NIS</th>
              <th style="text-align:right;min-width:90px">Nominal</th>
              <th style="text-align:right;min-width:90px">Terbayar</th>
              <th style="text-align:right;min-width:80px">Sisa</th>
              <th style="text-align:center;min-width:120px">Status</th>
              <th style="min-width:90px">Tgl Bayar</th>
              <th>Metode</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($ss as $pi => $ls):
              $ls_st  = isset($ls['t_status']) ? $ls['t_status'] : '';
              $ls_bay = (float)$ls['sudah_bayar'];
              $ls_nom = (int)$ls['t_nominal'];
              $ls_sisa= max(0, $ls_nom - $ls_bay);
              $ls_mets= ($ls['metode_list']) ? array_unique(explode(',', $ls['metode_list'])) : array();
              if (!$ls['tagihan_id'])       { $bgRow=''; $chipCls='chip-notag'; $chipLbl='Tdk Ada Tagihan'; $df='notag'; }
              elseif ($ls_st==='lunas')     { $bgRow='rgba(5,150,105,.04)';  $chipCls='chip-lunas';   $chipLbl='Lunas';      $df='lunas'; }
              elseif ($ls_st==='cicilan')   { $bgRow='rgba(217,119,6,.03)';  $chipCls='chip-cicilan'; $chipLbl='Cicilan';    $df='cicilan'; }
              else                          { $bgRow='rgba(220,38,38,.03)';  $chipCls='chip-belum';   $chipLbl='Belum Bayar';$df='belum'; }
            ?>
            <tr style="background:<?= $bgRow ?>" data-status="<?= $df ?>">
              <td style="color:#9AAAC8;font-size:11px;text-align:center"><?= $pi+1 ?></td>
              <td><div style="font-weight:700;font-size:13px"><?= e($ls['nama']) ?></div></td>
              <td style="font-family:monospace;font-size:11.5px;color:#5A6A8A"><?= e($ls['nis']) ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700"><?= $ls_nom ? rupiah($ls_nom) : '&mdash;' ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700;color:<?= $ls_bay>0?'#059669':'#9AAAC8' ?>"><?= $ls_bay>0 ? rupiah($ls_bay) : '&mdash;' ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700;color:<?= $ls_sisa>0?'#DC2626':'#9AAAC8' ?>"><?= $ls_sisa>0 ? rupiah($ls_sisa) : '&mdash;' ?></td>
              <td style="text-align:center"><span class="chip <?= $chipCls ?>"><?= $chipLbl ?></span></td>
              <td style="font-size:12px;color:var(--text2)"><?= $ls['tgl_bayar_terakhir'] ? date('d M Y', strtotime($ls['tgl_bayar_terakhir'])) : '&mdash;' ?></td>
              <td>
                <?php foreach ($ls_mets as $m):
                  $mb = isset($metBdg[strtolower($m)]) ? $metBdg[strtolower($m)] : array('#F1F5F9','#475569');
                ?>
                <span style="background:<?= $mb[0] ?>;color:<?= $mb[1] ?>;border-radius:5px;padding:1px 6px;font-size:10.5px;font-weight:600;display:inline-block;margin:1px"><?= ucfirst($m) ?></span>
                <?php endforeach ?>
                <?php if (!$ls_mets): ?><span style="color:var(--text3)">&mdash;</span><?php endif ?>
              </td>
            </tr>
            <?php endforeach ?>
          </tbody>
        </table>
      </div>

      <!-- Footer kelas -->
      <div style="padding:10px 14px;border-top:2px solid var(--border);background:var(--surface2);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;flex-shrink:0">
        <span style="font-size:12px;color:var(--text3)"><?= count($ss) ?> siswa</span>
        <div style="display:flex;gap:12px;flex-wrap:wrap">
          <span style="font-size:12px;color:var(--text3)">Tagihan: <strong><?= rupiah($nomKelas) ?></strong></span>
          <span style="font-size:12px;color:#059669">Terbayar: <strong><?= rupiah($bayarKelas) ?></strong></span>
          <?php if ($nomKelas > $bayarKelas): ?>
          <span style="font-size:12px;color:#DC2626">Sisa: <strong><?= rupiah($nomKelas - $bayarKelas) ?></strong></span>
          <?php endif ?>
        </div>
      </div>
    <!-- Tanda Tangan per kelas (tampil saat cetak) -->
    <div class="print-ttd-kelas" style="display:none">
      <div style="display:flex;justify-content:space-around;flex-wrap:wrap;gap:20px;margin-top:20px;padding-top:14px;border-top:1px solid #CBD5E1">
        <div style="text-align:center;min-width:180px;position:relative">
          <div style="font-size:10pt;color:#555">Mengetahui,</div>
          <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Kepala Sekolah/Madrasah</div>
          <div style="height:60px;position:relative;display:flex;align-items:center;justify-content:center">
            <?php if($ttdUrl): ?>
            <img src="<?= e($ttdUrl) ?>" style="max-height:56px;max-width:140px;object-fit:contain;position:relative;z-index:2">
            <?php endif ?>
            <?php if($capUrl): ?>
            <img src="<?= e($capUrl) ?>" style="position:absolute;left:50%;transform:translateX(-30%);width:64px;height:64px;object-fit:contain;opacity:.55;z-index:1;top:-4px">
            <?php endif ?>
          </div>
          <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaKepsek ? e($namaKepsek) : '...............................' ?></div>
          <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipKepsek ? e($nipKepsek) : '...............................' ?></div>
        </div>
        <div style="text-align:center;min-width:180px">
          <div style="font-size:10pt;color:#555">Dibuat oleh,</div>
          <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Bendahara / Petugas SPP</div>
          <div style="height:60px"></div>
          <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaBendahara ? e($namaBendahara) : '...............................' ?></div>
          <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipBendahara ? e($nipBendahara) : '...............................' ?></div>
        </div>
      </div>
    </div><!-- end print-ttd-kelas -->

    </div><!-- end ktab-pane -->
    <?php $paneIdx++; endforeach ?>
  </div>

</div>
<?php endif ?> <?php /* end if empty groupedKelas */ ?>

<?php elseif ($viewMode === 'transaksi'): ?>
<!-- ============ MODE: RIWAYAT TRANSAKSI ============ -->

<!-- Kop transaksi (hanya cetak) -->
<div class="print-kop-kelas" style="display:none;padding:6px 0 10px">
  <?= cetakKopSurat($setting, $logoUrl, $namaSekolah, $alamatSekolah, $noTelepon,
      'LAPORAN PEMBAYARAN SPP',
      'Riwayat Transaksi &nbsp;&mdash;&nbsp; Periode: '.$judulPeriode.($kelas ? ' &nbsp;&mdash;&nbsp; Kelas: '.$kelas : ''),
      $tglCetak) ?>
</div>

<!-- Statistik -->
<div class="stat-grid">
  <div class="stat-box" style="border-left:4px solid #4F6EF7"><div class="stat-val" style="color:#4F6EF7"><?= count($transaksi) ?></div><div class="stat-lbl">Total Transaksi</div></div>
  <div class="stat-box" style="border-left:4px solid #22C55E"><div class="stat-val" style="color:#22C55E"><?= rupiah($totalNominal) ?></div><div class="stat-lbl">Total Penerimaan</div></div>
  <div class="stat-box" style="border-left:4px solid #F59E0B"><div class="stat-val" style="color:#F59E0B"><?= rupiah($totalTunai) ?> <small>(<?= $jmlTunai ?>)</small></div><div class="stat-lbl">Tunai</div></div>
  <div class="stat-box" style="border-left:4px solid #0EA5E9"><div class="stat-val" style="color:#0EA5E9"><?= rupiah($totalTransfer) ?> <small>(<?= $jmlTransfer ?>)</small></div><div class="stat-lbl">Transfer</div></div>
  <div class="stat-box" style="border-left:4px solid #8B5CF6"><div class="stat-val" style="color:#8B5CF6"><?= rupiah($totalQris) ?> <small>(<?= $jmlQris ?>)</small></div><div class="stat-lbl">QRIS</div></div>
  <div class="stat-box" style="border-left:4px solid #EC4899"><div class="stat-val" style="color:#EC4899"><?= $totalSiswaAktif ?></div><div class="stat-lbl">Siswa Aktif</div></div>
</div>

<?php if (!empty($rekapKelas)): ?>
<div style="margin-bottom:18px">
  <div class="section-title">Rekap Per Kelas</div>
  <table class="tbl"><thead><tr><th>Kelas</th><th>Siswa</th><th>Transaksi</th><th style="text-align:right">Total</th></tr></thead>
  <tbody>
    <?php foreach ($rekapKelas as $rk): ?>
    <tr><td><strong>Kelas <?= e($rk['kelas']) ?></strong></td><td><?= $rk['jml_siswa'] ?></td><td><?= $rk['jml_bayar'] ?></td><td style="text-align:right;font-weight:600"><?= rupiah($rk['total']) ?></td></tr>
    <?php endforeach ?>
    <tr class="total"><td colspan="2"><strong>Total</strong></td><td><strong><?= count($transaksi) ?></strong></td><td style="text-align:right"><strong><?= rupiah($totalNominal) ?></strong></td></tr>
  </tbody></table>
</div>
<?php endif ?>

<?php if ($tipe==='bulanan' && !empty($rekapHarian)): ?>
<div style="margin-bottom:18px">
  <div class="section-title">Rekap Harian &mdash; <?= bulanIndo($bulan) ?> <?= $tahun ?></div>
  <table class="tbl"><thead><tr><th>Tanggal</th><th>Hari</th><th>Transaksi</th><th style="text-align:right">Total</th></tr></thead>
  <tbody>
    <?php $hI=array('Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu');
    foreach ($rekapHarian as $rh): ?>
    <tr><td><?= date('d M Y',strtotime($rh['tgl'])) ?></td><td><?= $hI[date('w',strtotime($rh['tgl']))] ?></td><td><?= $rh['jml'] ?></td><td style="text-align:right;font-weight:600"><?= rupiah($rh['total']) ?></td></tr>
    <?php endforeach ?>
    <tr class="total"><td colspan="2"><strong>Total</strong></td><td><strong><?= count($transaksi) ?></strong></td><td style="text-align:right"><strong><?= rupiah($totalNominal) ?></strong></td></tr>
  </tbody></table>
</div>
<?php endif ?>

<?php if ($tipe==='tahunan' && !empty($rekapBulanan)): ?>
<div style="margin-bottom:18px">
  <div class="section-title">Rekap Bulanan Tahun <?= $tahun ?></div>
  <table class="tbl"><thead><tr><th>Bulan</th><th>Transaksi</th><th style="text-align:right">Total</th></tr></thead>
  <tbody>
    <?php $totBln=0; foreach ($rekapBulanan as $rb): $totBln+=$rb['total']; ?>
    <tr><td><strong><?= bulanIndo((int)$rb['bln']) ?></strong></td><td><?= $rb['jml'] ?></td><td style="text-align:right;font-weight:600"><?= rupiah($rb['total']) ?></td></tr>
    <?php endforeach ?>
    <tr class="total"><td><strong>Total <?= $tahun ?></strong></td><td><strong><?= count($transaksi) ?></strong></td><td style="text-align:right"><strong><?= rupiah($totBln) ?></strong></td></tr>
  </tbody></table>
</div>
<?php endif ?>

<!-- Detail Transaksi -->
<div>
  <div class="section-hdr no-print">
    <div class="section-title" style="margin:0;padding:0;border:none;flex:1">
      Detail Transaksi
      <span style="background:var(--surface2);border-radius:99px;padding:1px 9px;font-size:11px;color:var(--text3);font-weight:500;margin-left:4px"><?= count($transaksi) ?> data</span>
    </div>
    <div class="lap-view-toggle">
      <button id="lapBtnTable" class="active" onclick="lapSwitchView('table')">Tabel</button>
      <button id="lapBtnCard"  onclick="lapSwitchView('card')">Kartu</button>
    </div>
  </div>
  <?php if (empty($transaksi)): ?>
  <div style="text-align:center;padding:40px;color:var(--text3)">Tidak ada data transaksi untuk periode ini.</div>
  <?php else: ?>
  <div id="lapViewTable">
    <div class="lap-scroll-wrap">
      <table class="tbl"><thead><tr><th style="width:30px">No</th><th>Tanggal</th><th style="min-width:140px">Nama</th><th>NIS</th><th>Kelas</th><th>Periode</th><th>Metode</th><th style="text-align:right">Jumlah</th><th>Petugas</th></tr></thead>
      <tbody id="lapTableBody"></tbody></table>
    </div>
    <div class="lap-table-footer">
      <div class="lap-pag-wrap">
        <select class="lap-per-page" id="lapPerPage" onchange="lapChangePage(1)"><option value="10">10/hal</option><option value="25" selected>25/hal</option><option value="50">50/hal</option></select>
        <span class="lap-pag-info" id="lapPagInfo"></span>
        <div id="lapPagination" style="display:flex;gap:3px;flex-wrap:wrap"></div>
      </div>
      <div style="display:flex;align-items:center;gap:6px">
        <span style="font-size:12px;color:var(--text3)">Total:</span>
        <span style="font-family:'DM Mono',monospace;font-size:14px;font-weight:700;color:#16A34A"><?= rupiah($totalNominal) ?></span>
      </div>
    </div>
  </div>
  <div id="lapViewCards" style="display:none">
    <div style="max-height:560px;overflow-y:auto;padding:2px"><div class="lap-cards-grid" id="lapCardsGrid"></div></div>
    <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;padding:10px 4px 4px;border-top:1px solid var(--border);margin-top:10px">
      <div class="lap-pag-wrap">
        <select class="lap-per-page" id="lapPerPageCard" onchange="lapChangePageCard(1)"><option value="12">12/hal</option><option value="24" selected>24/hal</option></select>
        <span class="lap-pag-info" id="lapPagInfoCard"></span>
        <div id="lapPaginationCard" style="display:flex;gap:3px;flex-wrap:wrap"></div>
      </div>
      <div style="display:flex;align-items:center;gap:6px"><span style="font-size:12px;color:var(--text3)">Total:</span><span style="font-family:'DM Mono',monospace;font-size:14px;font-weight:700;color:#16A34A"><?= rupiah($totalNominal) ?></span></div>
    </div>
  </div>
  <?php endif ?>
</div>

<!-- TTD transaksi (hanya cetak) -->
<div class="print-ttd-kelas" style="display:none">
  <div style="display:flex;justify-content:space-around;flex-wrap:wrap;gap:20px;margin-top:20px;padding-top:14px;border-top:1px solid #CBD5E1">
    <div style="text-align:center;min-width:180px;position:relative">
      <div style="font-size:10pt;color:#555">Mengetahui,</div>
      <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Kepala Sekolah/Madrasah</div>
      <div style="height:60px;position:relative;display:flex;align-items:center;justify-content:center">
        <?php if($ttdUrl): ?>
        <img src="<?= e($ttdUrl) ?>" style="max-height:56px;max-width:140px;object-fit:contain;position:relative;z-index:2">
        <?php endif ?>
        <?php if($capUrl): ?>
        <img src="<?= e($capUrl) ?>" style="position:absolute;left:50%;transform:translateX(-30%);width:64px;height:64px;object-fit:contain;opacity:.55;z-index:1;top:-4px">
        <?php endif ?>
      </div>
      <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaKepsek ? e($namaKepsek) : '...............................' ?></div>
      <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipKepsek ? e($nipKepsek) : '...............................' ?></div>
    </div>
    <div style="text-align:center;min-width:180px">
      <div style="font-size:10pt;color:#555">Dibuat oleh,</div>
      <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Bendahara / Petugas SPP</div>
      <div style="height:60px"></div>
      <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaBendahara ? e($namaBendahara) : '...............................' ?></div>
      <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipBendahara ? e($nipBendahara) : '...............................' ?></div>
    </div>
  </div>
</div>

<?php else: ?>
<!-- ============ MODE: TAGIHAN SPP SISWA ============ -->

<!-- Search box -->
<div class="no-print" style="margin-bottom:20px">
  <div style="background:linear-gradient(135deg,#1E2D4E,#2E4478);border-radius:16px;padding:20px 22px;position:relative;overflow:visible">
    <div style="font-size:12px;font-weight:700;color:rgba(255,255,255,.6);text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px">Cari Siswa &mdash; Lihat Semua Tagihan SPP</div>
    <div style="position:relative;max-width:480px;z-index:100" id="kartuWrap">
      <input type="text" id="kartuInput" placeholder="Ketik nama atau NIS siswa..."
             autocomplete="off" oninput="kartuSearch(this.value)"
             style="width:100%;box-sizing:border-box;padding:10px 14px;background:rgba(255,255,255,.15);border:1.5px solid rgba(255,255,255,.3);border-radius:10px;color:#fff;font-size:13.5px;font-family:'DM Sans',sans-serif;outline:none">
      <div class="ksearch-drop" id="kartuDrop"></div>
    </div>
    <div style="font-size:11px;color:rgba(255,255,255,.4);margin-top:6px">Ketik minimal 2 karakter lalu pilih dari hasil</div>
  </div>
</div>

<?php if ($kartSiswaInfo): ?>
<?php
  $fotoSiswaFile = isset($kartSiswaInfo['foto']) ? $kartSiswaInfo['foto'] : '';
  $fotoSiswaAbs  = $rootDir.'/uploads/foto_siswa/'.$fotoSiswaFile;
  $fotoSiswaUrl  = ($fotoSiswaFile && file_exists($fotoSiswaAbs)) ? 'uploads/foto_siswa/'.e($fotoSiswaFile) : null;
?>

<!-- Kop kartu siswa (hanya cetak) -->
<div class="print-kop-kelas" style="display:none;padding:6px 0 10px">
  <?= cetakKopSurat($setting, $logoUrl, $namaSekolah, $alamatSekolah, $noTelepon,
      'TAGIHAN SPP SISWA',
      e($kartSiswaInfo['nama']).' &nbsp;&mdash;&nbsp; NIS: '.e($kartSiswaInfo['nis']).' &nbsp;&mdash;&nbsp; Kelas '.e($kartSiswaInfo['kelas'].' '.($kartSiswaInfo['jurusan']??'')),
      $tglCetak) ?>
</div>
<div class="kartu-layout">
  <!-- Kiri: kartu SPP siswa -->
  <div>
    <!-- Profil — no-print -->
    <div class="no-print" style="background:var(--surface);border:1.5px solid var(--border);border-radius:14px;padding:16px;margin-bottom:14px;display:flex;align-items:center;gap:14px;flex-wrap:wrap">
      <?php if($fotoSiswaUrl): ?>
      <img src="<?= $fotoSiswaUrl ?>?v=<?= filemtime($fotoSiswaAbs) ?>"
           alt="Foto <?= e($kartSiswaInfo['nama']) ?>"
           style="width:56px;height:56px;border-radius:13px;object-fit:cover;flex-shrink:0;border:2px solid var(--border)">
      <?php else: ?>
      <div style="width:56px;height:56px;border-radius:13px;background:#1E2D4E;display:flex;align-items:center;justify-content:center;font-size:22px;font-weight:800;color:#fff;flex-shrink:0">
        <?= mb_strtoupper(mb_substr($kartSiswaInfo['nama'],0,1)) ?>
      </div>
      <?php endif ?>
      <div style="flex:1;min-width:150px">
        <div style="font-size:16px;font-weight:700;color:var(--text)"><?= e($kartSiswaInfo['nama']) ?></div>
        <div style="display:flex;gap:7px;flex-wrap:wrap;margin-top:5px">
          <span style="background:#EDE9FE;color:#5B21B6;border-radius:6px;padding:2px 9px;font-size:12px;font-weight:700">NIS: <?= e($kartSiswaInfo['nis']) ?></span>
          <span class="pill pill-purple"><?= e($kartSiswaInfo['kelas']) ?> <?= e(isset($kartSiswaInfo['jurusan'])?$kartSiswaInfo['jurusan']:'') ?></span>
        </div>
      </div>
      <a href="index.php?page=laporan&view=kartu_siswa" class="btn btn-outline btn-sm" style="font-size:12px">Ganti Siswa</a>
    </div>
    <!-- Summary — no-print -->
    <div class="no-print" style="background:var(--surface2);border:1.5px solid var(--border);border-radius:12px;padding:12px 16px;margin-bottom:14px;display:flex;align-items:center;flex-wrap:wrap;gap:0">
      <div style="flex:1;min-width:120px;text-align:center;padding:6px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--text3);margin-bottom:4px">Total Tagihan</div>
        <div style="font-size:15px;font-weight:700;color:var(--text);font-family:'DM Mono',monospace"><?= count($kartTagihan) ?> bulan</div>
      </div>
      <div style="flex:1;min-width:140px;text-align:center;padding:6px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--text3);margin-bottom:4px">Total Tagihan (Rp)</div>
        <div style="font-size:15px;font-weight:700;color:var(--text);font-family:'DM Mono',monospace"><?= rupiah($kartTotalTagih) ?></div>
      </div>
      <div style="flex:1;min-width:140px;text-align:center;padding:6px 14px;border-right:1px solid var(--border)">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--text3);margin-bottom:4px">Terbayar</div>
        <div style="font-size:15px;font-weight:700;color:#059669;font-family:'DM Mono',monospace"><?= rupiah($kartTotalBayar) ?></div>
      </div>
      <div style="flex:1;min-width:140px;text-align:center;padding:6px 14px">
        <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.7px;color:var(--text3);margin-bottom:4px">Sisa / Status</div>
        <div style="font-size:15px;font-weight:700;font-family:'DM Mono',monospace;color:<?= $kartTotalSisa>0?'#DC2626':'#059669' ?>"><?= $kartTotalSisa>0 ? rupiah($kartTotalSisa) : '✓ Lunas' ?></div>
      </div>
    </div>
    <!-- Tabel riwayat -->
    <div style="background:var(--surface);border:1.5px solid var(--border);border-radius:14px;overflow:hidden">
      <div style="padding:12px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px">
        <div style="font-size:14px;font-weight:700;color:var(--text)">
          Tagihan SPP &mdash; <?= e($kartSiswaInfo['nama']) ?>
          <span style="background:var(--surface2);border-radius:99px;padding:1px 8px;font-size:11px;color:var(--text3);font-weight:500;margin-left:4px"><?= e($kartSiswaInfo['nis']) ?> &middot; Kelas <?= e($kartSiswaInfo['kelas']) ?> <?= e($kartSiswaInfo['jurusan']??'') ?></span>
          <span style="background:var(--surface2);border-radius:99px;padding:1px 8px;font-size:11px;color:var(--text3);font-weight:500;margin-left:4px"><?= count($kartTagihan) ?> tagihan</span>
        </div>
        <a href="index.php?page=laporan&view=kartu_siswa" class="btn btn-outline btn-sm no-print" style="font-size:12px;flex-shrink:0">↩ Ganti Siswa</a>
      </div>
      <?php if (empty($kartTagihan)): ?>
      <div style="padding:32px;text-align:center;color:var(--text3)">Belum ada tagihan untuk siswa ini.</div>
      <?php else: ?>
      <div style="overflow-x:auto">
        <table class="tbl">
          <thead><tr><th>No</th><th>Periode</th><th>Semester</th><th style="text-align:right">Nominal</th><th style="text-align:right">Terbayar</th><th style="text-align:right">Sisa</th><th style="text-align:center">Status</th><th>Tgl Bayar</th><th>Metode</th></tr></thead>
          <tbody>
            <?php
            $metBdg2 = array('tunai'=>array('#FEF3C7','#92400E'),'transfer'=>array('#E0F2FE','#0369A1'),'qris'=>array('#EDE9FE','#5B21B6'),'dana'=>array('#DBEAFE','#1251B5'),'gopay'=>array('#CCFBF1','#0369A1'),'ovo'=>array('#EDE9FE','#4C3494'),'shopeepay'=>array('#FFE4E4','#C0392B'),'linkaja'=>array('#FFE4E4','#B91C1C'),'credit_card'=>array('#DBEAFE','#1E40AF'),'bank_transfer'=>array('#DBEAFE','#1E40AF'),'echannel'=>array('#FEF3C7','#92400E'),'permata'=>array('#DBEAFE','#1E40AF'),'bca'=>array('#DBEAFE','#006CB7'),'bni'=>array('#FEF3C7','#92400E'),'bri'=>array('#DBEAFE','#00529C'),'cstore'=>array('#D1FAE5','#065F46'),'midtrans'=>array('#EDE9FE','#5B21B6'));
            foreach ($kartTagihan as $idx => $tg):
              $st    = isset($tg['status']) ? $tg['status'] : '';
              $tSem  = (int)(isset($tg['semester']) ? $tg['semester'] : 0);
              $bay   = (float)$tg['sudah_bayar'];
              $sisa  = (int)$tg['sisa'];
              $mList = $tg['metode_list'] ? array_unique(explode(',', $tg['metode_list'])) : array();
              if ($st==='lunas')   { $bgR='rgba(5,150,105,.04)';  $chC='chip-lunas';   $chL='Lunas'; }
              elseif($st==='cicilan'){$bgR='rgba(217,119,6,.03)'; $chC='chip-cicilan'; $chL='Cicilan'; }
              else                 { $bgR='rgba(220,38,38,.03)';  $chC='chip-belum';   $chL='Belum Bayar'; }
            ?>
            <tr style="background:<?= $bgR ?>">
              <td style="color:#9AAAC8;font-size:11px"><?= $idx+1 ?></td>
              <td>
                <div style="font-weight:700"><?= bulanIndo((int)$tg['bulan']) ?> <?= $tg['tahun'] ?></div>
                <?php if ($tg['tahun_ajaran']): ?><div style="font-size:10.5px;color:var(--text3)"><?= e($tg['tahun_ajaran']) ?></div><?php endif ?>
              </td>
              <td>
                <?php if ($tSem): ?>
                <span style="background:<?= $tSem===1?'#ECFDF5':'#EFF6FF' ?>;color:<?= $tSem===1?'#059669':'#2563EB' ?>;border-radius:6px;padding:2px 7px;font-size:10.5px;font-weight:700"><?= $tSem===1?'Ganjil':'Genap' ?></span>
                <?php else: ?><span style="color:var(--text3)">&mdash;</span><?php endif ?>
              </td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700"><?= rupiah($tg['nominal']) ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700;color:<?= $bay>0?'#059669':'#9AAAC8' ?>"><?= $bay>0?rupiah($bay):'&mdash;' ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:700;color:<?= $sisa>0?'#DC2626':'#9AAAC8' ?>"><?= $sisa>0?rupiah($sisa):'&mdash;' ?></td>
              <td style="text-align:center"><span class="chip <?= $chC ?>"><?= $chL ?></span></td>
              <td style="font-size:12px;color:var(--text2)"><?= $tg['tgl_bayar_terakhir']?date('d M Y',strtotime($tg['tgl_bayar_terakhir'])):'&mdash;' ?></td>
              <td><?php foreach($mList as $m): $mb=isset($metBdg2[strtolower($m)])?$metBdg2[strtolower($m)]:array('#F1F5F9','#475569'); ?>
                <span style="background:<?= $mb[0] ?>;color:<?= $mb[1] ?>;border-radius:5px;padding:1px 6px;font-size:10.5px;font-weight:600;display:inline-block;margin:1px"><?= ucfirst($m) ?></span>
              <?php endforeach; if(!$mList): ?><span style="color:var(--text3)">&mdash;</span><?php endif ?></td>
            </tr>
            <?php endforeach ?>
            <tr class="total">
              <td colspan="3" style="font-weight:700">TOTAL</td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:800;font-size:14px"><?= rupiah($kartTotalTagih) ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:800;font-size:14px;color:#059669"><?= rupiah($kartTotalBayar) ?></td>
              <td style="text-align:right;font-family:'DM Mono',monospace;font-weight:800;font-size:14px;color:<?= $kartTotalSisa>0?'#DC2626':'#059669' ?>"><?= $kartTotalSisa>0?rupiah($kartTotalSisa):'Lunas' ?></td>
              <td colspan="3" style="font-size:12px;color:var(--text3)">
                <?php $jlL=0; foreach($kartTagihan as $k){ if($k['status']==='lunas')$jlL++; } ?>
                <?= $jlL ?>/<?= count($kartTagihan) ?> lunas
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <?php endif ?>
    </div>
  </div>

  <!-- Kanan: panel per kelas -->
  <div class="no-print">
    <?php
    $perKelasData = array();
    if ($viewMode === 'kartu_siswa') {
        try {
            $stPK = $pdo->prepare(
                "SELECT k.tingkat AS kelas, k.nama_kelas AS jurusan,
                        COUNT(DISTINCT s.id) AS total_siswa,
                        SUM(CASE WHEN t.status='lunas' THEN 1 ELSE 0 END) AS jml_lunas,
                        SUM(CASE WHEN t.status='cicilan' THEN 1 ELSE 0 END) AS jml_cicilan,
                        SUM(CASE WHEN t.status IS NOT NULL AND t.status!='lunas' AND t.status!='cicilan' THEN 1 ELSE 0 END) AS jml_belum
                 FROM kelas k
                 LEFT JOIN siswa s ON s.kelas=k.tingkat AND s.jurusan=k.nama_kelas AND s.status='aktif'
                 LEFT JOIN tagihan_spp t ON t.siswa_id=s.id AND t.bulan=? AND t.tahun=?
                 WHERE k.status='aktif'
                 GROUP BY k.tingkat, k.nama_kelas
                 ORDER BY FIELD(k.tingkat,'X','XI','XII'), k.nama_kelas"
            );
            $stPK->execute(array($bulan, $tahun));
            $perKelasData = $stPK->fetchAll();
        } catch(Exception $e) { $perKelasData = array(); }
    }
    ?>
    <div class="perkelas-wrap">
      <div class="perkelas-hdr">Status Per Kelas &mdash; <?= bulanIndo($bulan) ?> <?= $tahun ?></div>
      <?php if (empty($perKelasData)): ?>
      <div style="padding:20px;text-align:center;font-size:12px;color:var(--text3)">Belum ada data.</div>
      <?php else: ?>
      <div class="perkelas-list">
        <?php
        $prevTk2 = '';
        $tkAll   = array_sum(array_column($perKelasData,'total_siswa'));
        $tlAll   = array_sum(array_column($perKelasData,'jml_lunas'));
        $pAll    = $tkAll>0 ? round($tlAll/$tkAll*100) : 0;
        ?>
        <div style="padding:10px 14px;background:linear-gradient(135deg,#1E2D4E,#2E4478)">
          <div style="display:flex;align-items:center;justify-content:space-between;color:#fff;margin-bottom:4px;font-size:12px;font-weight:700">
            <span>Semua Kelas</span><span><?= $pAll ?>% lunas</span>
          </div>
          <div style="height:5px;background:rgba(255,255,255,.2);border-radius:99px;overflow:hidden;margin-bottom:5px">
            <div style="height:100%;border-radius:99px;width:<?= $pAll ?>%;background:linear-gradient(90deg,#34D399,#4ADE80)"></div>
          </div>
          <div style="display:flex;gap:10px;font-size:11px;font-weight:600">
            <span style="color:#4ADE80"><?= $tlAll ?> lunas</span>
            <span style="color:#FCA5A5"><?= array_sum(array_column($perKelasData,'jml_belum')) ?> belum</span>
            <span style="color:rgba(255,255,255,.5);margin-left:auto"><?= $tkAll ?> siswa</span>
          </div>
        </div>
        <?php foreach ($perKelasData as $pk):
          $pkt = $pk['total_siswa']>0 ? round($pk['jml_lunas']/$pk['total_siswa']*100) : 0;
          $pkLabel = trim($pk['kelas'].' '.$pk['jurusan']);
          $pkActive = ($kartSiswaInfo && $kartSiswaInfo['kelas']==$pk['kelas'] && (isset($kartSiswaInfo['jurusan'])?$kartSiswaInfo['jurusan']:'') == $pk['jurusan']);
          $bClr = $pkt>=80?'#059669':($pkt>=50?'#D97706':'#DC2626');
          if ($pk['kelas'] !== $prevTk2): $prevTk2=$pk['kelas']; ?>
        <div class="perkelas-grp">Kelas <?= e($pk['kelas']) ?></div>
        <?php endif ?>
        <div class="perkelas-item <?= $pkActive?'active':'' ?>">
          <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px">
            <span style="font-size:12.5px;font-weight:700;color:var(--text)"><?= e($pkLabel) ?></span>
            <span style="font-size:10px;color:var(--text3);background:var(--surface2);border-radius:99px;padding:1px 6px"><?= $pk['total_siswa'] ?></span>
          </div>
          <div style="height:4px;background:var(--border);border-radius:99px;overflow:hidden;margin-bottom:4px">
            <div style="height:100%;border-radius:99px;width:<?= $pkt ?>%;background:<?= $bClr ?>"></div>
          </div>
          <div style="display:flex;gap:5px;font-size:10.5px;font-weight:600;flex-wrap:wrap">
            <span style="color:#059669"><?= $pk['jml_lunas'] ?> lunas</span>
            <?php if ((int)$pk['jml_cicilan']>0): ?><span style="color:#D97706"><?= $pk['jml_cicilan'] ?> cicilan</span><?php endif ?>
            <span style="color:#DC2626"><?= $pk['jml_belum'] ?> belum</span>
            <span style="color:<?= $bClr ?>;margin-left:auto"><?= $pkt ?>%</span>
          </div>
        </div>
        <?php endforeach ?>
      </div>
      <?php endif ?>
    </div>
  </div>
</div>
<?php else: ?>
<div style="background:var(--surface);border:1.5px dashed var(--border);border-radius:16px;padding:52px 24px;text-align:center">
  <div style="width:56px;height:56px;border-radius:16px;background:linear-gradient(135deg,#1E2D4E,#4F6EF7);display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
    <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
  </div>
  <div style="font-size:17px;font-weight:700;color:var(--text);margin-bottom:8px">Cari Siswa untuk Melihat Tagihan SPP</div>
  <div style="font-size:13px;color:var(--text3);max-width:380px;margin:0 auto;line-height:1.6">Ketik nama atau NIS siswa di kotak pencarian di atas.</div>
</div>
<?php endif ?>

<!-- TTD kartu siswa (hanya cetak) -->
<?php if($kartSiswaInfo): ?>
<div class="print-ttd-kelas" style="display:none">
  <div style="display:flex;justify-content:space-around;flex-wrap:wrap;gap:20px;margin-top:20px;padding-top:14px;border-top:1px solid #CBD5E1">
    <div style="text-align:center;min-width:180px;position:relative">
      <div style="font-size:10pt;color:#555">Mengetahui,</div>
      <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Kepala Sekolah/Madrasah</div>
      <div style="height:60px;position:relative;display:flex;align-items:center;justify-content:center">
        <?php if($ttdUrl): ?>
        <img src="<?= e($ttdUrl) ?>" style="max-height:56px;max-width:140px;object-fit:contain;position:relative;z-index:2">
        <?php endif ?>
        <?php if($capUrl): ?>
        <img src="<?= e($capUrl) ?>" style="position:absolute;left:50%;transform:translateX(-30%);width:64px;height:64px;object-fit:contain;opacity:.55;z-index:1;top:-4px">
        <?php endif ?>
      </div>
      <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaKepsek ? e($namaKepsek) : '...............................' ?></div>
      <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipKepsek ? e($nipKepsek) : '...............................' ?></div>
    </div>
    <div style="text-align:center;min-width:180px">
      <div style="font-size:10pt;color:#555">Dibuat oleh,</div>
      <div style="font-size:11pt;font-weight:600;color:#000;margin-top:2px">Bendahara / Petugas SPP</div>
      <div style="height:60px"></div>
      <div style="font-size:10pt;font-weight:700;color:#000;border-bottom:1.5px solid #555;padding-bottom:4px;margin-bottom:3px"><?= $namaBendahara ? e($namaBendahara) : '...............................' ?></div>
      <div style="font-size:8.5pt;color:#666;margin-top:2px;font-family:monospace">NIP. <?= $nipBendahara ? e($nipBendahara) : '...............................' ?></div>
    </div>
  </div>
</div>
<?php endif ?>

<!-- TTD -->
<?php endif ?><!-- end viewMode block -->
<div class="ttd-wrap">
  <div class="ttd-box">
    <div class="ttd-title">Mengetahui,</div>
    <div class="ttd-jabatan">Kepala Sekolah/Madrasah</div>
    <div class="ttd-space" style="position:relative;display:flex;align-items:center;justify-content:center">
      <?php if($ttdUrl): ?>
      <img src="<?= e($ttdUrl) ?>" style="max-height:66px;max-width:140px;object-fit:contain;position:relative;z-index:2">
      <?php endif ?>
      <?php if($capUrl): ?>
      <img src="<?= e($capUrl) ?>" style="position:absolute;left:50%;transform:translateX(-30%);width:68px;height:68px;object-fit:contain;opacity:.5;z-index:1;top:-2px">
      <?php endif ?>
    </div>
    <div class="ttd-nama"><?= $namaKepsek ? e($namaKepsek) : '...............................' ?></div>
    <div class="ttd-nip">NIP. <?= $nipKepsek ? e($nipKepsek) : '...............................' ?></div>
  </div>
  <div class="ttd-box">
    <div class="ttd-title">Dibuat oleh,</div>
    <div class="ttd-jabatan">Bendahara / Petugas SPP</div>
    <div class="ttd-space"></div>
    <div class="ttd-nama"><?= $namaBendahara ? e($namaBendahara) : '...............................' ?></div>
    <div class="ttd-nip">NIP. <?= $nipBendahara ? e($nipBendahara) : '...............................' ?></div>
  </div>
</div>

</div><!-- end areaCetak -->

<script>
var LAP_DATA = <?= $transaksiJson ?>;
var BULAN_INDO = ['','Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
var AVATAR_COLORS = ['#4F6EF7','#EC4899','#14B8A6','#F59E0B','#22C55E','#8B5CF6','#0EA5E9','#EF4444'];
var METODE_STYLE = {
  'tunai'        :{label:'Tunai',        bar:'#F59E0B',bg:'#FEF3C7',color:'#92400E'},
  'transfer'     :{label:'Transfer',     bar:'#0EA5E9',bg:'#E0F2FE',color:'#0369A1'},
  'qris'         :{label:'QRIS',         bar:'#8B5CF6',bg:'#EDE9FE',color:'#5B21B6'},
  'dana'         :{label:'DANA',         bar:'#118EEA',bg:'#DBEAFE',color:'#1251B5'},
  'gopay'        :{label:'GoPay',        bar:'#00AED6',bg:'#CCFBF1',color:'#0369A1'},
  'ovo'          :{label:'OVO',          bar:'#4C3494',bg:'#EDE9FE',color:'#4C3494'},
  'shopeepay'    :{label:'ShopeePay',    bar:'#EE4D2D',bg:'#FFE4E4',color:'#C0392B'},
  'linkaja'      :{label:'LinkAja',      bar:'#E02020',bg:'#FFE4E4',color:'#B91C1C'},
  'credit_card'  :{label:'Kartu Kredit', bar:'#1D4ED8',bg:'#DBEAFE',color:'#1E40AF'},
  'bank_transfer':{label:'Transfer Bank',bar:'#3B82F6',bg:'#DBEAFE',color:'#1E40AF'},
  'echannel'     :{label:'Mandiri VA',   bar:'#F59E0B',bg:'#FEF3C7',color:'#92400E'},
  'permata'      :{label:'Permata VA',   bar:'#1E40AF',bg:'#DBEAFE',color:'#1E40AF'},
  'bca'          :{label:'BCA VA',       bar:'#006CB7',bg:'#DBEAFE',color:'#006CB7'},
  'bni'          :{label:'BNI VA',       bar:'#F59E0B',bg:'#FEF3C7',color:'#92400E'},
  'bri'          :{label:'BRI VA',       bar:'#00529C',bg:'#DBEAFE',color:'#00529C'},
  'cstore'       :{label:'Minimarket',   bar:'#10B981',bg:'#D1FAE5',color:'#065F46'},
  'midtrans'     :{label:'Midtrans',     bar:'#8B5CF6',bg:'#EDE9FE',color:'#5B21B6'}
};
function fmtR(n){return 'Rp\u202F'+parseInt(n||0).toLocaleString('id-ID');}
function fmtD(s){var d=new Date(s);if(isNaN(d))return s;return String(d.getDate()).padStart(2,'0')+'/'+String(d.getMonth()+1).padStart(2,'0')+'/'+d.getFullYear();}
function fmtJ(s){var d=new Date(s);if(isNaN(d))return '';return String(d.getHours()).padStart(2,'0')+':'+String(d.getMinutes()).padStart(2,'0');}
function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');}
function buildPager(id,cur,total,fn){
  var el=document.getElementById(id);if(!el)return;
  if(total<=1){el.innerHTML='';return;}
  var h='<button class="lap-pag-btn" onclick="'+fn+'('+(cur-1)+')" '+(cur<=1?'disabled':'')+'>&lsaquo;</button>';
  var pg=[];
  if(total<=7){for(var i=1;i<=total;i++)pg.push(i);}
  else{pg.push(1);if(cur>3)pg.push('...');for(var p=Math.max(2,cur-1);p<=Math.min(total-1,cur+1);p++)pg.push(p);if(cur<total-2)pg.push('...');pg.push(total);}
  pg.forEach(function(x){
    if(x==='...')h+='<span class="lap-pag-ellipsis">...</span>';
    else h+='<button class="lap-pag-btn'+(x===cur?' active':'')+'" onclick="'+fn+'('+x+')">'+x+'</button>';
  });
  h+='<button class="lap-pag-btn" onclick="'+fn+'('+(cur+1)+')" '+(cur>=total?'disabled':'')+'>&rsaquo;</button>';
  el.innerHTML=h;
}

/* Tabel Transaksi */
var lapCurPage=1;
function lapGetPP(){return parseInt((document.getElementById('lapPerPage')||{value:'25'}).value)||25;}
function lapChangePage(p){lapCurPage=p;lapRenderTable(p);}
function lapRenderTable(page){
  var el=document.getElementById('lapTableBody');if(!el)return;
  var pp=lapGetPP(),data=LAP_DATA,total=data.length,tp=Math.max(1,Math.ceil(total/pp));
  page=Math.min(Math.max(1,page),tp);lapCurPage=page;
  var start=(page-1)*pp,end=Math.min(start+pp,total),html='';
  data.slice(start,end).forEach(function(tr,i){
    var gi=start+i,alt=gi%2===0?'':'alt',mk=(tr.metode_bayar||'').toLowerCase();
    var bc='bdg-'+(mk||'tunai'),ml=mk.charAt(0).toUpperCase()+mk.slice(1);
    html+='<tr class="'+alt+'"><td style="text-align:center;color:#9AAAC8">'+(gi+1)+'</td>'+
      '<td><div>'+fmtD(tr.tgl_bayar)+'</div><div style="font-size:10px;color:#9AAAC8">'+fmtJ(tr.tgl_bayar)+'</div></td>'+
      '<td><strong>'+esc(tr.nama)+'</strong></td>'+
      '<td style="font-family:monospace;font-size:11.5px;color:#5A6A8A">'+esc(tr.nis)+'</td>'+
      '<td>'+esc(tr.kelas)+'</td>'+
      '<td>'+(BULAN_INDO[parseInt(tr.t_bulan)]||tr.t_bulan)+' '+tr.t_tahun+'</td>'+
      '<td><span class="bdg '+bc+'">'+esc(ml)+'</span></td>'+
      '<td style="text-align:right;font-weight:600">'+fmtR(tr.jumlah_bayar)+'</td>'+
      '<td style="font-size:11px;color:#5A6A8A">'+esc(tr.nama_admin||'&ndash;')+'</td></tr>';
  });
  el.innerHTML=html;
  var info=document.getElementById('lapPagInfo');
  if(info)info.textContent='Menampilkan '+(total===0?0:start+1)+'&ndash;'+end+' dari '+total;
  buildPager('lapPagination',page,tp,'lapChangePage');
}
/* Card Transaksi */
var lapCurCard=1;
function lapGetPPC(){return parseInt((document.getElementById('lapPerPageCard')||{value:'24'}).value)||24;}
function lapChangePageCard(p){lapCurCard=p;lapRenderCards(p);}
function lapRenderCards(page){
  var el=document.getElementById('lapCardsGrid');if(!el)return;
  var pp=lapGetPPC(),data=LAP_DATA,total=data.length,tp=Math.max(1,Math.ceil(total/pp));
  page=Math.min(Math.max(1,page),tp);lapCurCard=page;
  var start=(page-1)*pp,end=Math.min(start+pp,total),html='';
  data.slice(start,end).forEach(function(tr,i){
    var gi=start+i,col=AVATAR_COLORS[gi%AVATAR_COLORS.length];
    var mk=(tr.metode_bayar||'').toLowerCase(),ms=METODE_STYLE[mk]||{label:mk,bar:'#94A3B8',bg:'#F1F5F9',color:'#475569'};
    html+='<div class="lap-card">'+
      '<div class="lap-card-bar" style="background:'+ms.bar+'"></div>'+
      '<div class="lap-card-body">'+
        '<div class="lap-card-top">'+
          '<div class="lap-card-ava" style="background:'+col+'">'+(tr.nama?tr.nama.charAt(0).toUpperCase():'?')+'</div>'+
          '<div style="flex:1;min-width:0"><div class="lap-card-name">'+esc(tr.nama)+'</div><div class="lap-card-sub">'+esc(tr.nis)+' &middot; '+esc((tr.kelas||'')+' '+(tr.jurusan||''))+'</div></div>'+
          '<div class="lap-card-amount">'+fmtR(tr.jumlah_bayar)+'</div>'+
        '</div>'+
        '<hr class="lap-card-hr">'+
        '<div class="lap-card-rows">'+
          '<div class="lap-card-row"><span class="lap-card-lbl">Periode</span><span class="lap-card-val">'+(BULAN_INDO[parseInt(tr.t_bulan)]||tr.t_bulan)+' '+tr.t_tahun+'</span></div>'+
          '<div class="lap-card-row"><span class="lap-card-lbl">Metode</span><span class="lap-metode-pill" style="background:'+ms.bg+';color:'+ms.color+'">'+ms.label+'</span></div>'+
          '<div class="lap-card-row"><span class="lap-card-lbl">Waktu</span><span class="lap-card-val">'+fmtD(tr.tgl_bayar)+' '+fmtJ(tr.tgl_bayar)+'</span></div>'+
        '</div>'+
      '</div>'+
      '<div class="lap-card-footer"><div class="lap-card-num">'+(gi+1)+'</div><span style="font-size:11px;color:var(--text3)">'+esc(tr.nis)+'</span></div>'+
    '</div>';
  });
  el.innerHTML=html;
  var info=document.getElementById('lapPagInfoCard');
  if(info)info.textContent='Menampilkan '+(total===0?0:start+1)+'-'+end+' dari '+total;
  buildPager('lapPaginationCard',page,tp,'lapChangePageCard');
}
function lapSwitchView(mode){
  var isTbl=mode==='table';
  var vt=document.getElementById('lapViewTable'),vc=document.getElementById('lapViewCards');
  if(vt)vt.style.display=isTbl?'block':'none';
  if(vc)vc.style.display=isTbl?'none':'block';
  var bt=document.getElementById('lapBtnTable'),bc=document.getElementById('lapBtnCard');
  if(bt)bt.classList.toggle('active',isTbl);
  if(bc)bc.classList.toggle('active',!isTbl);
  try{localStorage.setItem('laporan_view',mode);}catch(e){}
  if(isTbl)lapRenderTable(lapCurPage);else lapRenderCards(lapCurCard);
}
function toggleFilter(tipe){
  var t=['harian','bulanan','tahunan'];
  t.forEach(function(v){
    var el=document.getElementById('f'+v.charAt(0).toUpperCase()+v.slice(1));
    if(el)el.style.display=(v===tipe)?'contents':'none';
  });
  var fb=document.getElementById('fBulanan');
  if(fb)fb.style.display=(tipe==='bulanan')?'contents':'none';
}

function toggleKop(){
  var kop = document.getElementById('kopSurat');
  var btn = document.getElementById('btnKop');
  if(!kop) return;
  if(kop.style.display==='none'||kop.style.display===''){
    kop.style.display='block';
    if(btn) btn.style.background='var(--indigo-light)';
  } else {
    kop.style.display='none';
    if(btn) btn.style.background='';
  }
}

/* Kelas Tab */
function ktabPilih(idx){
  var tabs=document.querySelectorAll('.ktab-item');
  var panes=document.querySelectorAll('.ktab-pane');
  tabs.forEach(function(el){el.classList.remove('active');});
  panes.forEach(function(el){el.classList.remove('active');el.style.display='none';});
  if(tabs[idx])tabs[idx].classList.add('active');
  if(panes[idx]){panes[idx].classList.add('active');panes[idx].style.display='flex';}
  if(window.innerWidth<900&&panes[idx])panes[idx].scrollIntoView({behavior:'smooth',block:'start'});
}

/* Pane filter */
function paneFilter(paneId,f,btn){
  var pane=document.getElementById(paneId);if(!pane)return;
  pane.querySelectorAll('.pane-chip').forEach(function(b){b.classList.remove('on');});
  if(btn)btn.classList.add('on');
  pane.querySelectorAll('tbody tr[data-status]').forEach(function(tr){
    var st=tr.getAttribute('data-status');
    var show=f==='semua'||st===f||(f==='belum'&&(st==='belum'||st==='notag'));
    tr.style.display=show?'':'none';
  });
  var n=0;
  pane.querySelectorAll('tbody tr[data-status]').forEach(function(tr){
    if(tr.style.display!=='none'){n++;var td=tr.querySelector('td');if(td)td.textContent=n;}
  });
}

/* Kartu search */
var _kTimer=null;
function kartuSearch(q){
  clearTimeout(_kTimer);
  var drop=document.getElementById('kartuDrop');if(!drop)return;
  if(q.trim().length<2){drop.style.display='none';return;}
  _kTimer=setTimeout(function(){
    fetch('index.php?page=laporan&_ajax=cari_siswa&q='+encodeURIComponent(q))
      .then(function(r){return r.json();})
      .then(function(data){
        if(!data.length){drop.style.display='none';return;}
        var html='';
        data.forEach(function(s,i){
          var ac=AVATAR_COLORS[i%AVATAR_COLORS.length];
          var avaHtml;
          if(s.foto){
            avaHtml='<img src="uploads/foto_siswa/'+s.foto+'" style="width:36px;height:36px;border-radius:9px;object-fit:cover;flex-shrink:0" onerror="this.style.display=\'none\';this.nextElementSibling.style.display=\'flex\'">'
              +'<div style="width:36px;height:36px;border-radius:9px;background:'+ac+';display:none;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#fff;flex-shrink:0">'+s.nama.charAt(0).toUpperCase()+'</div>';
          } else {
            avaHtml='<div style="width:36px;height:36px;border-radius:9px;background:'+ac+';display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;color:#fff;flex-shrink:0">'+s.nama.charAt(0).toUpperCase()+'</div>';
          }
          html+='<div class="ksearch-item" onclick="kartuPilih('+s.id+',\''+esc(s.nama)+'\')">'
            +avaHtml
            +'<div><div style="font-weight:600;font-size:13px;color:#1E2D4E">'+esc(s.nama)+'</div>'
            +'<div style="font-size:11px;color:#9AAAC8">NIS: '+esc(s.nis)+' &middot; '+esc(s.kelas)+' '+esc(s.jurusan)+'</div></div>'
            +'</div>';
        });
        drop.innerHTML=html;drop.style.display='block';
      }).catch(function(){drop.style.display='none';});
  },280);
}
function kartuPilih(id,nama){
  var inp=document.getElementById('kartuInput');if(inp)inp.value=nama;
  var drop=document.getElementById('kartuDrop');if(drop)drop.style.display='none';
  window.location='index.php?page=laporan&view=kartu_siswa&siswa_id='+id;
}
document.addEventListener('click',function(e){
  var w=document.getElementById('kartuWrap');
  if(w&&!w.contains(e.target)){var d=document.getElementById('kartuDrop');if(d)d.style.display='none';}
});

/* Init */
(function(){
  if(LAP_DATA.length>0){
    lapRenderTable(1);
    var saved=null;try{saved=localStorage.getItem('laporan_view');}catch(e){}
    lapSwitchView(saved||'table');
  }
  /* Saat print: tampilkan semua baris tersembunyi & restore setelah print */
  var hiddenRows=[];
  window.addEventListener('beforeprint',function(){
    hiddenRows=[];
    document.querySelectorAll('tr[data-status][style*="display: none"]').forEach(function(tr){
      hiddenRows.push(tr);
      tr.style.display='';
    });
    /* Renumber setelah semua ditampilkan */
    document.querySelectorAll('.ktab-pane tbody').forEach(function(tbody){
      var n=0;
      tbody.querySelectorAll('tr[data-status]').forEach(function(tr){
        n++;var td=tr.querySelector('td');if(td)td.textContent=n;
      });
    });
  });
  window.addEventListener('afterprint',function(){
    hiddenRows.forEach(function(tr){tr.style.display='none';});
    hiddenRows=[];
  });
})();
</script>
<?php require_once 'layout/footer.php'; ?>