<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Audit\AuditAuthorizationPolicy;
use MintyPHP\Module\Audit\Service\ImportAuditService;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(AuditAuthorizationPolicy::ABILITY_IMPORTS_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
    (int) ($session['user']['id'] ?? 0),
    ['can_purge' => SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE]
);

Buffer::set('title', t('Import audit logs'));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Import 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),
    'user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(ImportAuditService::class)->filterOptions(200);

$activeUserIds = array_map('strval', is_array($filterState['user_ids'] ?? null) ? $filterState['user_ids'] : []);

$importAuditUserItems = [];
foreach ((array) ($filterOptions['users'] ?? []) as $userOption) {
    if (!is_array($userOption)) {
        continue;
    }
    $userId = (int) ($userOption['id'] ?? 0);
    if ($userId <= 0) {
        continue;
    }
    $displayName = trim((string) ($userOption['display_name'] ?? ''));
    $email = trim((string) ($userOption['email'] ?? ''));
    $exists = (bool) ($userOption['exists'] ?? false);
    $label = $displayName !== '' ? $displayName : $email;
    if ($label === '') {
        $label = $exists
            ? sprintf(t('User #%d'), $userId)
            : sprintf(t('User #%d (deleted)'), $userId);
    }

    $id = (string) $userId;
    $importAuditUserItems[$id] = [
        'id' => $id,
        'description' => $label,
    ];
}
foreach ($activeUserIds as $userId) {
    if (!isset($importAuditUserItems[$userId])) {
        $importAuditUserItems[$userId] = [
            'id' => $userId,
            'description' => sprintf(t('User #%d (deleted)'), (int) $userId),
        ];
    }
}
$importAuditUserItems = array_values($importAuditUserItems);

$toolbarFilterState = [
    'search' => (string) ($filterState['search'] ?? ''),
    'profile_key' => (string) ($filterState['profile_key'] ?? ''),
    'status' => (string) ($filterState['status'] ?? ''),
    'created_from' => (string) ($filterState['created_from'] ?? ''),
    'created_to' => (string) ($filterState['created_to'] ?? ''),
    'user_ids' => $activeUserIds,
];
$toolbarOptionSets = [
    'user_items' => $importAuditUserItems,
];
$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',
    ],
    'profile_key' => [
        'label' => t('Profile'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['profile_key']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['profile_key'] ?? [])),
    ],
    'status' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['status']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
    ],
    'user_ids' => [
        'label' => t('Users'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($importAuditUserItems),
    ],
    'created_range' => [
        'label' => t('Created'),
        'type' => 'date_range',
        'from_param' => 'created_from',
        'to_param' => 'created_to',
    ],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
