<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\RoleAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

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

$currentUserId = (int) ($session['user']['id'] ?? 0);
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$decision = $authorizationService->authorize(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}
$capabilities = $decision->attribute('capabilities', []);
$canCreateRoles = is_array($capabilities) ? (bool) ($capabilities['can_create_role'] ?? false) : false;
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
    'search' => ['type' => 'string'],
    'active' => ['type' => 'string', 'default' => 'all'],
]);
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'filter_state' => $filterState,
    'search_keys' => ['search'],
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'active' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['active']['default'] ?? 'all')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['active'] ?? [])),
    ],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];

Buffer::set('title', t('Roles'));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('Roles')],
];
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$csrfKey = Session::$csrfSessionKey;
$csrfToken = $session[$csrfKey] ?? '';
Buffer::set(
    'grid_csrf',
    json_encode(['key' => $csrfKey, 'token' => $csrfToken], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);
