<?php

use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Module\Helpdesk\Service\DebitorCacheControl;
use MintyPHP\Module\Helpdesk\Service\DebitorDetailService;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Support\Guard;

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

gridRequireGetRequest();

$filters = gridParseFilters(requestInput()->queryAll(), [
    'customerNo' => ['type' => 'string'],
    'customerName' => ['type' => 'string'],
]);

$customerNo = (string) ($filters['customerNo'] ?? '');
$customerName = (string) ($filters['customerName'] ?? '');
$refreshRequested = DebitorCacheControl::parseRefreshFlag(requestInput()->query('refresh', ''));

if ($customerNo === '' || $customerName === '') {
    Router::json([
        'ok' => false,
        'categories' => [],
        'meta' => [
            'cache_used' => false,
            'cache_bypassed' => $refreshRequested,
            'cache_refreshed' => false,
        ],
    ]);

    return;
}

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();
$tenantScope = DebitorCacheControl::resolveTenantScope($session);
if ($refreshRequested) {
    DebitorCacheControl::invalidateDebitorCaches($sessionStore, $tenantScope, $customerNo, true);
}

$cacheKey = DebitorCacheControl::ticketsKey($tenantScope, $customerNo);
$cacheTtl = DebitorCacheControl::TTL_STANDARD_SECONDS;
$cached = $sessionStore->get($cacheKey);
$allTickets = null;
$cacheUsed = false;

if (!$refreshRequested && is_array($cached) && isset($cached['fetched_at']) && (time() - (int) $cached['fetched_at']) < $cacheTtl) {
    $allTickets = $cached['tickets'] ?? [];
    $cacheUsed = true;
}

if ($allTickets === null) {
    $service = app(DebitorDetailService::class);
    $result = $service->loadTickets($customerNo, $customerName);

    if (!($result['ok'] ?? false)) {
        Router::json([
            'ok' => false,
            'categories' => [],
            'meta' => [
                'cache_used' => $cacheUsed,
                'cache_bypassed' => $refreshRequested,
                'cache_refreshed' => $refreshRequested,
            ],
        ]);

        return;
    }

    $allTickets = $result['tickets'] ?? [];

    $sessionStore->set($cacheKey, [
        'tickets' => $allTickets,
        'fetched_at' => time(),
    ]);
}

$categories = [];
$supportUsers = [];
$contacts = [];

foreach ((array) $allTickets as $ticket) {
    if (!is_array($ticket)) {
        continue;
    }

    $category = trim((string) ($ticket['Category_1_Description'] ?? ''));
    if ($category !== '') {
        $categories[$category] = true;
    }

    $supportUser = trim((string) ($ticket['Support_User_Name'] ?? ''));
    if ($supportUser !== '') {
        $supportUsers[$supportUser] = true;
    }

    $contact = trim((string) ($ticket['Current_Contact_Name'] ?? ''));
    if ($contact !== '') {
        $contacts[$contact] = true;
    }
}

$categoryValues = array_keys($categories);
usort($categoryValues, 'strnatcasecmp');

$supportUserValues = array_keys($supportUsers);
usort($supportUserValues, 'strnatcasecmp');

$contactValues = array_keys($contacts);
usort($contactValues, 'strnatcasecmp');

Router::json([
    'ok' => true,
    'categories' => $categoryValues,
    'support_users' => $supportUserValues,
    'contacts' => $contactValues,
    'meta' => [
        'cache_used' => $cacheUsed,
        'cache_bypassed' => $refreshRequested,
        'cache_refreshed' => $refreshRequested,
    ],
]);
