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

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

if (!isset($_POST['id'])) {
    die("Data tidak valid!");
}

$id = (int) $_POST['id'];

/* AMBIL DATA FILE */
$stmt = $conn->prepare("SELECT upload_file FROM rekening_koran WHERE id_koran = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();

if (!$data) {
    die("Data tidak ditemukan!");
}

/* HAPUS FILE JIKA ADA */
if (!empty($data['upload_file'])) {
    $file = __DIR__ . "/upload/" . $data['upload_file'];
    if (file_exists($file)) {
        unlink($file);
    }
}

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

/* KEMBALI KE LIST */
header("Location: /ebos/list_rekening_koran.php?status=hapus");
exit;
