<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Pembayaran SPP';

// Kategori default untuk SPP
$kategoriSpp = $pdo->query("SELECT id FROM kategori WHERE kelompok='spp' AND tipe='pemasukan' AND status='aktif' LIMIT 1")->fetch();
$kategoriSppId = $kategoriSpp['id'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'bayar') {
    $siswaId = $_POST['siswa_id'];
    $akunId = $_POST['akun_id'];
    $tanggal = $_POST['tanggal'];
    $tagihanIds = $_POST['tagihan_ids'] ?? [];

    if (empty($tagihanIds)) {
        flash('error', 'Pilih minimal satu tagihan untuk dibayar.');
        header("Location: pembayaran_spp.php?siswa_id=$siswaId");
        exit;
    }

    $idTransaksiPertama = null;
    foreach ($tagihanIds as $tid) {
        $stmt = $pdo->prepare("SELECT * FROM tagihan_spp WHERE id=:id");
        $stmt->execute(['id'=>$tid]);
        $tagihan = $stmt->fetch();
        $stmt->closeCursor();
        if (!$tagihan || $tagihan['status'] === 'lunas') continue;

        $sisaBayar = $tagihan['nominal'] - $tagihan['jumlah_dibayar'];

        $noTransaksi = generateNoTransaksi($pdo, 'pemasukan');
        $stmtInsTx = $pdo->prepare("INSERT INTO transaksi (no_transaksi, tanggal, tipe, kategori_id, akun_id, jumlah, keterangan, siswa_id, tagihan_id, created_by)
                       VALUES (:no, :tgl, 'pemasukan', :kat, :akun, :jml, :ket, :siswa, :tagihan, :uid)");
        $stmtInsTx->execute([
                'no'=>$noTransaksi, 'tgl'=>$tanggal, 'kat'=>$kategoriSppId, 'akun'=>$akunId,
                'jml'=>$sisaBayar, 'ket'=>'Pembayaran SPP bulan ' . namaBulan($tagihan['bulan']) . ' ' . $tagihan['tahun'],
                'siswa'=>$siswaId, 'tagihan'=>$tid, 'uid'=>currentUser()['id']
            ]);
        $stmtInsTx->closeCursor();
        $idTransaksiPertama = $idTransaksiPertama ?? $pdo->lastInsertId();

        $pdo->prepare("UPDATE tagihan_spp SET jumlah_dibayar = nominal, status='lunas' WHERE id=:id")->execute(['id'=>$tid]);
    }

    flash('success', 'Pembayaran SPP berhasil dicatat.');
    header("Location: cetak_kwitansi.php?id=$idTransaksiPertama");
    exit;
}

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

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 * FROM tagihan_spp WHERE siswa_id=:id AND status='belum_lunas' ORDER BY tahun, bulan");
        $stmt->execute(['id'=>$siswaTerpilih['id']]);
        $tagihanBelumLunas = $stmt->fetchAll();
    }
}

$daftarSiswa = [];
if ($searchNama) {
    $stmt = $pdo->prepare("SELECT s.*, k.nama as kelas_nama FROM siswa s LEFT JOIN kelas k ON k.id=s.kelas_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();
}

$akunList = $pdo->query("SELECT * FROM akun_kas WHERE status='aktif' ORDER BY nama_akun")->fetchAll();

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

<h5 class="mb-3">Pembayaran SPP</h5>

<div class="card mb-3">
    <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($s['kelas_nama'] ?? '-') ?></td>
                        <td><a href="pembayaran_spp.php?siswa_id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary">Pilih</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<?php if ($siswaTerpilih): ?>
<div class="card">
    <div class="card-header">Bayar SPP - <?= htmlspecialchars($siswaTerpilih['nama']) ?> (<?= htmlspecialchars($siswaTerpilih['nis']) ?>)</div>
    <div class="card-body">
        <?php if (empty($tagihanBelumLunas)): ?>
            <div class="text-center text-muted py-4"><i class="bi bi-check-circle fs-2 text-success"></i><p class="mt-2 mb-0">Siswa ini tidak memiliki tunggakan SPP.</p></div>
        <?php else: ?>
        <form method="POST">
            <input type="hidden" name="action" value="bayar">
            <input type="hidden" name="siswa_id" value="<?= $siswaTerpilih['id'] ?>">
            <table class="table">
                <thead><tr><th width="40"><input type="checkbox" onclick="document.querySelectorAll('.chk-tagihan').forEach(c=>c.checked=this.checked)"></th><th>Bulan</th><th>Nominal</th><th>Sisa Bayar</th></tr></thead>
                <tbody>
                <?php foreach ($tagihanBelumLunas as $t): ?>
                    <tr>
                        <td><input type="checkbox" class="chk-tagihan" name="tagihan_ids[]" value="<?= $t['id'] ?>"></td>
                        <td><?= namaBulan($t['bulan']) . ' ' . $t['tahun'] ?></td>
                        <td><?= rupiah($t['nominal']) ?></td>
                        <td><?= rupiah($t['nominal'] - $t['jumlah_dibayar']) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div class="row">
                <div class="col-md-4 mb-3">
                    <label class="form-label">Tanggal Bayar</label>
                    <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Akun Penerima</label>
                    <select name="akun_id" class="form-select" required>
                        <?php foreach ($akunList as $a): ?>
                            <option value="<?= $a['id'] ?>"><?= htmlspecialchars($a['nama_akun']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <button class="btn btn-success"><i class="bi bi-cash-coin"></i> Simpan Pembayaran</button>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

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