<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_VIEW);

$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
    (int) ($session['user']['id'] ?? 0),
    UiCapabilityMap::PAGE_SYSTEM_AUDIT
);

Buffer::set('title', t('System audit logs'));
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
    ...gridSchemaQuery($filterSchema),
    'event_types' => [
        'type' => 'csv_strings',
        'max' => 200,
        'return' => 'array',
        'sanitizer' => static function (string $value): string {
            $value = strtolower(trim($value));
            if ($value === '' || strlen($value) > 64) {
                return '';
            }
            return preg_match('/^[a-z0-9._-]+$/', $value) === 1 ? $value : '';
        },
    ],
    'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(SystemAuditService::class)->filterOptions(200);

$activeEventTypes = is_array($filterState['event_types'] ?? null) ? $filterState['event_types'] : [];
$activeActorUserIds = array_map('strval', is_array($filterState['actor_user_ids'] ?? null) ? $filterState['actor_user_ids'] : []);

$eventTypeItems = [];
foreach ((array) ($filterOptions['event_types'] ?? []) as $eventType) {
    $eventType = strtolower(trim((string) $eventType));
    if ($eventType === '') {
        continue;
    }
    $eventTypeItems[$eventType] = [
        'id' => $eventType,
        'description' => $eventType,
    ];
}

foreach ($activeEventTypes as $eventType) {
    if (!isset($eventTypeItems[$eventType])) {
        $eventTypeItems[$eventType] = [
            'id' => $eventType,
            'description' => $eventType,
        ];
    }
}
$eventTypeItems = array_values($eventTypeItems);

$actorUserItems = [];
foreach ((array) ($filterOptions['actors'] ?? []) as $actorOption) {
    if (!is_array($actorOption)) {
        continue;
    }
    $actorId = (int) ($actorOption['id'] ?? 0);
    if ($actorId <= 0) {
        continue;
    }

    $actorDisplayName = trim((string) ($actorOption['display_name'] ?? ''));
    $actorEmail = trim((string) ($actorOption['email'] ?? ''));
    $actorExists = (bool) ($actorOption['exists'] ?? false);

    $label = $actorDisplayName !== '' ? $actorDisplayName : $actorEmail;
    if ($label === '') {
        $label = $actorExists
            ? sprintf(t('User #%d'), $actorId)
            : sprintf(t('User #%d (deleted)'), $actorId);
    }

    $id = (string) $actorId;
    $actorUserItems[$id] = [
        'id' => $id,
        'description' => $label,
    ];
}

foreach ($activeActorUserIds as $actorId) {
    if (!isset($actorUserItems[$actorId])) {
        $actorUserItems[$actorId] = [
            'id' => $actorId,
            'description' => sprintf(t('User #%d (deleted)'), (int) $actorId),
        ];
    }
}
$actorUserItems = array_values($actorUserItems);

$toolbarFilterState = [
    'search' => (string) ($filterState['search'] ?? ''),
    'event_types' => $activeEventTypes,
    'outcome' => (string) ($filterState['outcome'] ?? ''),
    'channel' => (string) ($filterState['channel'] ?? ''),
    'created_from' => (string) ($filterState['created_from'] ?? ''),
    'created_to' => (string) ($filterState['created_to'] ?? ''),
    'actor_user_ids' => $activeActorUserIds,
    'request_id' => (string) ($filterState['request_id'] ?? ''),
];
$toolbarOptionSets = [
    'event_type_items' => $eventTypeItems,
    'actor_user_items' => $actorUserItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'filter_state' => $filterState,
    'search_keys' => ['search'],
    'toolbar_state_overrides' => $toolbarFilterState,
    'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'outcome' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['outcome']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['outcome'] ?? [])),
    ],
    'channel' => [
        'label' => t('Channel'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['channel']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['channel'] ?? [])),
    ],
    'event_types' => [
        'label' => t('Event type'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($eventTypeItems),
    ],
    'actor_user_ids' => [
        'label' => t('Actor'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($actorUserItems),
    ],
    'request_id' => [
        'label' => t('Request ID'),
        'type' => 'text',
    ],
    'created_range' => [
        'label' => t('Created'),
        'type' => 'date_range',
        'from_param' => 'created_from',
        'to_param' => 'created_to',
    ],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
