<?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;
$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$module = "Expenses";

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

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

if ($result->num_rows === 0) {
    header("Location: expenses.php?trash=1&error=not_found");
    exit();
}

$expense = $result->fetch_assoc();

// Restore expense
$restore_stmt = $conn->prepare("UPDATE expenses SET deleted_at = NULL WHERE id = ?");
$restore_stmt->bind_param("i", $expense_id);

if ($restore_stmt->execute()) {
    // Audit log
    $details = "Restored expense: " . json_encode($expense);
    $device = $_SERVER['HTTP_USER_AGENT'];
    $audit = $conn->prepare("INSERT INTO audit_log (user_id, action, details, module, role_id, device_info) VALUES (?, 'RESTORE', ?, ?, ?, ?)");
    $audit->bind_param("issis", $user_id, $details, $module, $role_id, $device);
    $audit->execute();

    header("Location: expenses.php?restored=1");
    exit();
} else {
    header("Location: expenses.php?trash=1&error=restore_failed");
    exit();
}
