<?php
$uri = uri_string();
$navPerms = $navPerms ?? new \App\Services\NavigationPermissionService();

$navActive = static function (string $prefix) use ($uri): bool {
    $isReportUri = static function (string $uri): bool {
        $reportPrefixes = [
            'reports',
            'payroll/reports',
            'attendance/monthly',
            'attendance/late',
            'attendance/early-exit',
            'attendance/overtime',
            'sale/reports',
            'inventory/reports',
            'procurement/reports',
            'accounting/reports',
            'accounting/tax-reports',
            'accounting/receivables-aging',
            'accounting/payables-aging',
            'operations/work-orders/completion-reports',
        ];

        foreach ($reportPrefixes as $reportPrefix) {
            if ($uri === $reportPrefix || str_starts_with($uri, $reportPrefix . '/')) {
                return true;
            }
        }

        return false;
    };

    if ($prefix === 'dashboard') {
        return $uri === 'dashboard' || $uri === '';
    }

    if ($prefix === 'profile') {
        return $uri === 'profile';
    }

    if ($prefix === 'settings') {
        return $uri === 'settings' || str_starts_with($uri, 'settings/');
    }

    if ($prefix === 'reports') {
        return $isReportUri($uri);
    }

    if ($isReportUri($uri)) {
        return false;
    }

    if ($prefix === 'hrm') {
        return $uri === 'hrm' || str_starts_with($uri, 'employees') || str_starts_with($uri, 'departments')
            || str_starts_with($uri, 'leave') || str_starts_with($uri, 'holidays')
            || str_starts_with($uri, 'attendance') || str_starts_with($uri, 'payroll')
            || str_starts_with($uri, 'assets') || str_starts_with($uri, 'documents')
            || str_starts_with($uri, 'scheduling');
    }

    if ($prefix === 'sale') {
        return $uri === 'sale' || str_starts_with($uri, 'sale/');
    }

    if ($prefix === 'contracts') {
        return $uri === 'contracts' || str_starts_with($uri, 'contracts/');
    }

    if ($prefix === 'procurement') {
        return $uri === 'procurement' || str_starts_with($uri, 'procurement/');
    }

    if ($prefix === 'inventory') {
        return $uri === 'inventory' || str_starts_with($uri, 'inventory/');
    }

    if ($prefix === 'accounting') {
        return $uri === 'accounting' || str_starts_with($uri, 'accounting/');
    }

    if ($prefix === 'operations') {
        return $uri === 'operations' || str_starts_with($uri, 'operations/');
    }

    if ($prefix === 'messages') {
        return $uri === 'messages' || str_starts_with($uri, 'messages/');
    }

    if ($prefix === 'administration') {
        return $uri === 'settings' || str_starts_with($uri, 'settings/')
            || str_starts_with($uri, 'users') || str_starts_with($uri, 'roles');
    }

    return str_starts_with($uri, $prefix);
};

$mainNavItems = array_values(array_filter([
    ['label' => 'Dashboard', 'href' => base_url('dashboard'), 'route' => 'dashboard'],
], static fn (array $item): bool => $navPerms->canAccessTopModule($item['route'])));

$moduleNavItems = array_values(array_filter([
    ['label' => 'HRM', 'href' => base_url('hrm'), 'route' => 'hrm'],
    ['label' => 'Sales & CRM', 'href' => base_url('sale'), 'route' => 'sale'],
    ['label' => 'Contracts', 'href' => base_url('contracts'), 'route' => 'contracts'],
    ['label' => 'Procurement', 'href' => base_url('procurement'), 'route' => 'procurement'],
    ['label' => 'Inventory', 'href' => base_url('inventory'), 'route' => 'inventory'],
    ['label' => 'Accounting', 'href' => base_url('accounting'), 'route' => 'accounting'],
    ['label' => 'Operations', 'href' => base_url('operations'), 'route' => 'operations'],
    ['label' => 'Transport', 'href' => base_url('transport'), 'route' => 'transport'],
    ['label' => 'Reports', 'href' => base_url('reports'), 'route' => 'reports'],
], static fn (array $item): bool => $navPerms->canAccessTopModule($item['route'])));

$showModulesBar = $moduleNavItems !== [];
$modulesBarOpen = $showModulesBar && (
    $navActive('hrm') || $navActive('sale') || $navActive('contracts') || $navActive('procurement')
    || $navActive('inventory') || $navActive('accounting') || $navActive('operations')
    || $navActive('transport') || $navActive('reports')
);
$canViewEmployees = $navPerms->canAccessPath('employees');
$canCreateEmployees = $navPerms->canAccessPath('employees/create');
$canViewMessages = $navPerms->canAccessPath('messages');

$unreadMessages = (int) ($unreadMessages ?? 0);

$renderNavItem = static function (array $item) use ($navActive): void { ?>
    <a
        href="<?= esc($item['href']) ?>"
        class="enterprise-nav-link<?= $navActive($item['route']) ? ' active' : '' ?>"
    >
        <?= esc($item['label']) ?>
    </a>
<?php };

$name = $currentUser['fullName'] ?? 'User';
$parts = preg_split('/\s+/', trim($name));
$initials = strtoupper(
    (isset($parts[0][0]) ? $parts[0][0] : 'U')
    . (isset($parts[1][0]) ? $parts[1][0] : '')
);
?>

<header class="enterprise-navbar">
    <div class="enterprise-navbar-inner">
        <a href="<?= base_url($navPerms->can('dashboard.view') ? 'dashboard' : 'profile') ?>" class="enterprise-brand">
            <img src="<?= base_url('assets/img/pulse-logo.svg') ?>" alt="" class="enterprise-brand-logo" width="32" height="32">
            <span class="enterprise-brand-text">PULSE</span>
        </a>

        <nav class="enterprise-nav" aria-label="Main navigation">
            <?php foreach ($mainNavItems as $item): ?>
                <?php $renderNavItem($item); ?>
            <?php endforeach; ?>

            <?php if ($showModulesBar): ?>
            <button
                type="button"
                class="enterprise-nav-link enterprise-nav-link--modules<?= $modulesBarOpen ? ' active' : '' ?>"
                id="enterpriseModulesToggle"
                aria-expanded="<?= $modulesBarOpen ? 'true' : 'false' ?>"
                aria-controls="enterpriseModulesBar"
            >
                Modules
                <i class="fa-solid fa-chevron-down enterprise-nav-chevron"></i>
            </button>
            <?php endif; ?>
        </nav>

        <div class="enterprise-navbar-actions">
            <?php if ($canViewEmployees): ?>
            <form action="<?= base_url('employees') ?>" method="get" class="enterprise-nav-search d-none d-xl-flex" role="search">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="search" name="q" placeholder="Search directory..." aria-label="Search directory">
            </form>
            <?php endif; ?>

            <?php if ($canCreateEmployees): ?>
            <a href="<?= base_url('employees/create') ?>" class="enterprise-icon-btn d-none d-md-inline-flex" title="Quick add employee" aria-label="Add employee">
                <i class="fa-solid fa-plus"></i>
            </a>
            <?php endif; ?>
            <button type="button" class="enterprise-icon-btn d-none d-md-inline-flex" title="Notifications" aria-label="Notifications" disabled>
                <i class="fa-regular fa-bell"></i>
            </button>
            <?php if ($canViewMessages): ?>
            <a href="<?= base_url('messages') ?>" class="enterprise-icon-btn d-none d-md-inline-flex<?= $navActive('messages') ? ' active' : '' ?>" title="Messages" aria-label="Messages">
                <i class="fa-regular fa-envelope"></i>
                <?php if ($unreadMessages > 0): ?>
                    <span class="msg-nav-badge"><?= $unreadMessages > 99 ? '99+' : $unreadMessages ?></span>
                <?php endif; ?>
            </a>
            <?php endif; ?>

            <?php if (! empty($isAdmin)): ?>
                <a
                    href="<?= base_url('settings') ?>"
                    class="enterprise-profile-btn enterprise-settings-btn<?= $navActive('settings') ? ' active' : '' ?>"
                    aria-label="Settings"
                >
                    <i class="fa-solid fa-gear"></i>
                    <span>Settings</span>
                </a>
            <?php endif; ?>

            <a
                href="<?= base_url('profile') ?>"
                class="enterprise-profile-btn<?= $navActive('profile') ? ' active' : '' ?>"
            >
                <i class="fa-solid fa-user"></i>
                <span>Profile</span>
            </a>

            <div class="dropdown">
                <button class="enterprise-user-btn" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Account menu">
                    <span class="enterprise-avatar"><?= esc($initials) ?></span>
                    <i class="fa-solid fa-chevron-down enterprise-user-chevron"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end enterprise-nav-menu">
                    <li class="px-3 py-2 border-bottom">
                        <div class="fw-semibold small"><?= esc($name) ?></div>
                        <div class="text-muted small"><?= esc($currentUser['username'] ?? '') ?></div>
                    </li>
                    <li><a class="dropdown-item" href="<?= base_url('password/change') ?>"><i class="fa-solid fa-lock me-2"></i>Change Password</a></li>
                    <li><a class="dropdown-item" href="<?= base_url('account/sessions') ?>"><i class="fa-solid fa-display me-2"></i>Active Sessions</a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-danger" href="<?= base_url('logout') ?>"><i class="fa-solid fa-right-from-bracket me-2"></i>Logout</a></li>
                </ul>
            </div>

            <button class="enterprise-menu-toggle d-lg-none" type="button" data-bs-toggle="offcanvas" data-bs-target="#enterpriseMobileNav" aria-label="Open menu">
                <i class="fa-solid fa-bars"></i>
            </button>
        </div>
    </div>

    <?php if ($showModulesBar): ?>
    <div
        id="enterpriseModulesBar"
        class="enterprise-modules-bar<?= $modulesBarOpen ? ' is-open' : '' ?>"
        role="navigation"
        aria-label="Modules"
        <?= $modulesBarOpen ? '' : 'hidden' ?>
    >
        <div class="enterprise-modules-bar-inner">
            <nav class="enterprise-nav enterprise-nav--modules">
                <?php foreach ($moduleNavItems as $item): ?>
                    <?php $renderNavItem($item); ?>
                <?php endforeach; ?>
            </nav>
        </div>
    </div>
    <?php endif; ?>
</header>

<div class="offcanvas offcanvas-start enterprise-mobile-nav" tabindex="-1" id="enterpriseMobileNav">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title fw-bold small text-uppercase">Menu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>
    <div class="offcanvas-body">
        <nav class="enterprise-mobile-nav-list">
            <?php foreach ($mainNavItems as $item): ?>
                <a href="<?= esc($item['href']) ?>" class="enterprise-mobile-nav-link<?= $navActive($item['route']) ? ' active' : '' ?>">
                    <?= esc($item['label']) ?>
                </a>
            <?php endforeach; ?>

            <?php if ($showModulesBar): ?>
            <span class="enterprise-mobile-nav-link text-muted small text-uppercase">Modules</span>
            <?php foreach ($moduleNavItems as $item): ?>
                <a href="<?= esc($item['href']) ?>" class="enterprise-mobile-nav-link ps-3<?= $navActive($item['route']) ? ' active' : '' ?>">
                    <?= esc($item['label']) ?>
                </a>
            <?php endforeach; ?>
            <?php endif; ?>
            <hr class="my-3">
            <?php if (! empty($isAdmin)): ?>
                <a href="<?= base_url('settings') ?>" class="enterprise-mobile-nav-link<?= $navActive('settings') ? ' active' : '' ?>">Settings</a>
            <?php endif; ?>
            <a href="<?= base_url('profile') ?>" class="enterprise-mobile-nav-link<?= $navActive('profile') ? ' active' : '' ?>">Profile</a>
            <a href="<?= base_url('password/change') ?>" class="enterprise-mobile-nav-link<?= $navActive('password/change') ? ' active' : '' ?>">Change Password</a>
            <a href="<?= base_url('account/sessions') ?>" class="enterprise-mobile-nav-link<?= $navActive('account/sessions') ? ' active' : '' ?>">Active Sessions</a>
            <a href="<?= base_url('logout') ?>" class="enterprise-mobile-nav-link text-danger">Logout</a>
        </nav>
    </div>
</div>
