<?php
declare(strict_types=1);

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

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

if (!is_logged_in($conn)) {
    $_SESSION['intended_url'] = (string) ($_SERVER['HTTP_REFERER'] ?? ($_SERVER['REQUEST_URI'] ?? ''));
    http_response_code(401);
    echo json_encode(array(
        'success' => false,
        'message' => localized_text_value('เซสชันหมดอายุ กรุณาเข้าสู่ระบบอีกครั้ง', 'Your session expired. Please login again.'),
        'matches' => array(),
        'redirect_url' => auth_page_path('login.php'),
        'error_code' => 'auth_required',
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit();
}

if (!can_access_open_bill($conn)) {
    http_response_code(403);
    echo json_encode(array(
        'success' => false,
        'message' => localized_text_value('คุณไม่มีสิทธิ์ใช้งานฟังก์ชันนี้', 'Permission denied.'),
        'matches' => array(),
        'redirect_url' => auth_page_path(auth_preferred_landing_page($conn)),
        'error_code' => 'permission_denied',
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    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' => localized_text_value('กรุณากรอกเบอร์โทรหรือทะเบียนรถเพื่อค้นหา', 'Enter the exact customer phone number or plate number to search.'),
        'matches' => array(),
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    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['customerGroupLabel'] = customer_group_label((string) ($match['customerGroup'] ?? 'member'));
        $match['availablePackages'] = $packageRowsByLookup[$lookupKey] ?? array();
    }
    unset($match);

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

    echo json_encode(array(
        'success' => false,
        'message' => localized_text_value('ค้นหาลูกค้าไม่สำเร็จ', 'Customer lookup failed.'),
        'matches' => array(),
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
