<?php
// search_clients.php
// AJAX endpoint for the searchable Client Name dropdown. Returns JSON.
// GET search_clients.php?q=partial+name

require_once 'includes/auth.php';
require_role(['admin', 'inspector', 'coordinator'], true); // read-only client lookup, safe for all roles

require 'db.php';

header('Content-Type: application/json');

$q = trim($_GET['q'] ?? '');
$browse = isset($_GET['browse']) && $_GET['browse'] === '1';

if ($browse) {
    // "Browse all" mode — capped at 200 for performance, ordered alphabetically.
    $stmt = $pdo->prepare("SELECT ClientID, Client_Name, Address FROM tbl_clients WHERE Deleted_At IS NULL ORDER BY Client_Name ASC LIMIT 200");
    $stmt->execute();
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    exit;
}

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

$stmt = $pdo->prepare(
    "SELECT ClientID, Client_Name, Address
     FROM tbl_clients
     WHERE Client_Name LIKE ? AND Deleted_At IS NULL
     ORDER BY Client_Name ASC
     LIMIT 15"
);
$stmt->execute(['%' . $q . '%']);

echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
