<?php

declare(strict_types=1);

// Prevent caching (only if headers still open)
if (!headers_sent()) {
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
}

require_once __DIR__ . '/../../src/helpers.php';
require_once __DIR__ . '/../../src/Auth/AuthManager.php';
require_once __DIR__ . '/../../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../../src/Permissions/PermissionManager.php';

function renderNavigationNew(string $activePage = '', string $theme = 'dark'): void
{
    // Check if user is authenticated
    if (!AuthManager::isAuthenticated()) {
        return;
    }

    // Get current user and company
    $user = AuthManager::getCurrentUser();

    // Get company from session first (most reliable), then URL parameter
    $company = null;
    $workspaceParam = $_GET['workspace'] ?? null;
    $pdo = getPDO();

    // Priority 1: Use session company if available
    if (isset($_SESSION['current_company_id'])) {
        $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
        $stmt->execute([$_SESSION['current_company_id']]);
        $company = $stmt->fetch();
    }

    // Priority 2: Use URL parameter if session company not found
    if (!$company && $workspaceParam) {
        if (is_string($workspaceParam) && !is_numeric($workspaceParam)) {
            // Search by username
            $stmt = $pdo->prepare("SELECT * FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
        } else {
            // Search by ID
            $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
            $stmt->execute([(int)$workspaceParam]);
            $company = $stmt->fetch();
        }
    }

    // Priority 3: Fallback to user's first company
    if (!$company) {
        $stmt = $pdo->prepare("SELECT c.* FROM companies c
                              JOIN user_company_access uca ON c.id = uca.company_id
                              WHERE uca.user_id = ?
                              ORDER BY c.id LIMIT 1");
        $stmt->execute([$user['id']]);
        $company = $stmt->fetch();
    }

    // Update session if we found a different company
    if ($company && (!isset($_SESSION['current_company_id']) || $_SESSION['current_company_id'] != $company['id'])) {
        $_SESSION['current_company_id'] = $company['id'];
        $_SESSION['current_company'] = $company;
    }

    $hasWorkspace = (bool) $company;
    $workspaceUsernameRaw = $hasWorkspace
        ? ($company['username'] ?? (string) $company['id'])
        : null;
    $workspaceSlug = $workspaceUsernameRaw ? urlencode((string) $workspaceUsernameRaw) : null;
    $workspaceQuery = $workspaceSlug ? '?workspace=' . $workspaceSlug : '';
    $workspaceQueryWithPrefix = $workspaceSlug ? '&workspace=' . $workspaceSlug : '';

    // Get user permissions for this workspace
    $userId = (int)$user['id'];
    $companyId = $company ? (int)$company['id'] : 0;
    $isOwner = $companyId ? PermissionManager::isOwner($userId, $companyId) : false;

    AuthManager::updateUserPresence($userId, $companyId ?: null, $_SERVER['REQUEST_URI'] ?? null);

    // Helper to check permission
    $hasPermission = function(string $permission) use ($userId, $companyId, $isOwner): bool {
        if (!$companyId) return false;
        if ($isOwner) return true;
        return PermissionManager::hasPermission($userId, $companyId, $permission);
    };

    // Build workspace query fragments for links
    $appendWorkspaceParam = function(string $path) use ($workspaceSlug): string {
        if (!$workspaceSlug) {
            return $path;
        }
        $separator = str_contains($path, '?') ? '&' : '?';
        return $path . $separator . 'workspace=' . $workspaceSlug;
    };

    // Build nav items with permission requirements
    $allNavItems = [
        ['path' => $workspaceSlug ? '/index.php' . $workspaceQuery : '/index.php', 'label' => 'Dashboard', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6', 'permission' => 'dashboard_view'],
        ['path' => $appendWorkspaceParam('/clients.php'), 'label' => 'Clients', 'icon' => 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z', 'permission' => 'clients_view'],
        ['path' => '#', 'label' => 'Proposals', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'permission' => 'proposals_view', 'dropdown' => [
            ['path' => $appendWorkspaceParam('/proposals.php'), 'label' => 'View All', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'permission' => 'proposals_view'],
            ['path' => $appendWorkspaceParam('/generate.php'), 'label' => 'Generate Proposal', 'icon' => 'M12 4v16m8-8H4', 'permission' => 'proposals_create'],
            ['path' => $appendWorkspaceParam('/templates.php'), 'label' => 'Manage Templates', 'icon' => 'M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z', 'permission' => 'templates_manage'],
            ['path' => $appendWorkspaceParam('/modules.php'), 'label' => 'Manage Modules', 'icon' => 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10', 'permission' => 'templates_manage'],
            ['path' => $appendWorkspaceParam('/labels.php'), 'label' => 'Labels', 'icon' => 'M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z', 'permission' => 'templates_manage'],
        ]],
        ['path' => '#', 'label' => 'Contracts', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'permission' => 'contracts_view', 'dropdown' => [
            ['path' => $appendWorkspaceParam('/contracts.php'), 'label' => 'View All', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'permission' => 'contracts_view'],
            ['path' => $appendWorkspaceParam('/contract_create.php'), 'label' => 'Contract Create', 'icon' => 'M12 4v16m8-8H4', 'permission' => 'contracts_create'],
            ['path' => $appendWorkspaceParam('/contract_templates.php'), 'label' => 'Contract Templates', 'icon' => 'M4 5a1 1 0 011-1h14a1 1 0 011 1v2a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM4 13a1 1 0 011-1h6a1 1 0 011 1v6a1 1 0 01-1 1H5a1 1 0 01-1-1v-6zM16 13a1 1 0 011-1h2a1 1 0 011 1v6a1 1 0 01-1 1h-2a1 1 0 01-1-1v-6z', 'permission' => 'templates_manage'],
            ['path' => $appendWorkspaceParam('/contract_modules.php'), 'label' => 'Contract Modules', 'icon' => 'M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10', 'permission' => 'templates_manage'],
        ]],
        ['path' => $appendWorkspaceParam('/invoices.php'), 'label' => 'Invoicing', 'icon' => 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z', 'permission' => 'invoices_view', 'dropdown' => [
            ['path' => $appendWorkspaceParam('/invoices.php'), 'label' => 'View All Invoices', 'icon' => 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z', 'permission' => 'invoices_view'],
            ['path' => $appendWorkspaceParam('/invoice_create.php'), 'label' => 'Create Invoice', 'icon' => 'M12 4v16m8-8H4', 'permission' => 'invoices_create'],
            ['path' => $appendWorkspaceParam('/invoice_items.php'), 'label' => 'Items', 'icon' => 'M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4', 'permission' => 'invoices_edit'],
            ['path' => $appendWorkspaceParam('/invoice_settings.php'), 'label' => 'Invoice Settings', 'icon' => 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z', 'permission' => 'invoices_edit'],
        ]],
        ['path' => $appendWorkspaceParam('/projects.php'), 'label' => 'Projects', 'icon' => 'M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z', 'permission' => 'projects_view'],
        ['path' => '#', 'label' => 'New', 'icon' => 'M12 4v16m8-8H4', 'dropdown' => [
            ['path' => $appendWorkspaceParam('/generate.php'), 'label' => 'New Proposal', 'icon' => 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2', 'permission' => 'proposals_create'],
            ['path' => $appendWorkspaceParam('/contract_create.php'), 'label' => 'New Contract', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'permission' => 'contracts_create'],
            ['path' => $appendWorkspaceParam('/invoice_create.php'), 'label' => 'New Invoice', 'icon' => 'M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z', 'permission' => 'invoices_create'],
            ['path' => $appendWorkspaceParam('/clients.php'), 'label' => 'New Client', 'icon' => 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z', 'permission' => 'clients_create'],
        ]],
    ];

    // Filter nav items based on permissions
    $filterNavItems = function(array $items) use ($hasPermission): array {
        $filtered = [];
        foreach ($items as $item) {
            // Check if item has permission requirement
            if (isset($item['permission']) && !$hasPermission($item['permission'])) {
                continue; // Skip this item
            }

            // If item has dropdown, filter dropdown items too
            if (isset($item['dropdown'])) {
                $filteredDropdown = [];
                foreach ($item['dropdown'] as $dropdownItem) {
                    // Skip separators
                    if ($dropdownItem['path'] === '-') {
                        $filteredDropdown[] = $dropdownItem;
                        continue;
                    }
                    // Check permission
                    if (isset($dropdownItem['permission']) && !$hasPermission($dropdownItem['permission'])) {
                        continue;
                    }
                    $filteredDropdown[] = $dropdownItem;
                }

                // Remove consecutive separators and leading/trailing separators
                $cleanDropdown = [];
                $lastWasSeparator = true;
                foreach ($filteredDropdown as $dropdownItem) {
                    if ($dropdownItem['path'] === '-') {
                        if (!$lastWasSeparator) {
                            $cleanDropdown[] = $dropdownItem;
                            $lastWasSeparator = true;
                        }
                    } else {
                        $cleanDropdown[] = $dropdownItem;
                        $lastWasSeparator = false;
                    }
                }
                // Remove trailing separator
                if (!empty($cleanDropdown) && end($cleanDropdown)['path'] === '-') {
                    array_pop($cleanDropdown);
                }

                // Only include dropdown if it has items
                if (!empty($cleanDropdown)) {
                    $item['dropdown'] = $cleanDropdown;
                    $filtered[] = $item;
                }
            } else {
                $filtered[] = $item;
            }
        }
        return $filtered;
    };

    $navItems = $filterNavItems($allNavItems);

    // Get user companies for workspace switcher
    $userCompanies = [];
    if ($user) {
        try {
            $pdo = getPDO();

            $primaryCompany = null;
            if ($user['company_id']) {
                $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ?');
                $stmt->execute([$user['company_id']]);
                $primaryCompany = $stmt->fetch();
            }

            $stmt = $pdo->prepare('
                SELECT c.* FROM companies c
                JOIN user_company_access uca ON c.id = uca.company_id
                WHERE uca.user_id = ? AND c.id != ?
                ORDER BY c.name ASC
            ');
            $stmt->execute([$user['id'], $user['company_id'] ?? 0]);
            $grantedCompanies = $stmt->fetchAll() ?: [];

            if ($primaryCompany) {
                array_unshift($userCompanies, $primaryCompany);
            }
            $userCompanies = array_merge($userCompanies, $grantedCompanies);
        } catch (Exception $e) {
            if ($company) {
                $userCompanies = [$company];
            }
        }
    }
?>

<style>
    /* Notion-inspired Navigation - Compact */
    .nav-item {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 6px;
        border-radius: 3px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.6);
        background: transparent;
        border: none;
        cursor: pointer;
        transition: background 0.1s ease;
        text-align: left;
    }
    
    .nav-item:hover {
        background: rgba(255, 255, 255, 0.05);
        color: rgba(255, 255, 255, 0.85);
    }
    
    .nav-item.active {
        background: rgba(255, 255, 255, 0.07);
        color: #fff;
    }
    
    .nav-item svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
        opacity: 0.55;
    }
    
    .nav-item:hover svg,
    .nav-item.active svg {
        opacity: 0.85;
    }
    
    .nav-item .chevron {
        width: 8px;
        height: 8px;
        margin-left: auto;
        opacity: 0.4;
        transition: transform 0.12s ease;
    }
    
    .nav-item .chevron.open {
        transform: rotate(90deg);
    }
    
    /* Submenu with line indicator */
    .nav-submenu {
        position: relative;
        margin-left: 10px;
        padding-left: 10px;
        margin-top: 1px;
        padding-bottom: 1px;
    }
    
    .nav-submenu::before {
        content: '';
        position: absolute;
        left: 0;
        top: 2px;
        bottom: 2px;
        width: 1px;
        background: rgba(255, 255, 255, 0.08);
    }
    
    .nav-submenu-item {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 8px;
        border-radius: 3px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.55);
        background: transparent;
        transition: background 0.1s ease, color 0.1s ease;
    }
    
    .nav-submenu-item:hover {
        background: rgba(255, 255, 255, 0.05);
        color: rgba(255, 255, 255, 0.85);
    }
    
    /* Light mode */
    [data-theme='light'] #app-sidebar {
        background: #fbfbfa !important;
    }
    
    [data-theme='light'] .nav-item {
        color: rgba(55, 53, 47, 0.6);
    }
    
    [data-theme='light'] .nav-item:hover {
        background: rgba(0, 0, 0, 0.03);
        color: rgb(55, 53, 47);
    }
    
    [data-theme='light'] .nav-item.active {
        background: rgba(0, 0, 0, 0.05);
        color: rgb(55, 53, 47);
    }
    
    [data-theme='light'] .nav-submenu::before {
        background: rgba(0, 0, 0, 0.08);
    }
    
    [data-theme='light'] .nav-submenu-item {
        color: rgba(55, 53, 47, 0.5);
    }
    
    [data-theme='light'] .nav-submenu-item:hover {
        background: rgba(0, 0, 0, 0.03);
        color: rgb(55, 53, 47);
    }
    
    /* Footer buttons */
    .nav-footer-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 6px;
        border-radius: 3px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.55);
        background: transparent;
        border: none;
        cursor: pointer;
        transition: background 0.1s ease;
        text-align: left;
    }
    
    .nav-footer-btn:hover {
        background: rgba(255, 255, 255, 0.05);
        color: rgba(255, 255, 255, 0.85);
    }
    
    .nav-footer-btn svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
        opacity: 0.55;
    }
    
    [data-theme='light'] .nav-footer-btn {
        color: rgba(55, 53, 47, 0.55);
    }
    
    [data-theme='light'] .nav-footer-btn:hover {
        background: rgba(0, 0, 0, 0.03);
        color: rgb(55, 53, 47);
    }
    
    /* Avatars */
    .nav-avatar {
        width: 18px;
        height: 18px;
        border-radius: 3px;
        background: rgba(255, 255, 255, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 9px;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.75);
        flex-shrink: 0;
    }
    
    [data-theme='light'] .nav-avatar {
        background: rgba(0, 0, 0, 0.06);
        color: rgb(55, 53, 47);
    }
    
    .nav-workspace-icon {
        width: 16px;
        height: 16px;
        border-radius: 3px;
        background: rgba(255, 255, 255, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 8px;
        font-weight: 600;
        color: rgba(255, 255, 255, 0.75);
        flex-shrink: 0;
    }
    
    [data-theme='light'] .nav-workspace-icon {
        background: rgba(0, 0, 0, 0.06);
        color: rgb(55, 53, 47);
    }
    
    /* Dropdown menus */
    .nav-dropdown-menu {
        background: #252525;
        border-radius: 4px;
        padding: 3px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.25);
    }
    
    [data-theme='light'] .nav-dropdown-menu {
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.12);
        border: 1px solid rgba(0,0,0,0.06);
    }
    
    [data-theme='light'] #workspace-menu,
    [data-theme='light'] #user-menu {
        background: #fff !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        border: 1px solid rgba(0,0,0,0.06);
    }
    
    /* Separators */
    .nav-separator {
        height: 1px;
        background: rgba(255, 255, 255, 0.08);
        margin: 4px 0;
    }
    
    [data-theme='light'] .nav-separator {
        background: rgba(55, 53, 47, 0.12);
    }
    
    /* Primary action button - Black like Notion */
    .nav-btn-primary {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 6px;
        border-radius: 3px;
        font-size: 12px;
        font-weight: 500;
        color: #fff;
        background: #37352f;
        border: none;
        cursor: pointer;
        transition: background 0.1s ease;
        text-align: left;
    }
    
    .nav-btn-primary:hover {
        background: #2f2e2b;
    }
    
    .nav-btn-primary svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
    }
    
    [data-theme='light'] .nav-btn-primary {
        background: #37352f;
        color: #fff;
    }
    
    [data-theme='light'] .nav-btn-primary:hover {
        background: #2f2e2b;
    }
    
    /* Danger button */
    .nav-btn-danger {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 6px;
        border-radius: 3px;
        font-size: 12px;
        color: #eb5757;
        background: transparent;
        border: none;
        cursor: pointer;
        transition: background 0.1s ease;
        text-align: left;
    }
    
    .nav-btn-danger:hover {
        background: rgba(235, 87, 87, 0.08);
    }
    
    .nav-btn-danger svg {
        width: 14px;
        height: 14px;
        flex-shrink: 0;
    }
    
    /* Workspace switcher at top */
    .nav-workspace-trigger {
        display: flex;
        align-items: center;
        gap: 6px;
        width: 100%;
        padding: 4px 6px;
        border-radius: 3px;
        font-size: 12px;
        color: rgba(255, 255, 255, 0.8);
        background: transparent;
        border: none;
        cursor: pointer;
        transition: background 0.1s ease;
        text-align: left;
    }
    
    .nav-workspace-trigger:hover {
        background: rgba(255, 255, 255, 0.05);
    }
    
    [data-theme='light'] .nav-workspace-trigger {
        color: rgb(55, 53, 47);
    }
    
    [data-theme='light'] .nav-workspace-trigger:hover {
        background: rgba(0, 0, 0, 0.03);
    }
</style>

<!-- Notion-inspired sidebar navigation -->
<aside id="app-sidebar" class="fixed left-0 top-0 z-40 h-screen w-56 flex flex-col transform transition-transform duration-200 ease-out md:translate-x-0 -translate-x-full" style="background: #191919;">
    <!-- Header with workspace switcher -->
    <div class="px-2 pt-2 pb-1">
        <div class="relative">
            <button type="button" onclick="toggleWorkspaceMenu()" class="nav-workspace-trigger w-full">
                <div class="nav-workspace-icon"><?php echo strtoupper(substr($company['name'] ?? 'W', 0, 1)); ?></div>
                <span class="flex-1 text-left truncate"><?php echo htmlspecialchars($company['name'] ?? 'Workspace'); ?></span>
                <svg class="chevron" id="workspace-menu-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width:8px;height:8px;opacity:0.4;">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
            </button>
            
            <!-- Workspace dropdown (opens downward) -->
            <div id="workspace-menu" class="hidden absolute left-0 right-0 top-full mt-1 rounded-md p-1" style="background: #252525; z-index: 50; box-shadow: 0 2px 8px rgba(0,0,0,0.25);">
                <?php if (count($userCompanies) > 1): ?>
                    <?php foreach ($userCompanies as $userCompany): ?>
                        <?php if ($userCompany['id'] != ($company['id'] ?? 0)): ?>
                            <a href="/go-workspace.php?id=<?= $userCompany['id'] ?>" class="nav-footer-btn">
                                <div class="nav-workspace-icon"><?php echo strtoupper(substr($userCompany['name'], 0, 1)); ?></div>
                                <span class="truncate"><?php echo htmlspecialchars($userCompany['name']); ?></span>
                            </a>
                        <?php endif; ?>
                    <?php endforeach; ?>
                    <div class="nav-separator"></div>
                <?php endif; ?>
                <a href="<?php echo $appendWorkspaceParam('/settings.php'); ?>" class="nav-footer-btn">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path></svg>
                    <span>Settings</span>
                </a>
                <div class="nav-separator"></div>
                <a href="/workspace-plans.php" class="nav-btn-primary">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                    <span>Add Workspace</span>
                </a>
            </div>
        </div>
        
        <!-- Mobile close -->
        <button id="sidebar-close" class="md:hidden absolute top-2 right-2 p-1 rounded hover:bg-white/5">
            <svg class="w-4 h-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
        </button>
    </div>

    <!-- Navigation -->
    <nav class="flex-1 overflow-y-auto px-2">
        <div class="space-y-0.5">
            <?php foreach ($navItems as $item): ?>
                <?php if (isset($item['dropdown'])): ?>
                    <?php $isActiveParent = $item['label'] === $activePage; ?>
                    <div>
                        <button type="button" onclick="toggleDropdown('<?php echo htmlspecialchars($item['label']); ?>')" class="nav-item <?php echo $isActiveParent ? 'active' : ''; ?>">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="<?php echo $item['icon']; ?>"></path>
                            </svg>
                            <span class="flex-1 truncate"><?php echo htmlspecialchars($item['label']); ?></span>
                            <svg class="chevron" id="dropdown-icon-<?php echo htmlspecialchars($item['label']); ?>" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                            </svg>
                        </button>
                        <div id="dropdown-<?php echo htmlspecialchars($item['label']); ?>" class="nav-submenu hidden">
                            <?php foreach ($item['dropdown'] as $dropdownItem): ?>
                                <?php if ($dropdownItem['path'] !== '-'): ?>
                                    <a href="<?php echo $dropdownItem['path']; ?>" class="nav-submenu-item">
                                        <span><?php echo htmlspecialchars($dropdownItem['label']); ?></span>
                                    </a>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php else: ?>
                    <?php $isActive = $item['label'] === $activePage; ?>
                    <a href="<?php echo $item['path']; ?>" class="nav-item <?php echo $isActive ? 'active' : ''; ?>">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="<?php echo $item['icon']; ?>"></path>
                        </svg>
                        <span class="truncate"><?php echo htmlspecialchars($item['label']); ?></span>
                    </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    </nav>

    <!-- Footer -->
    <div class="p-2 space-y-0.5" style="border-top: 1px solid rgba(255,255,255,0.05);">
        <!-- Theme toggle -->
        <button type="button" onclick="toggleTheme()" id="theme-toggle" class="nav-footer-btn w-full">
            <svg id="theme-icon-dark" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display: block;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
            </svg>
            <svg id="theme-icon-light" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display: none;">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
            </svg>
            <span id="theme-label">Dark mode</span>
        </button>
        
        <!-- User menu -->
        <div class="relative">
            <button type="button" onclick="toggleUserMenu()" class="nav-footer-btn w-full">
                <div class="nav-avatar"><?php echo strtoupper(substr($user['name'] ?? 'U', 0, 1)); ?></div>
                <span class="flex-1 text-left truncate"><?php echo htmlspecialchars($user['name'] ?? 'User'); ?></span>
                <svg style="width:8px;height:8px;opacity:0.4;" id="user-menu-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"></path>
                </svg>
            </button>
            
            <!-- User dropdown (opens upward, close to trigger) -->
            <div id="user-menu" class="hidden absolute left-0 right-0 bottom-full mb-1 rounded-md p-1" style="background: #252525; z-index: 50; box-shadow: 0 2px 8px rgba(0,0,0,0.25);">
                <a href="<?php echo $appendWorkspaceParam('/profile.php'); ?>" class="nav-footer-btn">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                    <span>Profile</span>
                </a>
                <a href="<?php echo $appendWorkspaceParam('/billing.php'); ?>" class="nav-footer-btn">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path></svg>
                    <span>Billing</span>
                </a>
                <div class="nav-separator"></div>
                <a href="/logout.php" class="nav-btn-danger">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path></svg>
                    <span>Sign out</span>
                </a>
            </div>
        </div>
    </div>
</aside>

<!-- Mobile overlay -->
<div id="sidebar-overlay" class="fixed inset-0 z-30 hidden bg-black bg-opacity-50 md:hidden"></div>

<script>
// Theme management (shared across pages)
(function() {
    const THEME_STORAGE_KEY = 'theme';
    const html = document.documentElement;

    function updateNavThemeControls(theme) {
        const darkIcon = document.getElementById('theme-icon-dark');
        const lightIcon = document.getElementById('theme-icon-light');
        const label = document.getElementById('theme-label');
        const darkLogo = document.getElementById('nav-logo-dark');
        const lightLogo = document.getElementById('nav-logo-light');

        const controlsReady = darkIcon && lightIcon && label;
        if (controlsReady) {
            if (theme === 'light') {
                darkIcon.style.display = 'none';
                lightIcon.style.display = 'block';
                label.textContent = 'Light Mode';
            } else {
                darkIcon.style.display = 'block';
                lightIcon.style.display = 'none';
                label.textContent = 'Dark Mode';
            }
        }

        if (darkLogo && lightLogo) {
            if (theme === 'light') {
                darkLogo.style.display = 'none';
                lightLogo.style.display = 'block';
            } else {
                darkLogo.style.display = 'block';
                lightLogo.style.display = 'none';
            }
        }
    }

    function setTheme(theme, { emit = true, persist = true } = {}) {
        const nextTheme = theme === 'light' ? 'light' : 'dark';
        html.setAttribute('data-theme', nextTheme);
        if (persist) {
            localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
        }
        updateNavThemeControls(nextTheme);
        if (emit) {
            window.dispatchEvent(new CustomEvent('themechange', { detail: nextTheme }));
        }
    }

    window.toggleTheme = function() {
        const current = html.getAttribute('data-theme') || localStorage.getItem(THEME_STORAGE_KEY) || 'dark';
        const next = current === 'dark' ? 'light' : 'dark';
        setTheme(next);
    };

    window.__setTheme = function(theme) {
        setTheme(theme);
    };

    const savedTheme = localStorage.getItem(THEME_STORAGE_KEY) || 'dark';
    setTheme(savedTheme, { emit: false });
    window.dispatchEvent(new CustomEvent('themechange', { detail: savedTheme }));

    document.addEventListener('DOMContentLoaded', function() {
        updateNavThemeControls(savedTheme);
    });

    window.addEventListener('themechange', function(event) {
        if (event.detail) {
            updateNavThemeControls(event.detail);
        }
    });
})();

// Sidebar toggles and overlays
document.addEventListener('DOMContentLoaded', function() {
    const sidebar = document.getElementById('app-sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    const closeBtn = document.getElementById('sidebar-close');

    function openSidebar() {
        if (!sidebar || !overlay) return;
        sidebar.classList.remove('-translate-x-full');
        overlay.classList.remove('hidden');
    }

    function closeSidebar() {
        if (!sidebar || !overlay) return;
        sidebar.classList.add('-translate-x-full');
        overlay.classList.add('hidden');
    }

    if (overlay) {
        overlay.addEventListener('click', closeSidebar);
    }

    if (closeBtn) {
        closeBtn.addEventListener('click', closeSidebar);
    }

    window.openAppSidebar = openSidebar;
});

// Dropdown toggle functionality
function toggleDropdown(label) {
    const dropdown = document.getElementById('dropdown-' + label);
    const icon = document.getElementById('dropdown-icon-' + label);

    if (dropdown.classList.contains('hidden')) {
        dropdown.classList.remove('hidden');
        icon.style.transform = 'rotate(180deg)';
    } else {
        dropdown.classList.add('hidden');
        icon.style.transform = 'rotate(0deg)';
    }
}

// Theme toggle - COMPLETE REBUILD
function toggleTheme() {
    console.log('Toggle theme called');
    const html = document.documentElement;
    const currentTheme = html.getAttribute('data-theme') || 'dark';
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    
    console.log('Current theme:', currentTheme, 'New theme:', newTheme);
    
    // Update HTML attribute
    html.setAttribute('data-theme', newTheme);
    
    // Update UI
    const darkIcon = document.getElementById('theme-icon-dark');
    const lightIcon = document.getElementById('theme-icon-light');
    const label = document.getElementById('theme-label');
    
    console.log('Icons found:', !!darkIcon, !!lightIcon, !!label);
    
    if (newTheme === 'light') {
        if (darkIcon) darkIcon.style.display = 'none';
        if (lightIcon) lightIcon.style.display = 'block';
        if (label) label.textContent = 'Light Mode';
    } else {
        if (darkIcon) darkIcon.style.display = 'block';
        if (lightIcon) lightIcon.style.display = 'none';
        if (label) label.textContent = 'Dark Mode';
    }
    
    // Save preference
    localStorage.setItem('theme', newTheme);
    console.log('Theme saved:', newTheme);
}

// Initialize IMMEDIATELY - no DOMContentLoaded wait
(function() {
    const savedTheme = localStorage.getItem('theme') || 'dark';
    const html = document.documentElement;
    html.setAttribute('data-theme', savedTheme);
    
    console.log('Initial theme set to:', savedTheme);
    
    // Update UI immediately
    setTimeout(function() {
        const darkIcon = document.getElementById('theme-icon-dark');
        const lightIcon = document.getElementById('theme-icon-light');
        const label = document.getElementById('theme-label');
        
        console.log('Delayed update - Icons found:', !!darkIcon, !!lightIcon, !!label);
        
        if (savedTheme === 'light') {
            if (darkIcon) darkIcon.style.display = 'none';
            if (lightIcon) lightIcon.style.display = 'block';
            if (label) label.textContent = 'Light Mode';
        } else {
            if (darkIcon) darkIcon.style.display = 'block';
            if (lightIcon) lightIcon.style.display = 'none';
            if (label) label.textContent = 'Dark Mode';
        }
    }, 100);
})();

// Workspace menu toggle
function toggleWorkspaceMenu() {
    const menu = document.getElementById('workspace-menu');
    const icon = document.getElementById('workspace-menu-icon');

    if (menu.classList.contains('hidden')) {
        menu.classList.remove('hidden');
        icon.style.transform = 'rotate(180deg)';
    } else {
        menu.classList.add('hidden');
        icon.style.transform = 'rotate(0deg)';
    }
}

// User menu toggle
function toggleUserMenu() {
    const menu = document.getElementById('user-menu');
    const icon = document.getElementById('user-menu-icon');

    if (menu.classList.contains('hidden')) {
        menu.classList.remove('hidden');
        icon.style.transform = 'rotate(180deg)';
    } else {
        menu.classList.add('hidden');
        icon.style.transform = 'rotate(0deg)';
    }
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(event) {
    // Close workspace menu
    const workspaceMenu = document.getElementById('workspace-menu');
    if (workspaceMenu && !workspaceMenu.contains(event.target) && !event.target.closest('button[onclick*="toggleWorkspaceMenu"]')) {
        if (!workspaceMenu.classList.contains('hidden')) {
            workspaceMenu.classList.add('hidden');
            const workspaceIcon = document.getElementById('workspace-menu-icon');
            if (workspaceIcon) {
                workspaceIcon.style.transform = 'rotate(0deg)';
                workspaceIcon.style.opacity = '1';
                workspaceIcon.style.visibility = 'visible';
            }
        }
    }

    // Close user menu
    const userMenu = document.getElementById('user-menu');
    if (userMenu && !userMenu.contains(event.target) && !event.target.closest('button[onclick*="toggleUserMenu"]')) {
        if (!userMenu.classList.contains('hidden')) {
            userMenu.classList.add('hidden');
            const userIcon = document.getElementById('user-menu-icon');
            if (userIcon) {
                userIcon.style.transform = 'rotate(0deg)';
                userIcon.style.opacity = '1';
                userIcon.style.visibility = 'visible';
            }
        }
    }

    // Close navigation dropdowns
    const dropdowns = document.querySelectorAll('ul[id^="dropdown-"]');
    dropdowns.forEach(dropdown => {
        if (!dropdown.contains(event.target) && !event.target.closest('button[onclick*="toggleDropdown"]')) {
            if (!dropdown.classList.contains('hidden')) {
                dropdown.classList.add('hidden');
                const label = dropdown.id.replace('dropdown-', '');
                const icon = document.getElementById('dropdown-icon-' + label);
                if (icon) {
                    icon.style.transform = 'rotate(0deg)';
                    icon.style.opacity = '1';
                    icon.style.visibility = 'visible';
                }
            }
        }
    });
});
</script>

<?php
}
?>
