<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

// Check Permission
if (!can('expenses', 'delete')) {
    die('Access Denied: You do not have permission to reverse transactions.');
}

$trans_id = $_GET['id'] ?? 0;

if ($trans_id) {
    try {
        $pdo->beginTransaction();

        // 1. Fetch the transaction details to get the amount and box_id
        // We use FOR UPDATE to lock the row during the transaction
        $stmt = $pdo->prepare("SELECT amount, box_id, status FROM expense_transactions WHERE trans_id = ? FOR UPDATE");
        $stmt->execute([$trans_id]);
        $transaction = $stmt->fetch();

        if (!$transaction) {
            throw new Exception("Transaction not found.");
        }

        // 2. Check if already canceled to avoid double refunding
        if ($transaction['status'] === 'canceled') {
            throw new Exception("This transaction is already canceled.");
        }

        $amount_to_return = $transaction['amount'];
        $cashbox_id       = $transaction['box_id'];

        // 3. Update the transaction status to 'canceled'
        $updateStatus = $pdo->prepare("UPDATE expense_transactions SET status = 'canceled' WHERE trans_id = ?");
        $updateStatus->execute([$trans_id]);

        // 4. Return the amount to the specific cash box (current_balance)
        $updateBox = $pdo->prepare("UPDATE cash_boxes SET current_balance = current_balance + ? WHERE cashbox_id = ?");
        $updateBox->execute([$amount_to_return, $cashbox_id]);

        $pdo->commit();
        
        // Redirect back with success message
        header("Location: expenses.php?msg=reversed");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        die("Error: " . $e->getMessage());
    }
} else {
    header("Location: expenses.php");
    exit;
}