<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Helpdesk\HelpdeskAuthorizationPolicy;
use MintyPHP\Service\Access\AuthorizationService;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

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

$request = requestInput();
$query = $request->queryAll();

$filterSchema = require __DIR__ . '/filter-schema.php';
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'query' => $query,
    'search_keys' => ['search'],
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
$schemaByKey = $listFilterContext['schemaByKey'];
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'status' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) ($schemaByKey['status']['default'] ?? 'all'),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
    ],
    'category' => [
        'label' => t('Type'),
        'type' => 'select',
        'default' => (string) ($schemaByKey['category']['default'] ?? 'all'),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['category'] ?? [])),
    ],
    'ticket_state' => [
        'label' => t('Ticket status'),
        'type' => 'select',
        'default' => (string) ($schemaByKey['ticket_state']['default'] ?? 'all'),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['ticket_state'] ?? [])),
    ],
];

$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$authService = app(AuthorizationService::class);
$actorContext = ['actor_user_id' => $userId];
$canManage = $authService->authorize(HelpdeskAuthorizationPolicy::ABILITY_UPDATES_MANAGE, $actorContext)->isAllowed();

$csrfKey = '';
$csrfToken = '';
if ($canManage) {
    $csrfKey = Session::$csrfSessionKey;
    $csrfToken = (string) ($session[$csrfKey] ?? '');
}

Buffer::set('title', t('Updates'));
Buffer::set('style_groups', json_encode(['helpdesk']));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Helpdesk'), 'path' => 'helpdesk'],
    ['label' => t('Updates')],
];
