<?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 (!$amount || !$account_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

// Map financial_transactions.type to simplified categories
$type_map = [
    'sale_income' => 'sale',
    'expense_payment' => 'expense',
    'supplier_payment' => 'payment'
];

$valid_types = array_keys($type_map);
$placeholders = implode(',', array_fill(0, count($valid_types), '?'));
$types_str = str_repeat('s', count($valid_types)); // 'sss'

$sql = "
    SELECT id, amount, reference_id, type, transaction_date, account_id
    FROM financial_transactions
    WHERE amount BETWEEN ? AND ?
      AND reconciliation_status = 'pending'
      AND type IN ($placeholders)
    ORDER BY transaction_date DESC
    LIMIT 100
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Prepare failed: ' . $conn->error]);
    exit;
}

// Bind: min_amount, max_amount, types...
$min_amount = $amount - 1.00;  // ±1 tolerance
$max_amount = $amount + 1.00;
$bind_types = 'dd' . $types_str;
$bind_values = array_merge([$min_amount, $max_amount], $valid_types);

// References needed for bind_param
$refs = [];
foreach ($bind_values as $k => $v) {
    $refs[$k] = &$bind_values[$k];
}
call_user_func_array([$stmt, 'bind_param'], array_merge([$bind_types], $refs));

$stmt->execute();
$result = $stmt->get_result();

$matches = [];
while ($row = $result->fetch_assoc()) {
    $simple_type = $type_map[$row['type']] ?? 'unknown';
    $reason = [];

    // Check if amount is within tolerance but not exact
    if (abs($row['amount'] - $amount) > 0.01) {
        $reason[] = 'Amount slightly differs';
    }
    // Check if accounts differ
    if ((int)$row['account_id'] !== $account_id) {
        $reason[] = 'Different account';
    }

    $matches[] = [
        'id' => (int)$row['id'],
        'amount' => (float)$row['amount'],
        'reference_id' => $row['reference_id'],
        'type' => $simple_type,
        'transaction_date' => $row['transaction_date'],
        'reason' => count($reason) ? implode(', ', $reason) : 'Exact match'
    ];
}

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