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

$tahunAjaranList = $pdo->query("SELECT * FROM tahun_ajaran ORDER BY nama DESC")->fetchAll();
$tahunAktif = getTahunAjaranAktif($pdo);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'generate') {
        $bulan = (int)$_POST['bulan'];
        $tahun = (int)$_POST['tahun'];
        $tahunAjaranId = (int)$_POST['tahun_ajaran_id'];
        $jatuhTempo = $tahun . '-' . str_pad($bulan, 2, '0', STR_PAD_LEFT) . '-10';

        $siswaAktif = $pdo->query("SELECT id, nominal_spp FROM siswa WHERE status='aktif'")->fetchAll();
        $stmtCek = $pdo->prepare("SELECT COUNT(*) FROM tagihan_spp WHERE siswa_id=:sid AND tahun_ajaran_id=:taid AND bulan=:b AND tahun=:t");
        $stmtIns = $pdo->prepare("INSERT INTO tagihan_spp (siswa_id, tahun_ajaran_id, bulan, tahun, nominal, jatuh_tempo) VALUES (:sid,:taid,:b,:t,:nominal,:jt)");

        $jumlahDibuat = 0;
        foreach ($siswaAktif as $s) {
            $stmtCek->execute(['sid'=>$s['id'],'taid'=>$tahunAjaranId,'b'=>$bulan,'t'=>$tahun]);
            $sudahAda = $stmtCek->fetchColumn();
            $stmtCek->closeCursor();
            if ($sudahAda == 0) {
                $stmtIns->execute(['sid'=>$s['id'],'taid'=>$tahunAjaranId,'b'=>$bulan,'t'=>$tahun,'nominal'=>$s['nominal_spp'],'jt'=>$jatuhTempo]);
                $stmtIns->closeCursor();
                $jumlahDibuat++;
            }
        }
        flash('success', "Tagihan SPP bulan " . namaBulan($bulan) . " $tahun berhasil dibuat untuk $jumlahDibuat siswa.");
    } elseif ($action === 'delete') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT jumlah_dibayar FROM tagihan_spp WHERE id=:id"); $cek->execute(['id'=>$id]);
        $row = $cek->fetch();
        if ($row && $row['jumlah_dibayar'] > 0) {
            flash('error', 'Tagihan tidak dapat dihapus karena sudah ada pembayaran.');
        } else {
            $pdo->prepare("DELETE FROM tagihan_spp WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Tagihan berhasil dihapus.');
        }
    }
    header('Location: tagihan_spp.php' . (isset($_GET['filter']) ? '?' . $_SERVER['QUERY_STRING'] : ''));
    exit;
}

// Filter
$fBulan = $_GET['bulan'] ?? date('m');
$fTahun = $_GET['tahun'] ?? date('Y');
$fStatus = $_GET['status'] ?? '';
$fKelas = $_GET['kelas_id'] ?? '';

$sql = "SELECT ts.*, s.nis, s.nama as nama_siswa, 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";
$params = ['bulan'=>$fBulan, 'tahun'=>$fTahun];
if ($fStatus) { $sql .= " AND ts.status = :status"; $params['status'] = $fStatus; }
if ($fKelas) { $sql .= " AND s.kelas_id = :kelas_id"; $params['kelas_id'] = $fKelas; }
$sql .= " ORDER BY s.nama";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$tagihanList = $stmt->fetchAll();

$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">
    <h5 class="mb-0">Tagihan SPP</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalGenerate"><i class="bi bi-magic"></i> Generate Tagihan Bulanan</button>
</div>

<div class="card mb-3">
    <div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-2">
                <select name="bulan" class="form-select">
                    <?php for ($i=1;$i<=12;$i++): ?>
                        <option value="<?= $i ?>" <?= $i==$fBulan?'selected':'' ?>><?= namaBulan($i) ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2"><input type="number" name="tahun" value="<?= htmlspecialchars($fTahun) ?>" class="form-control" placeholder="Tahun"></div>
            <div class="col-md-3">
                <select name="kelas_id" class="form-select">
                    <option value="">Semua Kelas</option>
                    <?php foreach ($kelasList as $k): ?>
                        <option value="<?= $k['id'] ?>" <?= $fKelas==$k['id']?'selected':'' ?>><?= htmlspecialchars(formatKelasLabel($k['tingkat_nama'], $k['nama'])) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="">Semua Status</option>
                    <option value="lunas" <?= $fStatus=='lunas'?'selected':'' ?>>Lunas</option>
                    <option value="belum_lunas" <?= $fStatus=='belum_lunas'?'selected':'' ?>>Belum Lunas</option>
                </select>
            </div>
            <div class="col-md-2"><button class="btn btn-outline-primary w-100"><i class="bi bi-funnel"></i> Filter</button></div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead><tr><th>NIS</th><th>Nama</th><th>Kelas</th><th>Bulan</th><th>Nominal</th><th>Dibayar</th><th>Status</th><th>Aksi</th></tr></thead>
            <tbody>
            <?php foreach ($tagihanList as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['nis']) ?></td>
                    <td><?= htmlspecialchars($row['nama_siswa']) ?></td>
                    <td><?= htmlspecialchars(formatKelasLabel($row['tingkat_nama'] ?? '', $row['kelas_nama'] ?? '')) ?></td>
                    <td><?= namaBulan($row['bulan']) . ' ' . $row['tahun'] ?></td>
                    <td><?= rupiah($row['nominal']) ?></td>
                    <td><?= 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>
                        <?php if ($row['status'] !== 'lunas'): ?>
                            <a href="pembayaran_spp.php?siswa_id=<?= $row['siswa_id'] ?>" class="btn btn-sm btn-success"><i class="bi bi-cash"></i> Bayar</a>
                        <?php endif; ?>
                        <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php if (empty($tagihanList)): ?>
            <p class="text-center text-muted py-3 mb-0">Belum ada tagihan untuk periode ini. Klik "Generate Tagihan Bulanan".</p>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="modalGenerate" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Generate Tagihan SPP Bulanan</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <input type="hidden" name="action" value="generate">
                <p class="text-muted small">Sistem akan membuat tagihan SPP untuk semua siswa berstatus aktif sesuai nominal SPP masing-masing. Tagihan yang sudah ada tidak akan dibuat ulang.</p>
                <div class="mb-3">
                    <label class="form-label">Tahun Ajaran</label>
                    <select name="tahun_ajaran_id" class="form-select" required>
                        <?php foreach ($tahunAjaranList as $ta): ?>
                            <option value="<?= $ta['id'] ?>" <?= ($tahunAktif && $ta['id']==$tahunAktif['id'])?'selected':'' ?>><?= htmlspecialchars($ta['nama'].' - '.$ta['semester']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="row">
                    <div class="col-6 mb-3">
                        <label class="form-label">Bulan</label>
                        <select name="bulan" class="form-select">
                            <?php for ($i=1;$i<=12;$i++): ?>
                                <option value="<?= $i ?>" <?= $i==date('m')?'selected':'' ?>><?= namaBulan($i) ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-6 mb-3">
                        <label class="form-label">Tahun</label>
                        <input type="number" name="tahun" value="<?= date('Y') ?>" class="form-control" required>
                    </div>
                </div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button><button class="btn btn-primary">Generate</button></div>
        </form>
    </div>
</div>

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