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

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

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

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

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

// Prepare query to search deposits matching term in reference or description
$sql = "SELECT id, amount, reference FROM bank_transactions 
        WHERE type = 'deposit' 
          AND (reference LIKE ? OR description LIKE ?) 
        ORDER BY transaction_date DESC
        LIMIT 15";

$searchTerm = '%' . $term . '%';

if (!$stmt = $conn->prepare($sql)) {
    http_response_code(500);
    echo json_encode([]);
    exit();
}

$stmt->bind_param('ss', $searchTerm, $searchTerm);

if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode([]);
    $stmt->close();
    exit();
}

$result = $stmt->get_result();
$data = [];

while ($row = $result->fetch_assoc()) {
    $data[] = [
        'id' => (int)$row['id'],
        'amount' => (float)$row['amount'],
        'reference' => $row['reference']
    ];
}

$stmt->close();
$conn->close();

echo json_encode($data);
