<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
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(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW, [
    'actor_user_id' => $currentUserId,
]);
if (!$decision->isAllowed()) {
    Guard::deny();
}
$capabilities = $decision->attribute('capabilities', []);
$allowedTenantIds = is_array($capabilities) ? array_values(array_unique(array_map('intval', (array) ($capabilities['allowed_tenant_ids'] ?? [])))) : [];
$isStrictScope = is_array($capabilities) ? (bool) ($capabilities['is_strict_scope'] ?? false) : false;
$canCreateDepartments = is_array($capabilities) ? (bool) ($capabilities['can_create_department'] ?? false) : false;
$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
    'tenant' => ['type' => 'string'],
    'active' => ['type' => 'string', 'default' => 'all'],
    'search' => ['type' => 'string'],
]);

$tenants = app(\MintyPHP\Service\Tenant\TenantService::class)->list();
if ($allowedTenantIds) {
    $tenants = array_values(array_filter($tenants, static function (array $tenant) use ($allowedTenantIds): bool {
        $tenantId = (int) ($tenant['id'] ?? 0);
        return $tenantId > 0 && in_array($tenantId, $allowedTenantIds, true);
    }));
} elseif ($isStrictScope) {
    $tenants = [];
}
usort($tenants, static function ($a, $b) {
    return strcmp((string) ($a['description'] ?? ''), (string) ($b['description'] ?? ''));
});

Buffer::set('title', t('Departments'));
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)
);

$normalizedActiveFilter = (string) ($filterState['active'] ?? 'all');
if (in_array($normalizedActiveFilter, ['1', 'active'], true)) {
    $normalizedActiveFilter = 'active';
} elseif (in_array($normalizedActiveFilter, ['0', 'inactive'], true)) {
    $normalizedActiveFilter = 'inactive';
} elseif ($normalizedActiveFilter === '') {
    $normalizedActiveFilter = 'all';
}
$toolbarFilterStateOverrides = [
    'tenant' => (string) ($filterState['tenant'] ?? ''),
    'active' => $normalizedActiveFilter,
    'search' => (string) ($filterState['search'] ?? ''),
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'filter_state' => $filterState,
    'search_keys' => ['tenant', 'search'],
    'toolbar_state_overrides' => $toolbarFilterStateOverrides,
]);
$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'];
$activeTenant = (string) $toolbarFilterState['tenant'];
$activeStatus = (string) $toolbarFilterState['active'];
