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

// Only accessible by admin or accountant
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 4])) {
    http_response_code(403);
    echo "Unauthorized access.";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die("Invalid request.");
}

$user_id = $_SESSION['user_id'];
$deposit_id = intval($_POST['deposit_id'] ?? 0);
$fts = $_POST['fts'] ?? [];

if ($deposit_id <= 0 || empty($fts)) {
    die("Invalid form data.");
}

// Fetch the deposit amount
$deposit_stmt = $conn->prepare("
    SELECT amount 
    FROM bank_transactions 
    WHERE id = ? AND type = 'deposit' AND status = 'approved' AND reconciliation_status = 'pending'
");
$deposit_stmt->bind_param("i", $deposit_id);
$deposit_stmt->execute();
$deposit_stmt->bind_result($deposit_amount);
if (!$deposit_stmt->fetch()) {
    $deposit_stmt->close();
    die("Deposit not found or already reconciled.");
}
$deposit_stmt->close();

$total_reconciled = 0.0;
$valid_fts = [];

// Validate FT selections & amounts
foreach ($fts as $ft_id => $data) {
    if (!isset($data['select'])) continue;
    $amount = floatval($data['amount'] ?? 0);
    if ($amount <= 0) continue;

    $ft_id = intval($ft_id);
    $valid_fts[$ft_id] = $amount;
    $total_reconciled += $amount;
}

if (count($valid_fts) === 0) {
    die("No valid financial transactions selected.");
}

// Validate total matched amount
if (abs($total_reconciled - $deposit_amount) > 0.01) {
    die("Total matched amount does not equal deposit amount.");
}

// Check if any selected FT already reconciled
$ft_ids = array_keys($valid_fts);
$placeholders = implode(',', array_fill(0, count($ft_ids), '?'));
$types = str_repeat('i', count($ft_ids));

$check_stmt = $conn->prepare("SELECT id FROM financial_transactions WHERE id IN ($placeholders) AND reconciliation_status = 'reconciled'");
$check_stmt->bind_param($types, ...$ft_ids);
$check_stmt->execute();
$result = $check_stmt->get_result();
if ($result->num_rows > 0) {
    die("One or more selected transactions have already been reconciled.");
}
$check_stmt->close();

// Start DB transaction
$conn->begin_transaction();
try {
    $now = date('Y-m-d H:i:s');

    foreach ($valid_fts as $ft_id => $amount) {
        // Fetch linked sale
        $ft_info = $conn->prepare("SELECT linked_sale_id FROM financial_transactions WHERE id = ?");
        $ft_info->bind_param("i", $ft_id);
        $ft_info->execute();
        $ft_info->bind_result($linked_sale_id);
        $ft_info->fetch();
        $ft_info->close();

        // Construct description
        $desc = "Reconciled deposit to sale #" . ($linked_sale_id ?? 'N/A');

        // Insert into reconciliation links
        $link_stmt = $conn->prepare("
            INSERT INTO deposit_reconciliation_links 
            (bank_transaction_id, financial_transaction_id, linked_sale_id, reconciled_amount, created_by, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        $link_stmt->bind_param("iiidiss", $deposit_id, $ft_id, $linked_sale_id, $amount, $user_id, $now, $now);
        $link_stmt->execute();
        $link_stmt->close();

        // Update financial transaction
        $update_ft = $conn->prepare("
            UPDATE financial_transactions 
            SET 
                reconciliation_status = 'reconciled',
                linked_bank_transaction_id = ?,
                credit = ?,
                description = ?,
                reference_id = ?,
                updated_at = ?
            WHERE id = ?
        ");
        $update_ft->bind_param("dssisi", $deposit_id, $amount, $desc, $linked_sale_id, $now, $ft_id);
        $update_ft->execute();
        $update_ft->close();

        // Insert into audit log
        $audit = $conn->prepare("
            INSERT INTO reconciliation_audit_logs
            (event_type, bank_transaction_id, financial_transaction_id, user_id, amount, description, created_at)
            VALUES ('reconciled', ?, ?, ?, ?, ?, ?)
        ");
        $audit->bind_param("iiidss", $deposit_id, $ft_id, $user_id, $amount, $desc, $now);
        $audit->execute();
        $audit->close();
    }

    // Update bank transaction
    $update_bt = $conn->prepare("
        UPDATE bank_transactions 
        SET reconciliation_status = 'reconciled', updated_at = ? 
        WHERE id = ?
    ");
    $update_bt->bind_param("si", $now, $deposit_id);
    $update_bt->execute();
    $update_bt->close();

    $conn->commit();
    header("Location: bank_reconciliation.php?success=1");
    exit;

} catch (Exception $e) {
    $conn->rollback();
    die("Error during reconciliation: " . $e->getMessage());
}
