<?php

use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DebitorSearchService;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(HelpdeskAuthorizationPolicy::ABILITY_HANDOVERS_CREATE);
gridRequireGetRequest();

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

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

    return;
}

$result = app(DebitorSearchService::class)->search($query);
$items = [];

if (($result['status'] ?? '') === 'success') {
    foreach ((array) ($result['results'] ?? []) 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);
