<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

$expense_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($expense_id <= 0) {
    header("Location: expenses_trash.php?error=invalid_id");
    exit();
}

// Check if expense exists and is deleted
$stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ? AND deleted_at IS NOT NULL");
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$expense = $stmt->get_result()->fetch_assoc();

if (!$expense) {
    header("Location: expenses_trash.php?error=not_found");
    exit();
}

// Permanently delete
$perm_stmt = $conn->prepare("DELETE FROM expenses WHERE id = ?");
$perm_stmt->bind_param("i", $expense_id);

if ($perm_stmt->execute()) {
    // Audit log
    $log_stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id) VALUES (?, ?, ?, NOW(), 'expenses', ?)");
    $user_id = $_SESSION['user_id'];
    $action = 'Permanent Delete Expense';
    $details = "Expense ID $expense_id permanently deleted from trash.";
    $role_id = $_SESSION['role_id'];
    $log_stmt->bind_param("isss", $user_id, $action, $details, $role_id);
    $log_stmt->execute();
    $log_stmt->close();

    header("Location: expenses_trash.php?deleted=1");
    exit();
} else {
    header("Location: expenses_trash.php?error=delete_failed");
    exit();
}
?>
