<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

if (!is_logged_in($conn) || (!can_access($conn, 'booking') && !can_access($conn, 'quick_service'))) {
    http_response_code(403);
    echo json_encode(array(
        'success' => false,
        'message' => translate_text('Permission denied.'),
        'matches' => array(),
    ));
    exit();
}

$lookupQuery = trim((string) ($_GET['q'] ?? ($_GET['phone'] ?? ($_GET['plate_number'] ?? ''))));
$phoneDigits = normalize_phone($lookupQuery);
$plateNumber = normalize_plate($lookupQuery);

if ($phoneDigits === '' && $plateNumber === '') {
    echo json_encode(array(
        'success' => false,
        'message' => translate_text('Enter the exact customer phone number or plate number to search.'),
        'matches' => array(),
    ));
    exit();
}

try {
    $matches = find_customer_matches($conn, $lookupQuery, $lookupQuery);
    $packageRequests = array();

    foreach ($matches as $match) {
        $packageRequests[] = array(
            'customer_id' => (int) ($match['customerId'] ?? 0),
            'car_id' => (int) ($match['carId'] ?? 0),
        );
    }

    $packageRowsByLookup = service_customer_package_balance_rows_for_customer_cars($conn, $packageRequests);

    foreach ($matches as &$match) {
        $customerId = (int) ($match['customerId'] ?? 0);
        $carId = (int) ($match['carId'] ?? 0);
        $lookupKey = $customerId . ':' . $carId;
        $match['availablePackages'] = $packageRowsByLookup[$lookupKey] ?? array();
    }
    unset($match);

    echo json_encode(array(
        'success' => true,
        'matches' => $matches,
    ));
} catch (Throwable $exception) {
    http_response_code(500);

    echo json_encode(array(
        'success' => false,
        'message' => translate_text('Customer lookup failed.'),
        'matches' => array(),
    ));
}
