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

$searchNama = $_GET['q'] ?? '';
$siswaTerpilih = null;
$riwayatTagihan = [];

if (!empty($_GET['siswa_id'])) {
    $stmt = $pdo->prepare("
        SELECT s.*, k.nama as kelas_nama, t.nama as tingkat_nama
        FROM siswa s LEFT JOIN kelas k ON k.id=s.kelas_id LEFT JOIN tingkat t ON t.id=k.tingkat_id
        WHERE s.id=:id
    ");
    $stmt->execute(['id' => $_GET['siswa_id']]);
    $siswaTerpilih = $stmt->fetch();

    if ($siswaTerpilih) {
        $stmt = $pdo->prepare("
            SELECT ts.*, ta.nama as tahun_ajaran_nama,
                tr.tanggal as tanggal_bayar, tr.no_transaksi, a.nama_akun
            FROM tagihan_spp ts
            JOIN tahun_ajaran ta ON ta.id = ts.tahun_ajaran_id
            LEFT JOIN transaksi tr ON tr.tagihan_id = ts.id
            LEFT JOIN akun_kas a ON a.id = tr.akun_id
            WHERE ts.siswa_id = :id
            ORDER BY ts.tahun DESC, ts.bulan DESC
        ");
        $stmt->execute(['id' => $siswaTerpilih['id']]);
        $riwayatTagihan = $stmt->fetchAll();
    }
}

$daftarSiswa = [];
if ($searchNama) {
    $stmt = $pdo->prepare("
        SELECT s.*, k.nama as kelas_nama, t.nama as tingkat_nama
        FROM siswa s LEFT JOIN kelas k ON k.id=s.kelas_id LEFT JOIN tingkat t ON t.id=k.tingkat_id
        WHERE s.nama LIKE :q1 OR s.nis LIKE :q2 ORDER BY s.nama LIMIT 15
    ");
    $stmt->execute(['q1' => '%' . $searchNama . '%', 'q2' => '%' . $searchNama . '%']);
    $daftarSiswa = $stmt->fetchAll();
}

// Ringkasan
$totalTertagih = array_sum(array_column($riwayatTagihan, 'nominal'));
$totalTerbayar = array_sum(array_column($riwayatTagihan, 'jumlah_dibayar'));
$jmlLunas = count(array_filter($riwayatTagihan, fn($r) => $r['status'] === 'lunas'));
$jmlBelum = count(array_filter($riwayatTagihan, fn($r) => $r['status'] === 'belum_lunas'));

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">Laporan Pembayaran per Siswa</h5>
    <?php if ($siswaTerpilih): ?>
        <button class="btn btn-outline-secondary" onclick="window.print()"><i class="bi bi-printer"></i> Cetak</button>
    <?php endif; ?>
</div>

<div class="card mb-3 no-print">
    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-8">
                <input type="text" name="q" class="form-control" placeholder="Cari nama siswa atau NIS..." value="<?= htmlspecialchars($searchNama) ?>">
            </div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="bi bi-search"></i> Cari</button></div>
        </form>

        <?php if ($daftarSiswa): ?>
            <table class="table table-hover mt-3">
                <thead><tr><th>NIS</th><th>Nama</th><th>Kelas</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($daftarSiswa as $s): ?>
                    <tr>
                        <td><?= htmlspecialchars($s['nis']) ?></td>
                        <td><?= htmlspecialchars($s['nama']) ?></td>
                        <td><?= htmlspecialchars(formatKelasLabel($s['tingkat_nama'] ?? '', $s['kelas_nama'] ?? '')) ?></td>
                        <td><a href="laporan_per_siswa.php?siswa_id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary">Lihat Riwayat</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php elseif ($searchNama): ?>
            <p class="text-muted mt-3 mb-0">Tidak ada siswa yang cocok dengan pencarian "<?= htmlspecialchars($searchNama) ?>".</p>
        <?php endif; ?>
    </div>
</div>

<?php if ($siswaTerpilih): ?>
<div class="card">
    <div class="card-body">
        <?= renderKopSurat(getPengaturan($pdo)) ?>
        <div class="judul-laporan-resmi d-none d-print-block">
            <h5>LAPORAN RIWAYAT PEMBAYARAN SPP</h5>
        </div>

        <div class="d-flex justify-content-between align-items-start flex-wrap mb-3">
            <div>
                <h5 class="mb-1"><?= htmlspecialchars($siswaTerpilih['nama']) ?></h5>
                <div class="text-muted">
                    NIS: <?= htmlspecialchars($siswaTerpilih['nis']) ?>
                    &nbsp;|&nbsp; Kelas: <?= htmlspecialchars(formatKelasLabel($siswaTerpilih['tingkat_nama'] ?? '', $siswaTerpilih['kelas_nama'] ?? '')) ?>
                    &nbsp;|&nbsp; Ortu/Wali: <?= htmlspecialchars($siswaTerpilih['nama_ortu'] ?: '-') ?>
                </div>
            </div>
            <span class="badge text-bg-<?= $siswaTerpilih['status']==='aktif'?'success':'secondary' ?> fs-6"><?= ucfirst($siswaTerpilih['status']) ?></span>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3 col-6">
                <div class="card stat-card p-3"><div class="text-muted small">Bulan Lunas</div><div class="fw-bold fs-5 text-success"><?= $jmlLunas ?></div></div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card stat-card p-3"><div class="text-muted small">Bulan Belum Lunas</div><div class="fw-bold fs-5 text-danger"><?= $jmlBelum ?></div></div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card stat-card p-3"><div class="text-muted small">Total Tertagih</div><div class="fw-bold fs-5"><?= rupiah($totalTertagih) ?></div></div>
            </div>
            <div class="col-md-3 col-6">
                <div class="card stat-card p-3"><div class="text-muted small">Total Terbayar</div><div class="fw-bold fs-5"><?= rupiah($totalTerbayar) ?></div></div>
            </div>
        </div>

        <table class="table table-bordered table-hover">
            <thead>
                <tr><th>Bulan</th><th>Tahun Ajaran</th><th class="text-end">Nominal</th><th class="text-end">Dibayar</th><th>Status</th><th>Tanggal Bayar</th><th>No. Transaksi</th><th class="no-print">Aksi</th></tr>
            </thead>
            <tbody>
            <?php foreach ($riwayatTagihan as $row): ?>
                <tr>
                    <td><?= namaBulan($row['bulan']) . ' ' . $row['tahun'] ?></td>
                    <td><?= htmlspecialchars($row['tahun_ajaran_nama']) ?></td>
                    <td class="text-end"><?= rupiah($row['nominal']) ?></td>
                    <td class="text-end"><?= rupiah($row['jumlah_dibayar']) ?></td>
                    <td><span class="badge <?= $row['status']==='lunas' ? 'badge-lunas' : 'badge-belum' ?>"><?= $row['status']==='lunas' ? 'Lunas' : 'Belum Lunas' ?></span></td>
                    <td><?= $row['tanggal_bayar'] ? tanggalIndo($row['tanggal_bayar']) : '-' ?></td>
                    <td><?= htmlspecialchars($row['no_transaksi'] ?? '-') ?></td>
                    <td class="no-print">
                        <?php if ($row['status'] !== 'lunas'): ?>
                            <a href="pembayaran_spp.php?siswa_id=<?= $siswaTerpilih['id'] ?>" class="btn btn-sm btn-success">Bayar</a>
                        <?php elseif (!empty($row['no_transaksi'])): ?>
                            <?php
                                $txId = $pdo->prepare("SELECT id FROM transaksi WHERE tagihan_id=:tid LIMIT 1");
                                $txId->execute(['tid' => $row['id']]);
                                $txRow = $txId->fetch();
                                $txId->closeCursor();
                            ?>
                            <?php if ($txRow): ?>
                                <a href="cetak_kwitansi.php?id=<?= $txRow['id'] ?>" class="btn btn-sm btn-outline-secondary" target="_blank">Kwitansi</a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($riwayatTagihan)): ?>
                <tr><td colspan="8" class="text-center text-muted py-4">Belum ada riwayat tagihan SPP untuk siswa ini.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
        <?= renderTandaTanganLaporan(getPengaturan($pdo)) ?>
    </div>
</div>
<?php endif; ?>

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