<?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.php?trash=1&error=invalid_id");
    exit();
}

// Check if expense exists, is deleted, and belongs to current manager (if role_id == 2)
$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();
$result = $stmt->get_result();

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

$expense = $result->fetch_assoc();

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

if ($restore_stmt->execute()) {
    // Log audit
    $details = "Restored expense: " . json_encode($expense);
    $device = $_SERVER['HTTP_USER_AGENT'];
    $action = "Restore Expense";

    $audit = $conn->prepare("INSERT INTO audit_log (user_id, action, details, module, role_id, device_info, created_at)
                             VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $audit->bind_param("isssis", $user_id, $action, $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();
}
