<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

// Get search term
$term = isset($_GET['term']) ? $_GET['term'] : '';

if (empty($term) || strlen($term) < 2) {
    header('Content-Type: application/json');
    echo json_encode([]);
    exit();
}

// Search for matching file numbers
$query = "SELECT file_number, consignee_name, destination 
          FROM files 
          WHERE file_number LIKE ? OR consignee_name LIKE ? 
          ORDER BY created_date DESC 
          LIMIT 10";

$stmt = $conn->prepare($query);
$searchParam = "%$term%";
$stmt->bind_param("ss", $searchParam, $searchParam);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        'id' => $row['file_number'],
        'text' => $row['file_number'] . ' - ' . $row['consignee_name'] . ' (' . $row['destination'] . ')'
    ];
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode($data);
?>