<?php

use MintyPHP\Service\Docs\DocsCatalogService;

$layoutAuth = is_array($viewAuth['layout'] ?? null) ? $viewAuth['layout'] : [];
$canViewTenants = (bool) ($layoutAuth['can_view_tenants'] ?? false);
$canViewDepartments = (bool) ($layoutAuth['can_view_departments'] ?? false);
$canViewUsers = (bool) ($layoutAuth['can_view_users'] ?? false);
$canViewRoles = (bool) ($layoutAuth['can_view_roles'] ?? false);
$canViewPermissions = (bool) ($layoutAuth['can_view_permissions'] ?? false);
$canViewSettings = (bool) ($layoutAuth['can_view_settings'] ?? false);
$canViewImports = (bool) ($layoutAuth['can_view_imports'] ?? false);
$canViewJobs = (bool) ($layoutAuth['can_view_jobs'] ?? false);
$canViewApiDocs = (bool) ($layoutAuth['can_view_api_docs'] ?? false);
$canViewDocs = (bool) ($layoutAuth['can_view_docs'] ?? false);
$canViewMailLog = (bool) ($layoutAuth['can_view_mail_log'] ?? false);
$canViewApiAudit = (bool) ($layoutAuth['can_view_api_audit'] ?? false);
$canViewSystemAudit = (bool) ($layoutAuth['can_view_system_audit'] ?? false);
$canViewImportsAudit = (bool) ($layoutAuth['can_view_imports_audit'] ?? false);
$canViewUserLifecycleAudit = (bool) ($layoutAuth['can_view_user_lifecycle_audit'] ?? false);
$canViewStats = (bool) ($layoutAuth['can_view_stats'] ?? false);
$docsDefaultSlug = DocsCatalogService::defaultSlug();
$docsDefaultPath = 'admin/docs/' . $docsDefaultSlug;
$hasOrganization = $canViewTenants || $canViewDepartments || $canViewUsers;
$hasUsersSection = $canViewRoles || $canViewPermissions;
$hasAutomationSection = $canViewImports || $canViewJobs || $canViewApiDocs;
$hasMonitoringSection = $canViewStats;
$hasLogsSection = $canViewMailLog || $canViewApiAudit || $canViewSystemAudit || $canViewImportsAudit || $canViewUserLifecycleAudit;
$hasSystemSection = $canViewSettings || $canViewDocs;
$hasAdminPanel = layoutHasAdminPanel($layoutAuth);

// Declarative nav config for admin panel groups
$adminNavGroups = [
    [
        'key' => 'admin-organization',
        'label' => t('Organization'),
        'icon' => 'bi-building',
        'visible' => $hasOrganization,
        'items' => [
            [
                'label' => t('Tenants'),
                'path' => 'admin/tenants',
                'active' => navActive('admin/tenants', true),
                'visible' => $canViewTenants,
                'withTenant' => false,
            ],
            [
                'label' => t('Departments'),
                'path' => 'admin/departments',
                'active' => navActive('admin/departments', true),
                'visible' => $canViewDepartments,
                'withTenant' => true,
            ],
            [
                'label' => t('Users'),
                'path' => 'admin/users',
                'active' => navActive('admin/users', true),
                'visible' => $canViewUsers,
                'withTenant' => true,
            ],
        ],
    ],
    [
        'key' => 'admin-roles-permissions',
        'label' => t('Roles & permissions'),
        'icon' => 'bi-shield-lock',
        'visible' => $hasUsersSection,
        'items' => [
            [
                'label' => t('Roles'),
                'path' => 'admin/roles',
                'active' => navActive('admin/roles', true),
                'visible' => $canViewRoles,
                'withTenant' => false,
            ],
            [
                'label' => t('Permissions'),
                'path' => 'admin/permissions',
                'active' => navActive('admin/permissions', true),
                'visible' => $canViewPermissions,
                'withTenant' => false,
            ],
        ],
    ],
    [
        'key' => 'admin-automation',
        'label' => t('Automation & integrations'),
        'icon' => 'bi-plug',
        'visible' => $hasAutomationSection,
        'items' => [
            [
                'label' => t('Imports'),
                'path' => 'admin/imports',
                'active' => navActive('admin/imports', true),
                'visible' => $canViewImports,
                'withTenant' => false,
            ],
            [
                'label' => t('Scheduled jobs'),
                'path' => 'admin/scheduled-jobs',
                'active' => navActive('admin/scheduled-jobs', true),
                'visible' => $canViewJobs,
                'withTenant' => false,
            ],
            [
                'label' => t('API docs'),
                'path' => 'admin/api-docs',
                'active' => navActive('admin/api-docs', true),
                'visible' => $canViewApiDocs,
                'withTenant' => false,
            ],
        ],
    ],
    [
        'key' => 'admin-monitoring',
        'label' => t('Monitoring'),
        'icon' => 'bi-graph-up',
        'visible' => $hasMonitoringSection,
        'items' => [
            [
                'label' => t('Statistics'),
                'path' => 'admin/stats',
                'active' => navActive('admin/stats', true),
                'visible' => $canViewStats,
                'withTenant' => false,
            ],
        ],
    ],
    [
        'key' => 'admin-logs',
        'label' => t('Logs'),
        'icon' => 'bi-journal-text',
        'visible' => $hasLogsSection,
        'items' => [
            [
                'label' => t('Mail logs'),
                'path' => 'admin/mail-log',
                'active' => navActive('admin/mail-log', true),
                'visible' => $canViewMailLog,
                'withTenant' => false,
            ],
            [
                'label' => t('API audit'),
                'path' => 'admin/api-audit',
                'active' => navActive('admin/api-audit', true),
                'visible' => $canViewApiAudit,
                'withTenant' => false,
            ],
            [
                'label' => t('System audit logs'),
                'path' => 'admin/system-audit',
                'active' => navActive('admin/system-audit', true),
                'visible' => $canViewSystemAudit,
                'withTenant' => false,
            ],
            [
                'label' => t('Import logs'),
                'path' => 'admin/import-audit',
                'active' => navActive('admin/import-audit', true),
                'visible' => $canViewImportsAudit,
                'withTenant' => false,
            ],
            [
                'label' => t('User lifecycle logs'),
                'path' => 'admin/user-lifecycle-audit',
                'active' => navActive('admin/user-lifecycle-audit', true),
                'visible' => $canViewUserLifecycleAudit,
                'withTenant' => false,
            ],
        ],
    ],
    [
        'key' => 'admin-system',
        'label' => t('System'),
        'icon' => 'bi-sliders',
        'visible' => $hasSystemSection,
        'items' => [
            [
                'label' => t('Settings'),
                'path' => 'admin/settings',
                'active' => navActive('admin/settings', true),
                'visible' => $canViewSettings,
                'withTenant' => false,
            ],
            [
                'label' => t('Documentation'),
                'path' => $docsDefaultPath,
                'active' => navActive('admin/docs', true),
                'visible' => $canViewDocs,
                'withTenant' => false,
            ],
        ],
    ],
];

// Render helper for grouped admin aside navigation
$renderAdminNavGroup = static function (array $group, string $tenantQueryParam): void {
    if (empty($group['visible'])) {
        return;
    }
    $groupKey = trim((string) ($group['key'] ?? ''));
    if ($groupKey === '') {
        return;
    }
    $items = $group['items'] ?? [];
    $items = array_values(array_filter($items, static fn ($item) => !empty($item['visible'])));
    if (!$items) {
        return;
    }
    $groupIsActive = false;
    foreach ($items as $item) {
        $activeState = $item['active'] ?? [];
        if (!empty($activeState['isActive'])) {
            $groupIsActive = true;
            break;
        }
    }
    ?>
    <li class="app-sidebar-group app-sidebar-admin-group">
        <details data-details-key="<?php e($groupKey); ?>"<?php if ($groupIsActive): ?> open<?php endif; ?>>
            <summary>
                <?php if (!empty($group['icon'])): ?><i class="bi <?php e($group['icon']); ?>"></i> <?php endif; ?>
                <span><?php e($group['label'] ?? ''); ?></span>
            </summary>
            <ul>
                <?php foreach ($items as $item): ?>
                    <?php
                    $href = $item['path'] ?? '';
                    if ($href !== '' && !empty($item['withTenant'])) {
                        $href .= $tenantQueryParam;
                    }
                    $active = $item['active'] ?? ['class' => '', 'aria' => ''];
                    ?>
                    <li>
                        <a href="<?php e($href); ?>" class="<?php e($active['class'] ?? ''); ?>" <?php echo $active['aria'] ?? ''; ?>>
                            <?php e($item['label'] ?? ''); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </details>
    </li>
    <?php
};

// Read precomputed layout context from web/index.php (before Session::end()).
$layoutNav = is_array($layoutNav ?? null) ? $layoutNav : [];
$currentTenant = is_array($layoutNav['currentTenant'] ?? null) ? $layoutNav['currentTenant'] : null;
$availableTenants = is_array($layoutNav['availableTenants'] ?? null) ? $layoutNav['availableTenants'] : [];
$tenantQueryParam = trim((string) ($layoutNav['tenantQueryParam'] ?? ''));
$tenantAvatar = is_array($layoutNav['tenantAvatar'] ?? null) ? $layoutNav['tenantAvatar'] : [];
$tenantUuid = trim((string) ($tenantAvatar['uuid'] ?? ''));
$tenantName = trim((string) ($tenantAvatar['name'] ?? ''));
$hasTenantAvatar = !empty($tenantAvatar['hasAvatar']);
$csrfKey = trim((string) ($layoutNav['csrfKey'] ?? \MintyPHP\Session::$csrfSessionKey));
$csrfToken = (string) ($layoutNav['csrfToken'] ?? '');
$moduleSlots = is_array($layoutNav['moduleSlots'] ?? null) ? $layoutNav['moduleSlots'] : [];
$modulePanelSlots = is_array($moduleSlots['aside.tab_panel'] ?? null) ? $moduleSlots['aside.tab_panel'] : [];
$moduleSearchSlots = is_array($moduleSlots['search.resource_item'] ?? null) ? $moduleSlots['search.resource_item'] : [];
?>
<aside class="app-sidebar" id="app-sidebar" data-app-component="sidebar-toggle">
    <?php if ($currentTenant): ?>
        <div class="app-sidebar-tenant-logo">
            <a href="<?php e(lurl('')); ?>">
                <?php if ($hasTenantAvatar): ?>
                    <img src="auth/tenant-avatar-file?uuid=<?php e($tenantUuid); ?>&size=128" alt="<?php e($tenantName); ?>"
                        title="<?php e($tenantName); ?>">
                <?php else: ?>
                    <div class="app-sidebar-tenant-name">
                        <?php e($tenantName); ?>
                    </div>
                <?php endif; ?>
            </a>
            <button type="button" class="app-sidebar-tenant-toggle" data-sidebar-toggle
                aria-label="<?php e(t('Toggle Sidebar')); ?>">
                <i class="bi bi-list"></i>
            </button>
        </div>
    <?php endif; ?>
    <div id="app-sidebar-panels" class="app-sidebar-panels">
        <nav id="aside-panel-explorer" class="app-sidebar-panel" data-aside-panel="explorer"
            data-aside-title="<?php e(t('Explorer')); ?>" role="tabpanel" aria-labelledby="aside-tab-explorer"
            aria-label="<?php e(t('Primary navigation')); ?>">
            <ul>
                <li>
                    <?php $home = navActive(['', 'admin'], false); ?>
                    <a href="<?php e(lurl('')); ?>" class="<?php e($home['class']); ?>" <?php echo $home['aria']; ?>>
                        <?php e(t('Home')); ?>
                    </a>
                </li>
            </ul>
        </nav>
        <?php if ($hasAdminPanel): ?>
            <nav id="aside-panel-admin" class="app-sidebar-panel" data-aside-panel="admin"
                data-aside-title="<?php e(t('Admin')); ?>" data-aside-details-storage="aside-admin-sections-v1"
                data-aside-details-open-active="1" role="tabpanel" aria-labelledby="aside-tab-admin" hidden>
                <ul>
                    <?php foreach ($adminNavGroups as $group): ?>
                        <?php $renderAdminNavGroup($group, $tenantQueryParam); ?>
                    <?php endforeach; ?>
                </ul>
            </nav>
        <?php endif; ?>

        <?php
        // ── Module-contributed aside panels (aside.tab_panel slot) ──
        foreach ($modulePanelSlots as $panelSlot):
            if (!is_array($panelSlot)) { continue; }
            $panelKey = $panelSlot['key'] ?? '';
            $panelLabel = $panelSlot['label'] ?? '';
            $panelTemplate = $panelSlot['panel_template'] ?? '';
            $panelPermission = $panelSlot['permission'] ?? '';
            if ($panelPermission !== '' && empty($layoutAuth[$panelPermission])) { continue; }
            if ($panelKey === '' || $panelTemplate === '') { continue; }
        ?>
            <?php
            $panelDetailsStorage = $panelSlot['details_storage'] ?? '';
            $panelDetailsOpenActive = !empty($panelSlot['details_open_active']);
            ?>
            <nav id="aside-panel-<?php e($panelKey); ?>" class="app-sidebar-panel"
                data-aside-panel="<?php e($panelKey); ?>"
                <?php if ($panelDetailsStorage !== ''): ?>data-aside-details-storage="<?php e($panelDetailsStorage); ?>"<?php endif; ?>
                <?php if ($panelDetailsOpenActive): ?>data-aside-details-open-active="1"<?php endif; ?>
                data-aside-title="<?php e(t($panelLabel)); ?>"
                role="tabpanel" aria-labelledby="aside-tab-<?php e($panelKey); ?>" hidden>
                <?php
                // Include the module-provided panel template
                $panelTemplatePath = $panelTemplate;
                if (is_file($panelTemplatePath)) {
                    include $panelTemplatePath;
                }
                ?>
            </nav>
        <?php endforeach; ?>

        <div id="aside-panel-search" class="app-sidebar-panel" data-app-component="global-search" data-aside-panel="search"
            data-aside-title="<?php e(t('Search')); ?>" role="tabpanel" aria-labelledby="aside-tab-search" hidden>
            <form class="app-search">
                <input type="search" name="side-search" id="side-search" placeholder="<?php e(t('Search...')); ?>"
                    aria-label="<?php e(t('Search')); ?>">
                <span class="app-search-shortcut" data-search-shortcut aria-hidden="true"></span>
            </form>
            <div class="app-search-empty-state" data-global-search-empty>
                <i class="bi bi-search" aria-hidden="true"></i>
                <p><?php e(t('To start searching, type in the search field.')); ?></p>
                <small class="muted" data-search-empty-hint-template="<?php e(t('Tip: Use {shortcut} to focus search quickly.')); ?>"></small>
            </div>
            <nav id="global-search">
                <ul class="app-search-results" data-global-search-results aria-live="polite">
                    <?php if ($canViewUsers): ?>
                        <?php $usersSearch = navActive('admin/users', true); ?>
                        <li data-search-key="users" data-search-base="<?php e(lurl('admin/users')); ?>">
                            <a href="<?php e(lurl('admin/users')); ?>" class="<?php e($usersSearch['class']); ?>" <?php echo $usersSearch['aria']; ?>>
                                <span><?php e(t('Users')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewTenants): ?>
                        <?php $tenantsSearch = navActive('admin/tenants', true); ?>
                        <li data-search-key="tenants" data-search-base="<?php e(lurl('admin/tenants')); ?>">
                            <a href="<?php e(lurl('admin/tenants')); ?>" class="<?php e($tenantsSearch['class']); ?>" <?php echo $tenantsSearch['aria']; ?>>
                                <span><?php e(t('Tenants')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewDepartments): ?>
                        <?php $departmentsSearch = navActive('admin/departments', true); ?>
                        <li data-search-key="departments" data-search-base="<?php e(lurl('admin/departments')); ?>">
                            <a href="<?php e(lurl('admin/departments')); ?>"
                                class="<?php e($departmentsSearch['class']); ?>" <?php echo $departmentsSearch['aria']; ?>>
                                <span><?php e(t('Departments')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewRoles): ?>
                        <?php $rolesSearch = navActive('admin/roles', true); ?>
                        <li data-search-key="roles" data-search-base="<?php e(lurl('admin/roles')); ?>">
                            <a href="<?php e(lurl('admin/roles')); ?>" class="<?php e($rolesSearch['class']); ?>" <?php echo $rolesSearch['aria']; ?>>
                                <span><?php e(t('Roles')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewPermissions): ?>
                        <?php $permissionsSearch = navActive('admin/permissions', true); ?>
                        <li data-search-key="permissions" data-search-base="<?php e(lurl('admin/permissions')); ?>">
                            <a href="<?php e(lurl('admin/permissions')); ?>"
                                class="<?php e($permissionsSearch['class']); ?>" <?php echo $permissionsSearch['aria']; ?>>
                                <span><?php e(t('Permissions')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewJobs): ?>
                        <?php $scheduledJobsSearch = navActive('admin/scheduled-jobs', true); ?>
                        <li data-search-key="scheduled-jobs" data-search-base="<?php e(lurl('admin/scheduled-jobs')); ?>">
                            <a href="<?php e(lurl('admin/scheduled-jobs')); ?>"
                                class="<?php e($scheduledJobsSearch['class']); ?>" <?php echo $scheduledJobsSearch['aria']; ?>>
                                <span><?php e(t('Scheduled jobs')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php
                    $pagesSearch = navActivePublicPages();
                    ?>
                    <li data-search-key="pages" data-search-base="<?php e(lurl('')); ?>">
                        <a href="<?php e(lurl('')); ?>" class="<?php e($pagesSearch['class']); ?>" <?php echo $pagesSearch['aria']; ?>>
                            <span><?php e(t('Pages')); ?></span>
                            <span class="badge" data-search-count>0</span>
                        </a>
                        <ul class="app-search-preview" data-search-preview></ul>
                    </li>
                    <?php if ($canViewDocs): ?>
                        <?php $docsSearch = navActive('admin/docs', true); ?>
                        <li data-search-key="docs" data-search-base="<?php e(lurl($docsDefaultPath)); ?>">
                            <a href="<?php e(lurl($docsDefaultPath)); ?>" class="<?php e($docsSearch['class']); ?>" <?php echo $docsSearch['aria']; ?>>
                                <span><?php e(t('Documentation')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php $hotkeysSearch = navActive('help/hotkeys', true); ?>
                    <li data-search-key="hotkeys" data-search-base="<?php e(lurl('help/hotkeys')); ?>">
                        <a href="<?php e(lurl('help/hotkeys')); ?>" class="<?php e($hotkeysSearch['class']); ?>" <?php echo $hotkeysSearch['aria']; ?>>
                            <span><?php e(t('Keyboard shortcuts')); ?></span>
                            <span class="badge" data-search-count>0</span>
                        </a>
                        <ul class="app-search-preview" data-search-preview></ul>
                    </li>
                    <?php if ($canViewMailLog): ?>
                        <?php $mailLogSearch = navActive('admin/mail-log', true); ?>
                        <li data-search-key="mail-log" data-search-base="<?php e(lurl('admin/mail-log')); ?>">
                            <a href="<?php e(lurl('admin/mail-log')); ?>" class="<?php e($mailLogSearch['class']); ?>"
                                <?php echo $mailLogSearch['aria']; ?>>
                                <span><?php e(t('Mail logs')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewApiAudit): ?>
                        <?php $apiAuditSearch = navActive('admin/api-audit', true); ?>
                        <li data-search-key="api-audit" data-search-base="<?php e(lurl('admin/api-audit')); ?>">
                            <a href="<?php e(lurl('admin/api-audit')); ?>" class="<?php e($apiAuditSearch['class']); ?>"
                                <?php echo $apiAuditSearch['aria']; ?>>
                                <span><?php e(t('API audit')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php if ($canViewSystemAudit): ?>
                        <?php $systemAuditSearch = navActive('admin/system-audit', true); ?>
                        <li data-search-key="system-audit" data-search-base="<?php e(lurl('admin/system-audit')); ?>">
                            <a href="<?php e(lurl('admin/system-audit')); ?>" class="<?php e($systemAuditSearch['class']); ?>"
                                <?php echo $systemAuditSearch['aria']; ?>>
                                <span><?php e(t('System audit')); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endif; ?>
                    <?php
                    $coreSearchKeys = [
                        'users' => true,
                        'tenants' => true,
                        'departments' => true,
                        'roles' => true,
                        'permissions' => true,
                        'scheduled-jobs' => true,
                        'pages' => true,
                        'docs' => true,
                        'hotkeys' => true,
                        'mail-log' => true,
                        'api-audit' => true,
                        'system-audit' => true,
                    ];
                    foreach ($moduleSearchSlots as $searchSlot):
                        if (!is_array($searchSlot)) { continue; }
                        $slotKey = trim((string) ($searchSlot['key'] ?? ''));
                        if ($slotKey === '' || isset($coreSearchKeys[$slotKey])) { continue; }
                        $slotPermission = trim((string) ($searchSlot['permission'] ?? ''));
                        if ($slotPermission !== '' && empty($layoutAuth[$slotPermission])) { continue; }
                        $slotLabel = trim((string) ($searchSlot['label'] ?? ''));
                        if ($slotLabel === '') { continue; }
                        $slotBase = trim((string) ($searchSlot['base_url'] ?? ''));
                        if ($slotBase === '') { continue; }
                        $slotHref = $slotBase;
                        $slotActive = ['class' => '', 'aria' => ''];
                        if (!str_starts_with($slotBase, '/') && !str_starts_with($slotBase, 'http://') && !str_starts_with($slotBase, 'https://')) {
                            $slotHref = lurl($slotBase);
                            $slotActive = navActive($slotBase, true);
                        }
                    ?>
                        <li data-search-key="<?php e($slotKey); ?>" data-search-base="<?php e($slotHref); ?>">
                            <a href="<?php e($slotHref); ?>" class="<?php e($slotActive['class'] ?? ''); ?>"
                                <?php echo $slotActive['aria'] ?? ''; ?>>
                                <span><?php e(t($slotLabel)); ?></span>
                                <span class="badge" data-search-count>0</span>
                            </a>
                            <ul class="app-search-preview" data-search-preview></ul>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </nav>
        </div>
    </div>
</aside>
