<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Siswa Belum Bayar';

$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');
$kelasId = $_GET['kelas_id'] ?? '';

$sql = "
    SELECT ts.*, s.nis, s.nama as nama_siswa, s.nama_ortu, s.no_hp_ortu,
           k.nama as kelas_nama, t.nama as tingkat_nama
    FROM tagihan_spp ts
    JOIN siswa s ON s.id = ts.siswa_id
    LEFT JOIN kelas k ON k.id = s.kelas_id
    LEFT JOIN tingkat t ON t.id = k.tingkat_id
    WHERE ts.bulan = :bulan AND ts.tahun = :tahun AND ts.status = 'belum_lunas' AND s.status = 'aktif'
";
$params = ['bulan' => $bulan, 'tahun' => $tahun];
if ($kelasId) { $sql .= " AND s.kelas_id = :kelas_id"; $params['kelas_id'] = $kelasId; }
$sql .= " ORDER BY t.nama, k.nama, s.nama";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll();

// Kelompokkan per kelas supaya enak dibaca & ditagih per kelas
$perKelas = [];
foreach ($data as $row) {
    $namaKelas = formatKelasLabel($row['tingkat_nama'] ?? '', $row['kelas_nama'] ?? '');
    if ($namaKelas === '') $namaKelas = 'Tanpa Kelas';
    if (!isset($perKelas[$namaKelas])) $perKelas[$namaKelas] = [];
    $perKelas[$namaKelas][] = $row;
}

$totalSiswa = count($data);
$totalTunggakan = array_sum(array_map(fn($r) => $r['nominal'] - $r['jumlah_dibayar'], $data));

$kelasList = $pdo->query("SELECT k.*, t.nama as tingkat_nama FROM kelas k JOIN tingkat t ON t.id=k.tingkat_id ORDER BY t.nama, k.nama")->fetchAll();

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3 no-print">
    <h5 class="mb-0">Siswa Belum Bayar SPP</h5>
    <button class="btn btn-outline-secondary" onclick="window.print()"><i class="bi bi-printer"></i> Cetak</button>
</div>

<div class="card mb-3 no-print">
    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-3">
                <select name="bulan" class="form-select">
                    <?php for ($i=1;$i<=12;$i++): ?><option value="<?= $i ?>" <?= $i==$bulan?'selected':'' ?>><?= namaBulan($i) ?></option><?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2"><input type="number" name="tahun" value="<?= htmlspecialchars($tahun) ?>" class="form-control"></div>
            <div class="col-md-4">
                <select name="kelas_id" class="form-select">
                    <option value="">Semua Kelas</option>
                    <?php foreach ($kelasList as $k): ?>
                        <option value="<?= $k['id'] ?>" <?= $kelasId==$k['id']?'selected':'' ?>><?= htmlspecialchars(formatKelasLabel($k['tingkat_nama'], $k['nama'])) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="bi bi-funnel"></i> Tampilkan</button></div>
        </form>
    </div>
</div>


<div class="row g-3 mb-3 no-print">
    <div class="col-md-4 col-6">
        <div class="card stat-card p-3"><div class="text-muted small">Periode</div><div class="fw-bold"><?= namaBulan($bulan) ?> <?= $tahun ?></div></div>
    </div>
    <div class="col-md-4 col-6">
        <div class="card stat-card p-3"><div class="text-muted small">Jumlah Siswa Belum Bayar</div><div class="fw-bold fs-5 text-danger"><?= $totalSiswa ?></div></div>
    </div>
    <div class="col-md-4 col-6">
        <div class="card stat-card p-3"><div class="text-muted small">Total Tunggakan</div><div class="fw-bold fs-5 text-danger"><?= rupiah($totalTunggakan) ?></div></div>
    </div>
</div>

<?php if (empty($perKelas)): ?>
    <div class="card">
        <div class="card-body text-center text-muted py-5">
            <i class="bi bi-check-circle fs-2 text-success"></i>
            <p class="mt-2 mb-0">Semua siswa sudah membayar SPP untuk periode ini. 🎉</p>
        </div>
    </div>
<?php else: ?>
    <?php
    $MAKS_PER_HALAMAN = 25;
    $totalKelas = count($perKelas);
    $iKelas = 0;
    ?>
    <?php foreach ($perKelas as $namaKelas => $siswaList): ?>
        <?php
        $iKelas++;
        $kelasTerakhir = $iKelas === $totalKelas;
        $chunks = array_chunk($siswaList, $MAKS_PER_HALAMAN);
        $totalChunk = count($chunks);
        $nomorMulai = 1;
        ?>
        <?php foreach ($chunks as $ci => $chunkSiswa): ?>
            <?php
            $chunkTerakhir = ($ci === $totalChunk - 1);
            $halamanTerakhirKeseluruhan = $kelasTerakhir && $chunkTerakhir;
            ?>
            <div class="card mb-3 <?= !$halamanTerakhirKeseluruhan ? 'kelas-break' : '' ?>">
                <div class="card-header no-print">
                    Kelas <?= htmlspecialchars($namaKelas) ?>
                    <?= $totalChunk > 1 ? ' (Halaman ' . ($ci+1) . ' dari ' . $totalChunk . ')' : '' ?>
                    &mdash; <?= count($siswaList) ?> siswa belum bayar
                </div>
                <div class="card-body p-0">
                    <table class="table table-bordered mb-0">
                        <thead>
                            <tr class="d-none d-print-table-row"><td colspan="7" style="border:none; padding:0;"><?= renderKopSurat(getPengaturan($pdo)) ?></td></tr>
                            <tr class="d-none d-print-table-row"><td colspan="7" style="border:none; padding:0;" class="judul-laporan-resmi">
                                <h5 style="margin:0;">DAFTAR SISWA BELUM MEMBAYAR SPP &mdash; KELAS <?= strtoupper(htmlspecialchars($namaKelas)) ?></h5>
                                <p style="margin:0 0 6px;">Bulan <?= namaBulan($bulan) ?> <?= $tahun ?><?= $totalChunk > 1 ? ' (Halaman ' . ($ci+1) . '/' . $totalChunk . ')' : '' ?></p>
                            </td></tr>
                            <tr><th width="40">No</th><th>NIS</th><th>Nama Siswa</th><th class="text-end">Sisa Tagihan</th><th>Orang Tua/Wali</th><th>No. HP</th><th class="no-print"></th></tr>
                        </thead>
                        <tbody>
                        <?php foreach ($chunkSiswa as $j => $row): ?>
                            <tr>
                                <td><?= $nomorMulai + $j ?></td>
                                <td><?= htmlspecialchars($row['nis']) ?></td>
                                <td><?= htmlspecialchars($row['nama_siswa']) ?></td>
                                <td class="text-end text-danger fw-semibold"><?= rupiah($row['nominal'] - $row['jumlah_dibayar']) ?></td>
                                <td><?= htmlspecialchars($row['nama_ortu'] ?: '-') ?></td>
                                <td><?= htmlspecialchars($row['no_hp_ortu'] ?: '-') ?></td>
                                <td class="no-print"><a href="pembayaran_spp.php?siswa_id=<?= $row['siswa_id'] ?>" class="btn btn-sm btn-success">Bayar</a></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php if ($chunkTerakhir): ?>
                    <div class="card-body d-flex justify-content-between fw-bold border-top">
                        <span>Subtotal Kelas <?= htmlspecialchars($namaKelas) ?> (<?= count($siswaList) ?> siswa)</span>
                        <span class="text-danger"><?= rupiah(array_sum(array_map(fn($r) => $r['nominal'] - $r['jumlah_dibayar'], $siswaList))) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                <?php if ($chunkTerakhir): ?>
                    <div class="card-body"><?= renderTandaTanganLaporan(getPengaturan($pdo)) ?></div>
                <?php endif; ?>
            </div>
            <?php $nomorMulai += count($chunkSiswa); ?>
        <?php endforeach; ?>
    <?php endforeach; ?>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>