<?php

declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../../app-support.php';
require_once dirname(__DIR__, 3) . '/app/Support/TenantResolver.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Models/Tenant.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Models/TenantUser.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Services/TenantService.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Services/TenantMembershipService.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Services/TenantRoleService.php';
require_once dirname(__DIR__, 3) . '/app/Modules/Tenants/Controllers/TenantConsoleController.php';

if (!function_exists('tenant_roles_h')) {
    function tenant_roles_h(string $value): string
    {
        return app_h($value);
    }
}

if (!function_exists('tenant_roles_implode')) {
    /**
     * @param array<int, string> $items
     */
    function tenant_roles_implode(array $items): string
    {
        return implode(', ', array_map('tenant_roles_h', $items));
    }
}

$auth = app_require_auth();
$tenantLicense = ['plan_name' => 'Free', 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();

if (!app_can_manage_tenant($auth)) {
    app_flash('Dieser Bereich ist nur für Tenant-Admins oder Global-Admins verfügbar.', 'warning');
    app_redirect('/dashboard/');
}

$tenantService = new \App\Modules\Tenants\Services\TenantService(new \App\Support\TenantResolver());
$roleService = new \App\Modules\Tenants\Services\TenantRoleService(
    $tenantService,
    new \App\Modules\Tenants\Services\TenantMembershipService()
);
$controller = new \App\Modules\Tenants\Controllers\TenantConsoleController($tenantService, $roleService);

try {
    $pdo = app_pdo();
    $tenantLicense = app_tenant_license($pdo, (string) ($auth['tenant_id'] ?? ''));
    $tenantSettings = app_tenant_settings($pdo, (string) ($auth['tenant_id'] ?? ''));
} catch (\Throwable $ignored) {
}

$tenantId = (string) ($_GET['tenant'] ?? $auth['tenant_id'] ?? '');
$payload = $controller->roles($tenantId !== '' ? $tenantId : null);
$pageData = $payload['data'] ?? [];
$overview = $pageData['overview'] ?? [];
$tenant = $overview['tenant'] ?? [];
$metrics = $overview['metrics'] ?? [];
$roles = $overview['roles'] ?? [];
$delegationRules = $overview['delegation_rules'] ?? [];
$tenantSnapshots = $overview['tenant_snapshots'] ?? [];
$permissionGroups = $overview['permission_groups'] ?? [];
$notes = $overview['notes'] ?? [];
$tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);
$tenantNavGroups = app_tenant_navigation_groups($tenantNavItems);
$tenantHeaderNavItems = [];
$mobileBottomNavItems = [];
$mobileDrawerPrimaryItems = [];
foreach ($tenantNavItems as $item) {
    if (in_array((string) ($item['key'] ?? ''), ['dashboard', 'ledger', 'payments'], true)) {
        $tenantHeaderNavItems[] = $item;
        $mobileBottomNavItems[] = $item;
    }
}

$template = dirname(__DIR__, 3) . '/resources/views/tenants/roles.blade.php';
if (!is_file($template)) {
    throw new RuntimeException('Die Rollen-Ansicht konnte nicht gefunden werden.');
}

ob_start();
require $template;
$output = ob_get_clean();

echo $output;
