<?php

use MintyPHP\Module\Security\SecurityAuthorizationPolicy;
use MintyPHP\Module\Security\Service\SecurityBcGateway;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(SecurityAuthorizationPolicy::ABILITY_CHECKS_CREATE);
gridRequireGetRequest();

$request = requestInput();
$query = trim((string) $request->query('q', ''));

if ($query === '' || mb_strlen($query) < 2) {
    Router::json([]);

    return;
}

try {
    $rows = app(SecurityBcGateway::class)->searchCustomers($query);
} catch (\Throwable) {
    http_response_code(502);
    Router::json(['error' => 'search_failed']);

    return;
}

$items = [];
foreach ($rows as $row) {
    if (!is_array($row)) {
        continue;
    }
    $no = trim((string) ($row['No'] ?? ''));
    $name = trim((string) ($row['Name'] ?? ''));
    if ($no === '') {
        continue;
    }
    $items[] = [
        'value' => $no,
        'label' => $no . ' — ' . $name,
        'name' => $name,
        'meta' => trim((string) ($row['City'] ?? '')),
    ];
}

Router::json($items);
