<?php

use MintyPHP\Service\Docs\DocsCatalogService;

$layoutAuth = is_array($viewAuth['layout'] ?? null) ? $viewAuth['layout'] : [];
$moduleNavItemSlots = is_array(($layoutNav ?? [])['moduleSlots']['sidebar.admin_nav_item'] ?? null)
    ? $layoutNav['moduleSlots']['sidebar.admin_nav_item']
    : [];
$moduleExplorerNavSlots = is_array(($layoutNav ?? [])['moduleSlots']['explorer.nav_item'] ?? null)
    ? $layoutNav['moduleSlots']['explorer.nav_item']
    : [];
$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);
$canViewDocs = (bool) ($layoutAuth['can_view_docs'] ?? false);
$canViewMailLog = (bool) ($layoutAuth['can_view_mail_log'] ?? 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;
$hasLogsSection = $canViewMailLog;
$hasSystemSection = $canViewSettings || $canViewStats;
$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,
            ],
        ],
    ],
    [
        'key' => 'admin-logs',
        'label' => t('Logs'),
        'icon' => 'bi-journal-text',
        'visible' => $hasLogsSection,
        'items' => [
            [
                'label' => t('nav.logs.mail'),
                'path' => 'admin/mail-log',
                'active' => navActive('admin/mail-log', true),
                'visible' => $canViewMailLog,
                '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('Statistics'),
                'path' => 'admin/stats',
                'active' => navActive('admin/stats', true),
                'visible' => $canViewStats,
                'withTenant' => false,
            ],
        ],
    ],
];

// ── Append module-contributed admin nav groups (sidebar.admin_nav_item slot) ──
// Module items are grouped by their 'group' key. Each unique group becomes a
// <details><summary> section appended after the core admin nav groups.
if ($moduleNavItemSlots) {
    $moduleGroupsByKey = [];
    usort($moduleNavItemSlots, static fn ($a, $b) => ($a['order'] ?? 100) <=> ($b['order'] ?? 100));
    foreach ($moduleNavItemSlots as $slot) {
        if (!is_array($slot)) { continue; }
        $groupKey = trim((string) ($slot['group'] ?? ''));
        $slotPath = trim((string) ($slot['path'] ?? ''));
        $slotLabel = trim((string) ($slot['label'] ?? ''));
        $slotPermission = trim((string) ($slot['permission'] ?? ''));
        if ($groupKey === '' || $slotPath === '' || $slotLabel === '') { continue; }
        $slotVisible = $slotPermission === '' || !empty($layoutAuth[$slotPermission]);
        if (!isset($moduleGroupsByKey[$groupKey])) {
            $moduleGroupsByKey[$groupKey] = [];
        }
        $moduleGroupsByKey[$groupKey][] = [
            'label' => t($slotLabel),
            'path' => $slotPath,
            'active' => navActive($slotPath, true),
            'visible' => $slotVisible,
            'withTenant' => false,
        ];
    }
    // Known group metadata — modules declare their group key, we map to label + icon.
    $moduleGroupMeta = [
        'admin-automation' => ['label' => t('Automation & integrations'), 'icon' => 'bi-gear-wide-connected'],
        'admin-logs' => ['label' => t('Audit & logs'), 'icon' => 'bi-journal-text'],
    ];
    foreach ($moduleGroupsByKey as $groupKey => $items) {
        $hasVisible = false;
        foreach ($items as $item) {
            if (!empty($item['visible'])) { $hasVisible = true; break; }
        }
        // Also add mail log to the logs group if it exists as a core item
        if ($groupKey === 'admin-logs' && $canViewMailLog) {
            array_unshift($items, [
                'label' => t('nav.logs.mail'),
                'path' => 'admin/mail-log',
                'active' => navActive('admin/mail-log', true),
                'visible' => $canViewMailLog,
                'withTenant' => false,
            ]);
            $hasVisible = true;
        }
        $meta = $moduleGroupMeta[$groupKey] ?? ['label' => $groupKey, 'icon' => 'bi-list'];
        $adminNavGroups[] = [
            'key' => $groupKey,
            'label' => $meta['label'],
            'icon' => $meta['icon'],
            'visible' => $hasVisible,
            'items' => $items,
        ];
    }
    // If modules contributed to admin-logs, remove the core-only logs group (which only had mail log)
    if (isset($moduleGroupsByKey['admin-logs'])) {
        $adminNavGroups = array_values(array_filter($adminNavGroups, static function ($g) {
            // Remove the original core logs group (it's been merged into the module-contributed one)
            return !(($g['key'] ?? '') === 'admin-logs' && count($g['items'] ?? []) === 1 && ($g['items'][0]['path'] ?? '') === 'admin/mail-log');
        }));
    }
}

// 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'] ?? ''; // raw-html-ok: pre-built ARIA attribute from navActive() ?>>
                            <?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'] ?? ''));
$tenantLogo = is_array($layoutNav['tenantLogo'] ?? null) ? $layoutNav['tenantLogo'] : [];
$tenantUuid = trim((string) ($tenantLogo['uuid'] ?? ''));
$tenantName = trim((string) ($tenantLogo['name'] ?? ''));
$hasTenantLogoLight = !empty($tenantLogo['hasLogoLight']);
$hasTenantLogoDark = !empty($tenantLogo['hasLogoDark']);
$hasTenantLogo = $hasTenantLogoLight || $hasTenantLogoDark;
$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'] : [];
?>
<aside class="app-sidebar" id="app-sidebar" data-app-component="sidebar-toggle">
    <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']; // raw-html-ok: pre-built ARIA attribute from navActive() ?>>
                        <?php e(t('Home')); ?>
                    </a>
                </li>
                <?php foreach ($moduleExplorerNavSlots as $explorerSlot):
                    if (!is_array($explorerSlot)) { continue; }
                    $explorerKey = $explorerSlot['key'] ?? '';
                    $explorerLabel = $explorerSlot['label'] ?? '';
                    $explorerHref = $explorerSlot['href'] ?? '';
                    $explorerPermission = $explorerSlot['permission'] ?? '';
                    if ($explorerKey === '' || $explorerHref === '') { continue; }
                    if ($explorerPermission !== '' && empty($layoutAuth[$explorerPermission])) { continue; }
                    if (!str_starts_with($explorerHref, '/') && !str_starts_with($explorerHref, 'http')) {
                        $explorerHref = lurl($explorerHref);
                    }
                    $explorerActive = navActive($explorerSlot['href'], true);
                ?>
                    <li>
                        <a href="<?php e($explorerHref); ?>" class="<?php e($explorerActive['class'] ?? ''); ?>"
                            <?php echo $explorerActive['aria'] ?? ''; // raw-html-ok: pre-built ARIA attribute from navActive() ?>>
                            <?php e(t($explorerLabel)); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </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>
</aside>
