<?php

use MintyPHP\Module\Audit\Domain\UserLifecycleAction;
use MintyPHP\Module\Audit\Domain\UserLifecycleStatus;
use MintyPHP\Module\Audit\Domain\UserLifecycleTriggerType;

$canPurge = (bool) ($canUpdateSettings ?? false);

$filterSchema = require __DIR__ . '/../pages/audit/settings-user-lifecycle/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
    ...gridSchemaQuery($filterSchema),
    'actions' => [
        'type' => 'csv_strings',
        'max' => 200,
        'return' => 'array',
        'sanitizer' => gridEnumSanitizer(UserLifecycleAction::class),
    ],
    'statuses' => [
        'type' => 'csv_strings',
        'max' => 200,
        'return' => 'array',
        'sanitizer' => gridEnumSanitizer(UserLifecycleStatus::class),
    ],
    'trigger_types' => [
        'type' => 'csv_strings',
        'max' => 200,
        'return' => 'array',
        'sanitizer' => gridEnumSanitizer(UserLifecycleTriggerType::class),
    ],
    'actor_user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$activeActions = is_array($filterState['actions'] ?? null) ? $filterState['actions'] : [];
$activeStatuses = is_array($filterState['statuses'] ?? null) ? $filterState['statuses'] : [];
$activeTriggerTypes = is_array($filterState['trigger_types'] ?? null) ? $filterState['trigger_types'] : [];
$activeActorUserIds = array_map('strval', is_array($filterState['actor_user_ids'] ?? null) ? $filterState['actor_user_ids'] : []);

$actionLabelMap = [];
foreach (UserLifecycleAction::cases() as $actionCase) {
    $actionLabelMap[$actionCase->value] = t($actionCase->labelToken());
}
$statusLabelMap = [];
foreach (UserLifecycleStatus::cases() as $statusCase) {
    $statusLabelMap[$statusCase->value] = t($statusCase->labelToken());
}
$triggerLabelMap = [];
foreach (UserLifecycleTriggerType::cases() as $triggerCase) {
    $triggerLabelMap[$triggerCase->value] = t($triggerCase->labelToken());
}

$lifecycleActionItems = [];
foreach (UserLifecycleAction::values() as $action) {
    $lifecycleActionItems[$action] = [
        'id' => $action,
        'description' => $actionLabelMap[$action] ?? $action,
    ];
}
$lifecycleActionItems = array_values($lifecycleActionItems);

$lifecycleStatusItems = [];
foreach (UserLifecycleStatus::values() as $status) {
    $lifecycleStatusItems[$status] = [
        'id' => $status,
        'description' => $statusLabelMap[$status] ?? $status,
    ];
}
$lifecycleStatusItems = array_values($lifecycleStatusItems);

$lifecycleTriggerItems = [];
foreach (UserLifecycleTriggerType::values() as $triggerType) {
    $lifecycleTriggerItems[$triggerType] = [
        'id' => $triggerType,
        'description' => $triggerLabelMap[$triggerType] ?? $triggerType,
    ];
}
$lifecycleTriggerItems = array_values($lifecycleTriggerItems);

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

$toolbarFilterState = [
    'search' => (string) ($filterState['search'] ?? ''),
    'actions' => $activeActions,
    'statuses' => $activeStatuses,
    'trigger_types' => $activeTriggerTypes,
    'actor_user_ids' => $activeActorUserIds,
    'created_from' => (string) ($filterState['created_from'] ?? ''),
    'created_to' => (string) ($filterState['created_to'] ?? ''),
];
$toolbarOptionSets = [
    'action_items' => $lifecycleActionItems,
    'status_items' => $lifecycleStatusItems,
    'trigger_items' => $lifecycleTriggerItems,
    'actor_items' => $lifecycleActorItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'filter_state' => $filterState,
    'search_keys' => ['search'],
    'toolbar_state_overrides' => $toolbarFilterState,
    'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = is_array($listFilterContext['toolbarFilterSchema'] ?? null) ? $listFilterContext['toolbarFilterSchema'] : [];
$searchToolbarFilterSchema = is_array($listFilterContext['searchToolbarFilterSchema'] ?? null) ? $listFilterContext['searchToolbarFilterSchema'] : [];
$drawerToolbarFilterSchema = is_array($listFilterContext['drawerToolbarFilterSchema'] ?? null) ? $listFilterContext['drawerToolbarFilterSchema'] : [];
$toolbarFilterState = is_array($listFilterContext['toolbarFilterState'] ?? null) ? $listFilterContext['toolbarFilterState'] : [];
$toolbarOptionSets = is_array($listFilterContext['toolbarOptionSets'] ?? null) ? $listFilterContext['toolbarOptionSets'] : [];
$clientFilterSchema = is_array($listFilterContext['clientFilterSchema'] ?? null) ? $listFilterContext['clientFilterSchema'] : [];
$searchConfig = $listFilterContext['searchConfig'] ?? null;

$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'actions' => [
        'label' => t('Action'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($lifecycleActionItems),
    ],
    'statuses' => [
        'label' => t('Status'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($lifecycleStatusItems),
    ],
    'trigger_types' => [
        'label' => t('Trigger'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($lifecycleTriggerItems),
    ],
    'actor_user_ids' => [
        'label' => t('Actor'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($lifecycleActorItems),
    ],
    'created_range' => [
        'label' => t('Created'),
        'type' => 'date_range',
        'from_param' => 'created_from',
        'to_param' => 'created_to',
    ],
];

$filterUiNamespace = 'settings-user-lifecycle';
$filterToolbarId = 'settings-user-lifecycle-audit-toolbar';
$filterDrawerToolbarId = 'settings-user-lifecycle-audit-drawer-toolbar';
$filterDrawerTitleId = 'settings-user-lifecycle-audit-filter-drawer-title';

$pageConfig = [
    'dataUrl' => endpointUrl('admin/settings/user-lifecycle/audit-data'),
    'gridSearch' => $searchConfig,
    'filterSchema' => $clientFilterSchema,
    'filterChipMeta' => $filterChipMeta,
    'gridLang' => gridLang(),
    'labels' => [
        'created' => t('Created'),
        'status' => t('Status'),
        'action' => t('Action'),
        'trigger' => t('Trigger'),
        'targetEmail' => t('Target email'),
        'targetUuid' => t('Target UUID'),
        'reasonCode' => t('Reason code'),
        'restoredAt' => t('Restored at'),
    ],
];
?>

<section class="app-settings-user-lifecycle-audit" data-app-component="settings-user-lifecycle-audit">
  <?php require templatePath('partials/app-list-filters.phtml'); ?>

  <div class="app-list-table">
    <div id="settings-user-lifecycle-audit-grid"></div>
  </div>

  <script src="<?php e(assetVersion('vendor/gridjs/gridjs.umd.js')); ?>"></script>
  <script type="application/json" id="page-config-settings-user-lifecycle-audit-panel"><?php gridJsonForJs($pageConfig); ?></script>
  <script type="module" src="<?php e(assetVersion('modules/audit/js/pages/settings-user-lifecycle-audit-panel.js')); ?>"></script>
</section>
