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

/* ======================
   CEK LOGIN
====================== */
if (!isset($_SESSION['login']) || !isset($_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

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

/* ======================
   VALIDASI ID
====================== */
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    die("ID tidak valid!");
}

/* ======================
   AMBIL DATA LAPORAN
====================== */
if ($role === 'admin') {
    $stmt = $conn->prepare("
        SELECT upload_laporan, upload_rekening_koran
        FROM upload_laporan
        WHERE id_laporan = ?
    ");
    $stmt->bind_param("i", $id);
} else {
    $stmt = $conn->prepare("
        SELECT upload_laporan, upload_rekening_koran
        FROM upload_laporan
        WHERE id_laporan = ? AND npsn = ?
    ");
    $stmt->bind_param("is", $id, $npsn_login);
}

$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    die("⛔ Akses ditolak atau data tidak ditemukan!");
}

$data = $res->fetch_assoc();

/* ======================
   HAPUS FILE FISIK
====================== */
$folder = __DIR__ . "/upload/";

if (!empty($data['upload_laporan']) && file_exists($folder . $data['upload_laporan'])) {
    unlink($folder . $data['upload_laporan']);
}

if (!empty($data['upload_rekening_koran']) && file_exists($folder . $data['upload_rekening_koran'])) {
    unlink($folder . $data['upload_rekening_koran']);
}

/* ======================
   HAPUS DATA DATABASE
====================== */
$stmt = $conn->prepare("DELETE FROM upload_laporan WHERE id_laporan = ?");
$stmt->bind_param("i", $id);
$stmt->execute();

/* ======================
   REDIRECT
====================== */
header("Location: list_laporan.php?hapus=ok");
exit;
