<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\AddressBook\AddressBookAuthorizationPolicy;
use MintyPHP\Module\AddressBook\Service\AddressBookService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbilityOrForbidden(AddressBookAuthorizationPolicy::ABILITY_VIEW);
gridRequireGetRequest();

$query = requestInput()->queryAll();
$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php', $query);

foreach ($query as $rawKey => $rawValue) {
    $key = strtolower(trim((string) $rawKey));
    if (preg_match('/^(cf_|cfm_|cfd_)/', $key) !== 1) {
        continue;
    }
    $filters[$key] = $rawValue;
}

$currentUserId = (int) ($session['user']['id'] ?? 0);
$addressBookService = app(AddressBookService::class);
$result = $addressBookService->buildGridResult($currentUserId, $filters);
gridJsonDataResult(
    (array) ($result['data'] ?? []),
    (int) ($result['total'] ?? 0)
);
