<?php
// Proper error handling
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't show errors to users but log them

include('../koneksi.php');

// Verify user is authenticated
if (!isset($_SESSION['username']) || !isset($_SESSION['kode'])) {
    echo "<script type='text/javascript'>
        alert('Anda harus login terlebih dahulu!');
        window.location = '../login.php';
    </script>";
    exit;
}

// Get the current session data
$username = $_SESSION['username'];
$kode = $_SESSION['kode'];

// Validate required POST parameters
$required_fields = ['no_bukti', 'dataTable', 'register'];
foreach ($required_fields as $field) {
    if (!isset($_POST[$field]) || empty($_POST[$field])) {
        echo "<script type='text/javascript'>
            alert('Data " . ucfirst($field) . " harus diisi!');
            window.location = '../home.php?home=" . md5("delete_tagihansyahriah") . "';
        </script>";
        exit;
    }
}

// Get and sanitize form data
$no_bukti = mysqli_real_escape_string($koneksi, $_POST['no_bukti']);
$dataTable = mysqli_real_escape_string($koneksi, $_POST['dataTable']);
$register = mysqli_real_escape_string($koneksi, $_POST['register']);

// Validate dataTable for security - whitelist approach
$validTables = ['bulanan', 'seragam', 'kitab', 'imda1', 'imda2', 'imda3', 'iuran', 'imni', 'ikhtibar'];
if (!in_array($dataTable, $validTables)) {
    echo "<script type='text/javascript'>
        alert('Tabel tidak valid!');
        window.location = '../home.php?home=" . md5("delete_tagihansyahriah") . "';
    </script>";
    exit;
}

// Prepare and execute query to get original record before deletion
$stmt = mysqli_prepare($koneksi, "SELECT * FROM $dataTable WHERE no_bukti=?");
mysqli_stmt_bind_param($stmt, "s", $no_bukti);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$original = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);

// Check if record exists
if (!$original) {
    echo "<script type='text/javascript'>
        alert('Data tidak ditemukan!');
        window.location = '../home.php?home=" . md5("delete_tagihansyahriah") . "';
    </script>";
    exit;
}

// Begin transaction for data consistency
mysqli_begin_transaction($koneksi);
try {
    // First, delete entries from bukubesar related to this transaction
    $stmt = mysqli_prepare($koneksi, "DELETE FROM bukubesar WHERE no_bukti = ?");
    mysqli_stmt_bind_param($stmt, "s", $no_bukti);
    $delete_bukubesar_result = mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    
    if (!$delete_bukubesar_result) {
        throw new Exception("Error deleting bukubesar entries: " . mysqli_error($koneksi));
    }
    
    // Now, delete the transaction from the original table
    $stmt = mysqli_prepare($koneksi, "DELETE FROM $dataTable WHERE no_bukti = ?");
    mysqli_stmt_bind_param($stmt, "s", $no_bukti);
    $delete_transaction_result = mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    
    if (!$delete_transaction_result) {
        throw new Exception("Error deleting transaction: " . mysqli_error($koneksi));
    }
    
    // Log the deletion to a history/audit table if needed
    // This can be implemented according to system requirements
    
    // Commit transaction if everything is successful
    mysqli_commit($koneksi);
    
    // Redirect back to the page with parameters for showing transactions
    echo "<script type='text/javascript'>
        alert('Data berhasil dihapus!');
        window.location = '../home.php?home=" . md5("delete_tagihansyahriah") . "&show_transactions=1&register=" . urlencode($register) . "&dataTable=" . urlencode($dataTable) . "';
    </script>";
    exit;
    
} catch (Exception $e) {
    // Rollback if there's an error
    mysqli_rollback($koneksi);
    
    // Log the error to a file for administrators
    error_log("Database error in transaction deletion: " . $e->getMessage(), 0);
    
    echo "<script type='text/javascript'>
        alert('Error: " . htmlspecialchars($e->getMessage()) . "');
        window.location = '../home.php?home=" . md5("delete_tagihansyahriah") . "';
    </script>";
}

// Close connection
mysqli_close($koneksi);
?>