<?php

use MintyPHP\Buffer;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::DEPARTMENTS_VIEW);

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($currentUserId > 0) {
    permissionGateway()->getUserPermissions($currentUserId);
}

$tenants = directoryServicesFactory()->createTenantService()->list();
$allowedTenantIds = directoryServicesFactory()->createDirectoryScopeGateway()->getUserTenantIds($currentUserId);
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 (directoryServicesFactory()->createDirectoryScopeGateway()->isStrict()) {
    $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)
);
