<?php
session_start();
require_once __DIR__ . '/config/config.php';

/* =========================
   CEK LOGIN
========================= */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    die("Akses ditolak!");
}

$role = $_SESSION['role'] ?? '';

$conn->begin_transaction();

try {

    if ($role === 'admin') {

        // ======================
        // ADMIN → hapus SEMUA
        // ======================
        $conn->query("DELETE FROM kwitansi_detail");
        $conn->query("DELETE FROM kwitansi");

    } else {

        // ======================
        // SEKOLAH → hapus milik sendiri
        // ======================
        if (!isset($_SESSION['npsn'])) {
            throw new Exception("NPSN tidak ditemukan");
        }

        $npsn = mysqli_real_escape_string($conn, $_SESSION['npsn']);

        // hapus DETAIL berdasarkan kwitansi milik sekolah
        $sqlDetail = "
            DELETE FROM kwitansi_detail
            WHERE id_kwitansi IN (
                SELECT id_kwitansi FROM kwitansi WHERE npsn = '$npsn'
            )
        ";
        $conn->query($sqlDetail);

        // hapus INDUK
        $conn->query("DELETE FROM kwitansi WHERE npsn = '$npsn'");
    }

    $conn->commit();

    echo "
    <script>
        alert('Semua data kwitansi berhasil dihapus');
        window.location='list_kwitansi.php';
    </script>
    ";

} catch (Exception $e) {

    $conn->rollback();

    echo "
    <script>
        alert('Gagal menghapus data: {$e->getMessage()}');
        window.location='list_kwitansi.php';
    </script>
    ";
}

exit;
