<?php
session_start();
header('Content-Type: application/json');
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

include('../../includes/config.php');

$txn_id = intval($_GET['txn_id'] ?? 0);
$amount = floatval($_GET['amount'] ?? 0);
$account_id = intval($_GET['account_id'] ?? 0);

if (!$txn_id || !$amount || !$account_id) {
    echo json_encode(['success' => false, 'message' => 'Missing parameters']);
    exit;
}

$matches = [];
$stmt = $conn->prepare("
    SELECT id, amount, reference_id, 'sale' AS type 
    FROM financial_transactions 
    WHERE amount = ? AND account_id = ? AND reconciliation_status = 'pending' AND linked_bank_transaction_id IS NULL
    UNION ALL
    SELECT id, amount, reference_id, 'expense' 
    FROM financial_transactions 
    WHERE amount = ? AND account_id = ? AND reconciliation_status = 'pending' AND linked_bank_transaction_id IS NULL
    UNION ALL
    SELECT id, amount, reference_id, 'payment' 
    FROM financial_transactions 
    WHERE amount = ? AND account_id = ? AND reconciliation_status = 'pending' AND linked_bank_transaction_id IS NULL
");
$stmt->bind_param("didiid", $amount, $account_id, $amount, $account_id, $amount, $account_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $matches[] = $row;
}
$stmt->close();

echo json_encode(['success' => true, 'matches' => $matches]);
?>
