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

if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    echo json_encode([]);
    exit();
}

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

$term = isset($_GET['term']) ? trim($_GET['term']) : '';

if ($term === '') {
    echo json_encode([]);
    exit();
}

$stmt = $conn->prepare("
    SELECT id, payment_reference, amount 
    FROM payments 
    WHERE payment_reference LIKE CONCAT('%', ?, '%') OR id = ?
    ORDER BY created_at DESC
    LIMIT 10
");
$stmt->bind_param("si", $term, $term);
$stmt->execute();
$result = $stmt->get_result();

$suggestions = [];
while ($row = $result->fetch_assoc()) {
    $suggestions[] = [
        'id' => $row['id'],
        'label' => 'Payment #' . $row['id'] . ' - Ref: ' . $row['payment_reference'] . ' - MWK ' . number_format($row['amount'], 2),
        'value' => $row['id']
    ];
}

echo json_encode($suggestions);
$stmt->close();
?>
