<?php
session_start();
header('Content-Type: application/json');
require_once '../../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 4) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$bank_transaction_id = intval($_POST['bank_transaction_id'] ?? 0);
$financial_ids = $_POST['financial_transaction_ids'] ?? [];
$amounts = $_POST['amounts'] ?? [];

$errors = [];

// Validation: Deposit must exist
$bt_stmt = $conn->prepare("SELECT id, amount, type, reconciled FROM bank_transactions WHERE id = ?");
$bt_stmt->bind_param("i", $bank_transaction_id);
$bt_stmt->execute();
$bt_result = $bt_stmt->get_result();
$bt_stmt->close();

if ($bt_result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Bank transaction not found']);
    exit;
}

$deposit = $bt_result->fetch_assoc();
if ($deposit['type'] !== 'deposit') {
    echo json_encode(['success' => false, 'message' => 'Only deposits can be reconciled']);
    exit;
}

// Total amount validation
$total_recon = 0;
foreach ($amounts as $a) {
    if (!is_numeric($a) || $a <= 0) {
        $errors[] = 'Invalid amount in reconciliation list.';
        break;
    }
    $total_recon += floatval($a);
}

if ($total_recon > floatval($deposit['amount'])) {
    $errors[] = "Total reconciled amount exceeds deposit.";
}

if (count($financial_ids) != count($amounts)) {
    $errors[] = "Mismatch in transactions and amounts.";
}

if (!empty($errors)) {
    echo json_encode(['success' => false, 'message' => implode(" ", $errors)]);
    exit;
}

// Begin transaction
$conn->begin_transaction();
try {
    for ($i = 0; $i < count($financial_ids); $i++) {
        $ft_id = intval($financial_ids[$i]);
        $amt = floatval($amounts[$i]);

        // Validate FT
        $ft_stmt = $conn->prepare("SELECT id, linked_bank_transaction_id FROM financial_transactions WHERE id = ?");
        $ft_stmt->bind_param("i", $ft_id);
        $ft_stmt->execute();
        $ft_result = $ft_stmt->get_result();
        $ft_stmt->close();

        if ($ft_result->num_rows === 0) {
            throw new Exception("Invalid financial transaction ID: $ft_id");
        }

        $ft = $ft_result->fetch_assoc();

        // Optional: you could check for linked_bank_transaction_id already set, etc.

        // Insert into reconciliation table
        $ins_stmt = $conn->prepare("
            INSERT INTO deposit_reconciliation_links 
            (bank_transaction_id, financial_transaction_id, linked_sale_id, amount, created_by)
            VALUES (?, ?, (SELECT linked_sale_id FROM financial_transactions WHERE id = ? LIMIT 1), ?, ?)
        ");
        $ins_stmt->bind_param("iiidi", $bank_transaction_id, $ft_id, $ft_id, $amt, $user_id);
        $ins_stmt->execute();
        $ins_stmt->close();

        // Update FT with linked bank transaction
        $update_ft = $conn->prepare("UPDATE financial_transactions SET linked_bank_transaction_id = ?, reconciliation_status = 'reconciled' WHERE id = ?");
        $update_ft->bind_param("ii", $bank_transaction_id, $ft_id);
        $update_ft->execute();
        $update_ft->close();
    }

    // Mark BT as reconciled if fully matched
    if (abs($total_recon - floatval($deposit['amount'])) < 0.01) {
        $bt_update = $conn->prepare("UPDATE bank_transactions SET reconciled = 1, reconciliation_status = 'reconciled' WHERE id = ?");
        $bt_update->bind_param("i", $bank_transaction_id);
        $bt_update->execute();
        $bt_update->close();
    }

    $conn->commit();
    echo json_encode(['success' => true, 'message' => 'Reconciliation successful.']);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Reconciliation failed: ' . $e->getMessage()]);
}
