<?php

use MintyPHP\Buffer;
use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Service\Access\UiCapabilityMap;
use MintyPHP\Service\Audit\UserLifecycleAuditService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
    (int) ($session['user']['id'] ?? 0),
    UiCapabilityMap::PAGE_AUDIT_PURGE
);

Buffer::set('title', t('User lifecycle 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),
    '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'],
]);
$filterOptions = app(UserLifecycleAuditService::class)->filterOptions(200);

$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,
    ];
}
foreach ((array) ($filterOptions['actions'] ?? []) as $action) {
    $action = strtolower(trim((string) $action));
    if ($action === '') {
        continue;
    }
    $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,
    ];
}
foreach ((array) ($filterOptions['statuses'] ?? []) as $status) {
    $status = strtolower(trim((string) $status));
    if ($status === '') {
        continue;
    }
    $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,
    ];
}
foreach ((array) ($filterOptions['trigger_types'] ?? []) as $triggerType) {
    $triggerType = strtolower(trim((string) $triggerType));
    if ($triggerType === '') {
        continue;
    }
    $lifecycleTriggerItems[$triggerType] = [
        'id' => $triggerType,
        'description' => $triggerLabelMap[$triggerType] ?? $triggerType,
    ];
}
$lifecycleTriggerItems = array_values($lifecycleTriggerItems);

$lifecycleActorItems = [];
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;
    $lifecycleActorItems[$id] = [
        'id' => $id,
        'description' => $label,
    ];
}
foreach ($activeActorUserIds as $actorId) {
    if (!isset($lifecycleActorItems[$actorId])) {
        $lifecycleActorItems[$actorId] = [
            'id' => $actorId,
            'description' => sprintf(t('User #%d (deleted)'), (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 = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$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',
    ],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
