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

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

$expense_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$store_id = $_SESSION['store_id'] ?? null;
$module = "Expenses";

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

// Check if the expense exists, is deleted, and (if manager) belongs to their store
$sql = "SELECT * FROM expenses WHERE id = ? AND deleted_at IS NOT NULL";
$params = [$expense_id];
$types = 'i';

if ($role_id == 2 && $store_id) {
    $sql .= " AND store_id = ?";
    $params[] = $store_id;
    $types .= 'i';
}

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$expense = $stmt->get_result()->fetch_assoc();
$stmt->close();

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

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

if ($perm_stmt->execute()) {
    // Audit log
    $action = 'Permanent Delete Expense';
    $details = "Permanently deleted expense: " . json_encode($expense);
    $device = $_SERVER['HTTP_USER_AGENT'];

    $log_stmt = $conn->prepare("INSERT INTO audit_log 
        (user_id, action, details, created_at, module, role_id, device_info) 
        VALUES (?, ?, ?, NOW(), ?, ?, ?)");
    $log_stmt->bind_param("isssis", $user_id, $action, $details, $module, $role_id, $device);
    $log_stmt->execute();
    $log_stmt->close();

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