<?php
require_once __DIR__ . "/../../../app/config/auth.php";
require_login();
require_once __DIR__ . "/../../../app/config/app.php";
require_once __DIR__ . "/../../../app/config/session.php";
require_once __DIR__ . "/../../../app/config/koneksi.php";

// Pastikan ID ada
if (!isset($_GET['id']) || intval($_GET['id']) < 1) {
    header("Location: ../index.php");
    exit;
}

$id = intval($_GET['id']);
$user = getSession('pengurus_nama') ?? 'Unknown';
$now  = date("Y-m-d H:i:s");

// Ambil data lama (untuk log)
$q = mysqli_query($koneksi, "SELECT * FROM keuangan WHERE id=$id");
$data = mysqli_fetch_assoc($q);

if (!$data) {
    header("Location: ../index.php?notfound=1");
    exit;
}

// Simpan untuk LOG sebelum DELETE
$tanggal    = $data['tanggal'];
$keterangan = mysqli_real_escape_string($koneksi, $data['keterangan']);
$nilai      = $data['pengeluaran'];

// Hapus data
$delete = mysqli_query($koneksi, "DELETE FROM keuangan WHERE id=$id");

if ($delete) {

    // Insert log
    $log = "INSERT INTO log_keuangan 
            (alasan, id_keuangan, tanggal, keterangan, jenis, nilai, data_update, user_update)
            VALUES (
                'data dihapus',
                $id,
                '$tanggal',
                '$keterangan',
                'pengeluaran',
                $nilai,
                '$now',
                '$user'
            )";
    
    mysqli_query($koneksi, $log);
    header("Location: ../index.php?deleted=1");
    exit;
}

// Jika gagal
header("Location: ../index.php?error=1");
exit;
?>
