<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "No expense ID provided",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

$expense_id = intval($_GET['id']);

// First get the expense details for the notification
$stmt = $conn->prepare("SELECT exp_no FROM expenses WHERE id = ?");
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$result = $stmt->get_result();
$expense = $result->fetch_assoc();
$exp_no = $expense ? $expense['exp_no'] : 'Unknown';
$stmt->close();

try {
    // Prepare the DELETE statement
    $stmt = $conn->prepare("DELETE FROM expenses WHERE id = ?");
    $stmt->bind_param("i", $expense_id);
    
    // Execute the statement
    if ($stmt->execute()) {
        $_SESSION['sweet_alert'] = [
            'title' => 'Success!',
            'text' => "Expense $exp_no has been deleted successfully.",
            'icon' => 'success'
        ];
    } else {
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "Error deleting expense: " . $conn->error,
            'icon' => 'error'
        ];
    }
    
    $stmt->close();
} catch (Exception $e) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "Error: " . $e->getMessage(),
        'icon' => 'error'
    ];
}

// Redirect back to the expense list
header('Location: all_expenses.php');
exit();
?>