<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([]);
    exit();
}

$term = $_GET['term'] ?? '';
$searchTermWildcard = "%" . $term . "%";

$sql = "SELECT `ID` as `id`, CONCAT(`customer_name`, ' - ', `customer_phone`) as `label` 
        FROM `cms_customers` 
        WHERE `customer_name` LIKE ? OR `customer_phone` LIKE ?
        ORDER BY `customer_name` ASC
        LIMIT 20";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $searchTermWildcard, $searchTermWildcard);
$stmt->execute();
$result = $stmt->get_result();
$customers = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

echo json_encode($customers);
?>