<?php
include '../includes/config.php';

if (isset($_GET['id']) && !empty($_GET['id'])) {
    $expense_id = $_GET['id'];

    try {
        $conn->beginTransaction();

        $sql_check = "SELECT expense_id FROM bank_debit_amount WHERE expense_id = :expense_id";
        $stmt_check = $conn->prepare($sql_check);
        $stmt_check->bindParam(':expense_id', $expense_id, PDO::PARAM_INT);
        $stmt_check->execute();

        if ($stmt_check->rowCount() > 0) {
            $sql_debit = "DELETE FROM bank_debit_amount WHERE expense_id = :expense_id";
            $stmt_debit = $conn->prepare($sql_debit);
            $stmt_debit->bindParam(':expense_id', $expense_id, PDO::PARAM_INT);
            $stmt_debit->execute();
        }

        $sql_expense = "DELETE FROM expense WHERE id = :expense_id";
        $stmt_expense = $conn->prepare($sql_expense);
        $stmt_expense->bindParam(':expense_id', $expense_id, PDO::PARAM_INT);
        $stmt_expense->execute();

        $conn->commit();

        header("Location: ../list_expense.php");
        exit; 

    } catch (Exception $e) {
        $conn->rollBack();
        
        echo "<script>alert('Error deleting record: " . $e->getMessage() . "');</script>";
    }
} else {
    header("Location: ../list_expense.php");
    exit;
}
?>
