<?php
session_start();
include('../../includes/config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reconcile'])) {
    foreach ($_POST['reconcile'] as $expense_id => $triggered) {
        $expense_id = intval($expense_id);
        $bank_txn_id = intval($_POST['bank_txn_id'][$expense_id] ?? 0);

        if ($bank_txn_id === 0) {
            die("Error: No bank transaction selected for expense $expense_id");
        }

        $conn->begin_transaction();
        try {
            // Validate amounts match
            $expense = $conn->query("SELECT amount FROM expenses WHERE id = $expense_id")->fetch_assoc();
            $bank_txn = $conn->query("SELECT amount FROM bank_transactions WHERE id = $bank_txn_id")->fetch_assoc();

            if (!$expense || !$bank_txn) throw new Exception("Data not found.");
            if (abs($expense['amount'] - $bank_txn['amount']) > 0.01) throw new Exception("Amount mismatch!");

            // Reconcile
            $conn->query("UPDATE bank_transactions SET reconciled = 1 WHERE id = $bank_txn_id");
            $conn->query("UPDATE expenses SET reconciliation_status = 'reconciled' WHERE id = $expense_id");
            $conn->query("UPDATE financial_transactions SET reconciliation_status = 'reconciled' WHERE reference_id = $expense_id AND type = 'expense'");

            $conn->commit();
        } catch (Exception $e) {
            $conn->rollback();
            die("Reconciliation failed: " . $e->getMessage());
        }
    }

    header("Location:reconcile_expenses.php?success=1");
    exit();
}
?>
