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

$kategoriList = $pdo->query("SELECT * FROM kategori WHERE tipe='pemasukan' AND status='aktif' ORDER BY kelompok, nama")->fetchAll();
$akunList = $pdo->query("SELECT * FROM akun_kas WHERE status='aktif' ORDER BY nama_akun")->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();

// ------------------------------------------------------------------
// SIMPAN PEMBAYARAN MASSAL (per kelas, banyak siswa sekaligus)
// ------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'bayar_massal') {
    $kategoriId = $_POST['kategori_id'];
    $akunId     = $_POST['akun_id'];
    $tanggal    = $_POST['tanggal'];
    $keteranganDasar = trim($_POST['keterangan']);
    $siswaIds   = $_POST['siswa_ids'] ?? [];
    $nominalMap = $_POST['nominal'] ?? [];

    if (empty($siswaIds)) {
        flash('error', 'Pilih minimal satu siswa untuk dicatat pembayarannya.');
        header("Location: pembayaran_kategori.php?kategori_id=$kategoriId&kelas_id=" . ($_POST['kelas_id'] ?? ''));
        exit;
    }

    $idTransaksiPertama = null;
    $jumlahDicatat = 0;
    foreach ($siswaIds as $sid) {
        $jumlah = (float) str_replace('.', '', $nominalMap[$sid] ?? '0');
        if ($jumlah <= 0) continue;

        $noTransaksi = generateNoTransaksi($pdo, 'pemasukan');
        $stmt = $pdo->prepare("
            INSERT INTO transaksi (no_transaksi, tanggal, tipe, kategori_id, akun_id, jumlah, keterangan, siswa_id, created_by)
            VALUES (:no, :tgl, 'pemasukan', :kat, :akun, :jml, :ket, :siswa, :uid)
        ");
        $stmt->execute([
            'no' => $noTransaksi, 'tgl' => $tanggal, 'kat' => $kategoriId, 'akun' => $akunId,
            'jml' => $jumlah, 'ket' => $keteranganDasar, 'siswa' => $sid, 'uid' => currentUser()['id'],
        ]);
        $stmt->closeCursor();
        $idTransaksiPertama = $idTransaksiPertama ?? $pdo->lastInsertId();
        $jumlahDicatat++;
    }

    if ($jumlahDicatat === 1) {
        header("Location: cetak_kwitansi.php?id=$idTransaksiPertama");
        exit;
    }

    flash('success', "Pembayaran berhasil dicatat untuk $jumlahDicatat siswa.");
    header("Location: pembayaran_kategori.php?kategori_id=$kategoriId&kelas_id=" . ($_POST['kelas_id'] ?? ''));
    exit;
}

// ------------------------------------------------------------------
// SIMPAN PEMBAYARAN SATUAN (cari per nama/NIS, satu siswa)
// ------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'bayar_satuan') {
    $kategoriId = $_POST['kategori_id'];
    $siswaId    = $_POST['siswa_id'];
    $akunId     = $_POST['akun_id'];
    $tanggal    = $_POST['tanggal'];
    $jumlah     = (float) str_replace('.', '', $_POST['jumlah']);
    $keterangan = trim($_POST['keterangan']);

    $buktiFile = null;
    if (!empty($_FILES['bukti']['name'])) {
        $ext = pathinfo($_FILES['bukti']['name'], PATHINFO_EXTENSION);
        $buktiFile = 'bukti_' . time() . '_' . rand(100,999) . '.' . $ext;
        move_uploaded_file($_FILES['bukti']['tmp_name'], __DIR__ . '/assets/uploads/bukti/' . $buktiFile);
    }

    $noTransaksi = generateNoTransaksi($pdo, 'pemasukan');
    $stmt = $pdo->prepare("
        INSERT INTO transaksi (no_transaksi, tanggal, tipe, kategori_id, akun_id, jumlah, keterangan, siswa_id, bukti_file, created_by)
        VALUES (:no, :tgl, 'pemasukan', :kat, :akun, :jml, :ket, :siswa, :bukti, :uid)
    ");
    $stmt->execute([
        'no' => $noTransaksi, 'tgl' => $tanggal, 'kat' => $kategoriId, 'akun' => $akunId,
        'jml' => $jumlah, 'ket' => $keterangan, 'siswa' => $siswaId, 'bukti' => $buktiFile,
        'uid' => currentUser()['id'],
    ]);
    $stmt->closeCursor();
    $idTransaksi = $pdo->lastInsertId();

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

$kategoriId = $_GET['kategori_id'] ?? '';
$kelasId    = $_GET['kelas_id'] ?? '';
$searchNama = $_GET['q'] ?? '';
$mode       = $_GET['mode'] ?? 'kelas'; // 'kelas' atau 'individual'

$kategoriTerpilih = null;
foreach ($kategoriList as $k) { if ($k['id'] == $kategoriId) { $kategoriTerpilih = $k; break; } }

$kelasTerpilihLabel = '';
foreach ($kelasList as $kl) { if ($kl['id'] == $kelasId) { $kelasTerpilihLabel = formatKelasLabel($kl['tingkat_nama'], $kl['nama']); break; } }

// Data untuk mode per kelas: daftar siswa di kelas + status sudah/belum bayar kategori ini
$siswaKelas = [];
if ($kategoriId && $kelasId && $mode === 'kelas') {
    $stmt = $pdo->prepare("
        SELECT s.*,
            (SELECT MAX(tr.tanggal) FROM transaksi tr WHERE tr.siswa_id = s.id AND tr.kategori_id = :kid) as terakhir_bayar,
            (SELECT COUNT(*) FROM transaksi tr WHERE tr.siswa_id = s.id AND tr.kategori_id = :kid2) as jml_bayar
        FROM siswa s
        WHERE s.kelas_id = :kelas_id AND s.status = 'aktif'
        ORDER BY s.nama
    ");
    $stmt->execute(['kid' => $kategoriId, 'kid2' => $kategoriId, 'kelas_id' => $kelasId]);
    $siswaKelas = $stmt->fetchAll();
}

// Data untuk mode individual: pencarian nama/NIS
$daftarSiswa = [];
$siswaTerpilih = null;
$riwayatSiswa = [];
if ($mode === 'individual' && $kategoriId) {
    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 tr.*, a.nama_akun FROM transaksi tr LEFT JOIN akun_kas a ON a.id=tr.akun_id WHERE tr.siswa_id=:sid AND tr.kategori_id=:kid ORDER BY tr.tanggal DESC");
            $stmt->execute(['sid' => $siswaTerpilih['id'], 'kid' => $kategoriId]);
            $riwayatSiswa = $stmt->fetchAll();
        }
    }
    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();
    }
}

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

<h5 class="mb-3">Pembayaran per Kategori</h5>

<div class="card mb-3">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end" id="formFilter">
            <div class="col-md-4">
                <label class="form-label">1. Pilih Kategori Pemasukan</label>
                <select name="kategori_id" class="form-select" onchange="document.getElementById('formFilter').submit()" required>
                    <option value="">-- Pilih Kategori --</option>
                    <?php foreach ($kategoriList as $k): ?>
                        <option value="<?= $k['id'] ?>" <?= $kategoriId==$k['id']?'selected':'' ?>>
                            <?= htmlspecialchars($k['nama']) ?> <?= $k['kelompok']==='spp' ? '(SPP)' : '' ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php if ($kategoriId): ?>
            <div class="col-md-3">
                <label class="form-label">2. Mode</label>
                <select name="mode" class="form-select" onchange="document.getElementById('formFilter').submit()">
                    <option value="kelas" <?= $mode==='kelas'?'selected':'' ?>>Per Kelas (Massal)</option>
                    <option value="individual" <?= $mode==='individual'?'selected':'' ?>>Cari Individual</option>
                </select>
            </div>
            <?php if ($mode === 'kelas'): ?>
            <div class="col-md-3">
                <label class="form-label">3. Pilih Kelas</label>
                <select name="kelas_id" class="form-select" onchange="document.getElementById('formFilter').submit()">
                    <option value="">-- Pilih Kelas --</option>
                    <?php foreach ($kelasList as $kl): ?>
                        <option value="<?= $kl['id'] ?>" <?= $kelasId==$kl['id']?'selected':'' ?>><?= htmlspecialchars(formatKelasLabel($kl['tingkat_nama'], $kl['nama'])) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php else: ?>
            <div class="col-md-3">
                <label class="form-label">3. Cari Nama/NIS</label>
                <input type="text" name="q" class="form-control" placeholder="Ketik nama atau NIS..." value="<?= htmlspecialchars($searchNama) ?>">
            </div>
            <div class="col-md-1"><button class="btn btn-primary w-100"><i class="bi bi-search"></i></button></div>
            <?php endif; ?>
            <?php endif; ?>
        </form>
    </div>
</div>

<?php if ($kategoriId && $mode === 'kelas' && $kelasId): ?>
    <?php if (empty($siswaKelas)): ?>
        <div class="card"><div class="card-body text-center text-muted py-4">Tidak ada siswa aktif di kelas ini.</div></div>
    <?php else: ?>
    <form method="POST">
        <input type="hidden" name="action" value="bayar_massal">
        <input type="hidden" name="kategori_id" value="<?= $kategoriId ?>">
        <input type="hidden" name="kelas_id" value="<?= $kelasId ?>">
        <div class="card">
            <div class="card-header">
                Catat Pembayaran "<?= htmlspecialchars($kategoriTerpilih['nama'] ?? '') ?>" untuk Kelas <?= htmlspecialchars($kelasTerpilihLabel) ?>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-3">
                        <label class="form-label">Tanggal</label>
                        <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="col-md-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 class="col-md-3">
                        <label class="form-label">Nominal Default (untuk semua)</label>
                        <input type="text" id="nominalDefault" class="form-control" placeholder="contoh: 100000" oninput="formatRupiahInput(this); terapkanNominalDefault();">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Keterangan</label>
                        <input type="text" name="keterangan" class="form-control" placeholder="contoh: Uang kegiatan study tour">
                    </div>
                </div>

                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th width="40"><input type="checkbox" id="chkAll" checked onclick="document.querySelectorAll('.chk-siswa').forEach(c=>c.checked=this.checked)"></th>
                            <th>NIS</th><th>Nama</th><th>Riwayat Kategori Ini</th><th width="180">Nominal</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($siswaKelas as $s): ?>
                        <tr>
                            <td><input type="checkbox" class="chk-siswa" name="siswa_ids[]" value="<?= $s['id'] ?>" checked></td>
                            <td><?= htmlspecialchars($s['nis']) ?></td>
                            <td><?= htmlspecialchars($s['nama']) ?></td>
                            <td>
                                <?php if ($s['jml_bayar'] > 0): ?>
                                    <span class="badge text-bg-success">Sudah <?= $s['jml_bayar'] ?>x</span>
                                    <small class="text-muted">Terakhir: <?= tanggalIndo($s['terakhir_bayar']) ?></small>
                                <?php else: ?>
                                    <span class="badge text-bg-secondary">Belum pernah</span>
                                <?php endif; ?>
                            </td>
                            <td><input type="text" class="form-control form-control-sm nominal-input" name="nominal[<?= $s['id'] ?>]" placeholder="0" oninput="formatRupiahInput(this)"></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <button class="btn btn-success"><i class="bi bi-cash-coin"></i> Simpan Pembayaran Massal</button>
                <p class="text-muted small mt-2 mb-0">Hanya siswa yang dicentang dan memiliki nominal lebih dari 0 yang akan dicatat.</p>
            </div>
        </div>
    </form>

    <script>
    function terapkanNominalDefault() {
        const val = document.getElementById('nominalDefault').value;
        document.querySelectorAll('.chk-siswa:checked').forEach(chk => {
            const row = chk.closest('tr');
            row.querySelector('.nominal-input').value = val;
        });
    }
    document.querySelectorAll('.chk-siswa').forEach(c => c.addEventListener('change', terapkanNominalDefault));
    </script>
    <?php endif; ?>
<?php endif; ?>

<?php if ($kategoriId && $mode === 'individual'): ?>
    <?php if ($daftarSiswa): ?>
        <div class="card mb-3">
            <div class="card-body p-0">
                <table class="table table-hover mb-0">
                    <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="pembayaran_kategori.php?kategori_id=<?= $kategoriId ?>&mode=individual&siswa_id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary">Pilih</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php elseif ($searchNama): ?>
        <p class="text-muted">Tidak ada siswa yang cocok.</p>
    <?php endif; ?>

    <?php if ($siswaTerpilih): ?>
    <div class="card">
        <div class="card-header">
            Catat Pembayaran "<?= htmlspecialchars($kategoriTerpilih['nama'] ?? '') ?>" &mdash;
            <?= htmlspecialchars($siswaTerpilih['nama']) ?> (<?= htmlspecialchars($siswaTerpilih['nis']) ?>)
        </div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="bayar_satuan">
                <input type="hidden" name="kategori_id" value="<?= $kategoriId ?>">
                <input type="hidden" name="siswa_id" value="<?= $siswaTerpilih['id'] ?>">
                <div class="row">
                    <div class="col-md-4 mb-3"><label class="form-label">Tanggal</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">Jumlah</label><input type="text" name="jumlah" class="form-control" oninput="formatRupiahInput(this)" 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>
                <div class="mb-3"><label class="form-label">Keterangan</label><input type="text" name="keterangan" class="form-control"></div>
                <div class="mb-3"><label class="form-label">Bukti (opsional)</label><input type="file" name="bukti" class="form-control"></div>
                <button class="btn btn-success"><i class="bi bi-cash-coin"></i> Simpan Pembayaran</button>
            </form>

            <?php if ($riwayatSiswa): ?>
                <hr class="my-4">
                <h6>Riwayat Pembayaran Kategori Ini</h6>
                <table class="table table-sm">
                    <thead><tr><th>Tanggal</th><th>No. Transaksi</th><th class="text-end">Jumlah</th><th>Akun</th><th>Keterangan</th><th></th></tr></thead>
                    <tbody>
                    <?php foreach ($riwayatSiswa as $r): ?>
                        <tr>
                            <td><?= tanggalIndo($r['tanggal']) ?></td>
                            <td><?= htmlspecialchars($r['no_transaksi']) ?></td>
                            <td class="text-end text-success fw-semibold"><?= rupiah($r['jumlah']) ?></td>
                            <td><?= htmlspecialchars($r['nama_akun']) ?></td>
                            <td><?= htmlspecialchars($r['keterangan']) ?></td>
                            <td><a href="cetak_kwitansi.php?id=<?= $r['id'] ?>" target="_blank" class="btn btn-sm btn-outline-secondary">Kwitansi</a></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
<?php endif; ?>

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