<?php

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

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

$query = requestInput()->queryAll();
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php', $query);
$result = app(DebitorSearchService::class)->listForGrid($filters);

if (($result['status'] ?? '') !== 'success') {
    gridJsonDataResult([], 0);

    return;
}

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    if (!is_array($row)) {
        continue;
    }

    $debtorNo = trim((string) ($row['No'] ?? ''));
    if ($debtorNo === '') {
        continue;
    }

    $rows[] = [
        'No' => $debtorNo,
        'Name' => (string) ($row['Name'] ?? ''),
        'City' => (string) ($row['City'] ?? ''),
        'Phone_No' => (string) ($row['Phone_No'] ?? ''),
        'E_Mail' => (string) ($row['E_Mail'] ?? ''),
        'detail_url' => lurl('helpdesk/debitor/' . rawurlencode($debtorNo)),
    ];
}

gridJsonDataResult($rows, (int) ($result['total'] ?? 0));
