<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?= $_SESSION[CSRF_TOKEN_NAME] ?? '' ?>">
    <title><?= htmlspecialchars($pageTitle ?? 'Helmyx') ?> — Helmyx</title>
    <link rel="icon" type="image/png" sizes="32x32" href="<?= APP_URL ?>/assets/brand/favicon/helmyx-icon-32.png">

    <!-- Fonts: Montserrat (display/headings) + Inter (interface/body) — per brand guide -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600;700&family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <!-- Bootstrap 5 (used by dashboard/finance/notifications views) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">

    <!-- Tailwind (used by users/clients/contractors/suppliers/projects/reports views) -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            corePlugins: { preflight: false }
        };
    </script>

    <!-- Helmyx brand tokens (colours, type, shape — single source of truth, also used by the marketing site) -->
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/hx-tokens.css">

    <!-- Main CSS (loaded last so the app's own component classes win over Bootstrap's same-named ones) -->
    <!-- ?v=filemtime busts the browser cache automatically whenever this file changes on disk. -->
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/style.css?v=<?= @filemtime(ROOT_PATH . '/assets/css/style.css') ?: APP_VERSION ?>">
</head>
<?php
$__trialUser = \Core\Auth::user();
$__showTrialBanner = ($__trialUser['subscription_status'] ?? null) === 'trial'
    && !empty($__trialUser['trial_ends_at'])
    && !\Core\Auth::isContractorUser()
    && !\Core\Auth::isSupplierUser();
?>
<body class="app-body<?= $__showTrialBanner ? ' has-trial-banner' : '' ?>">
    <!-- Toast Container -->
    <div class="toast-container" id="toastContainer"></div>

    <?php if ($__showTrialBanner): $__trialEndIso = date('c', strtotime($__trialUser['trial_ends_at'])); ?>
    <div class="trial-banner" id="trialBanner" data-trial-end="<?= htmlspecialchars($__trialEndIso) ?>">
        <span id="trialBannerText">Loading your trial status…</span>
        <a href="<?= APP_URL ?>/billing/pay" class="trial-banner-cta">Upgrade now</a>
    </div>
    <?php endif; ?>

    <div class="app-wrapper">
        <!-- SIDEBAR -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-logo">
                <div class="logo-icon"><img src="<?= APP_URL ?>/assets/brand/logo/helmyx-icon-gradient.svg" alt=""></div>
                <div class="logo-text"><img src="<?= APP_URL ?>/assets/brand/logo/helmyx-wordmark-white.svg" alt="Helmyx"></div>
            </div>
            
            <nav class="sidebar-nav">
                <?php
                $user = \Core\Auth::user();
                $userRole = $user['entity_type'] ?? 'org_user';
                $isSuperAdmin = \Core\Auth::isSuperAdmin();
                $isContractor = \Core\Auth::isContractorUser();
                $isSupplier = \Core\Auth::isSupplierUser();

                if ($isSuperAdmin) {
                    $pendingOrgCount = (int) \Database::getInstance()
                        ->query("SELECT COUNT(*) FROM organizations WHERE status = 'pending'")
                        ->fetchColumn();
                    $navGroups = [
                        'Overview' => [
                            ['icon' => 'fa-chart-pie', 'label' => 'Dashboard', 'url' => '/dashboard/admin', 'badge' => '']
                        ],
                        'Platform' => [
                            ['icon' => 'fa-building', 'label' => 'Organizations', 'url' => '/admin/organizations', 'badge' => $pendingOrgCount > 0 ? (string)$pendingOrgCount : ''],
                            ['icon' => 'fa-tags', 'label' => 'Subscription Plans', 'url' => '/admin/plans', 'badge' => ''],
                            ['icon' => 'fa-file-invoice-dollar', 'label' => 'Platform Charges', 'url' => '/settings/billing', 'badge' => '']
                        ],
                        'System' => [
                            ['icon' => 'fa-users', 'label' => 'All Users', 'url' => '/users', 'badge' => ''],
                            ['icon' => 'fa-history', 'label' => 'Audit Log', 'url' => '/settings/audit', 'badge' => ''],
                            ['icon' => 'fa-sliders-h', 'label' => 'System Settings', 'url' => '/admin/system', 'badge' => '']
                        ]
                    ];
                } elseif ($isContractor) {
                    $navGroups = [
                        'Portal' => [
                            ['icon' => 'fa-home', 'label' => 'Dashboard', 'url' => '/dashboard', 'badge' => ''],
                            ['icon' => 'fa-briefcase', 'label' => 'My Projects', 'url' => '/projects', 'badge' => '']
                        ],
                        'Work & Progress' => [
                            ['icon' => 'fa-clipboard-check', 'label' => 'Daily Reports', 'url' => '/reports/daily', 'badge' => ''],
                            ['icon' => 'fa-file-invoice', 'label' => 'My Invoices', 'url' => '/finance/invoices', 'badge' => '']
                        ],
                        'Account' => [
                            ['icon' => 'fa-user-cog', 'label' => 'Profile & Security', 'url' => '/profile', 'badge' => '']
                        ]
                    ];
                } elseif ($isSupplier) {
                    $navGroups = [
                        'Portal' => [
                            ['icon' => 'fa-home', 'label' => 'Dashboard', 'url' => '/dashboard', 'badge' => '']
                        ],
                        'Work' => [
                            ['icon' => 'fa-file-invoice', 'label' => 'My Invoices', 'url' => '/finance/invoices', 'badge' => '']
                        ],
                        'Account' => [
                            ['icon' => 'fa-user-cog', 'label' => 'Profile & Security', 'url' => '/profile', 'badge' => '']
                        ]
                    ];
                } else {
                    $navGroups = [
                        'Overview' => [
                            ['icon' => 'fa-home', 'label' => 'Dashboard', 'url' => '/dashboard', 'badge' => '']
                        ],
                        'Management' => [
                            ['icon' => 'fa-briefcase', 'label' => 'Projects', 'url' => '/projects', 'badge' => ''],
                            ['icon' => 'fa-tags', 'label' => 'Project Categories', 'url' => '/projects/categories', 'badge' => ''],
                            ['icon' => 'fa-user-tie', 'label' => 'Clients', 'url' => '/clients', 'badge' => ''],
                            ['icon' => 'fa-hard-hat', 'label' => 'Contractors', 'url' => '/contractors', 'badge' => ''],
                            ['icon' => 'fa-truck', 'label' => 'Suppliers', 'url' => '/suppliers', 'badge' => '']
                        ],
                        'Finance' => [
                            ['icon' => 'fa-file-invoice-dollar', 'label' => 'Invoices', 'url' => '/finance/invoices', 'badge' => ''],
                            ['icon' => 'fa-calculator', 'label' => 'Expenses', 'url' => '/finance/expenses', 'badge' => ''],
                            ['icon' => 'fa-credit-card', 'label' => 'Billing Fees', 'url' => '/finance/billing', 'badge' => '']
                        ],
                        'Reports & Quality' => [
                            ['icon' => 'fa-clipboard-list', 'label' => 'Daily Reports', 'url' => '/reports/daily', 'badge' => ''],
                            ['icon' => 'fa-layer-group', 'label' => 'Report Templates', 'url' => '/reports/templates', 'badge' => '']
                        ],
                        'Administration' => [
                            ['icon' => 'fa-users', 'label' => 'Users & Roles', 'url' => '/users', 'badge' => ''],
                            ['icon' => 'fa-cog', 'label' => 'Settings', 'url' => '/settings', 'badge' => '']
                        ]
                    ];
                }
                
                $rawUri = $_SERVER['REQUEST_URI'] ?? '/';
                
                foreach ($navGroups as $group => $items):
                ?>
                    <div class="nav-section-title"><?= htmlspecialchars($group) ?></div>
                    <?php foreach ($items as $item): 
                        $fullUrl = APP_URL . $item['url'];
                        $isActive = (stripos($rawUri, $item['url']) !== false && $item['url'] !== '/') ? 'active' : '';
                        if ($item['url'] === '/dashboard' && ($rawUri === parse_url(APP_URL, PHP_URL_PATH) . '/dashboard' || $rawUri === parse_url(APP_URL, PHP_URL_PATH) . '/')) {
                            $isActive = 'active';
                        }
                    ?>
                        <a href="<?= $fullUrl ?>" class="nav-item <?= $isActive ?>">
                            <i class="fas <?= $item['icon'] ?> nav-icon"></i>
                            <span class="nav-text"><?= htmlspecialchars($item['label']) ?></span>
                            <?php if (!empty($item['badge'])): ?>
                                <span class="nav-badge"><?= htmlspecialchars($item['badge']) ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </nav>

            <?php
            $firstName = $user['first_name'] ?? 'User';
            $lastName  = $user['last_name'] ?? '';
            $initials  = strtoupper(substr($firstName, 0, 1) . substr($lastName, 0, 1));
            $roleLabel = ucfirst(str_replace('_', ' ', $user['entity_type'] ?? 'User'));
            ?>
            <div class="sidebar-user" style="padding:16px 24px;border-top:1px solid rgba(255,255,255,0.1);display:flex;align-items:center;gap:12px;margin-top:auto;">
                <div class="avatar avatar-sm"><?= htmlspecialchars($initials ?: 'U') ?></div>
                <div class="user-info" style="display:flex;flex-direction:column;overflow:hidden;">
                    <span class="user-name" style="color:white;font-weight:600;font-size:0.85rem;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;"><?= htmlspecialchars($firstName . ' ' . $lastName) ?></span>
                    <span class="user-role" style="color:var(--sidebar-text);font-size:0.75rem;"><?= htmlspecialchars($roleLabel) ?></span>
                </div>
            </div>
        </aside>

        <!-- MAIN CONTENT -->
        <div class="main-wrapper" id="mainWrapper">
            <!-- TOPBAR -->
            <header class="topbar">
                <div class="topbar-left">
                    <button class="sidebar-toggle" id="sidebarToggle" type="button">
                        <i class="fas fa-bars"></i>
                    </button>
                    
                    <div class="breadcrumb">
                        <a href="<?= APP_URL ?>/dashboard">Home</a>
                        <?php if(isset($breadcrumb) && is_array($breadcrumb)): ?>
                            <?php foreach($breadcrumb as $crumb): ?>
                                <i class="fas fa-chevron-right separator"></i>
                                <?php if(!empty($crumb['url'])): ?>
                                    <a href="<?= htmlspecialchars($crumb['url']) ?>"><?= htmlspecialchars($crumb['label']) ?></a>
                                <?php else: ?>
                                    <span><?= htmlspecialchars($crumb['label']) ?></span>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="topbar-right">
                    <div class="search-box">
                        <i class="fas fa-search search-icon"></i>
                        <input type="text" placeholder="Search projects...">
                    </div>
                    
                    <a href="<?= APP_URL ?>/notifications" class="notif-bell" style="text-decoration:none;color:inherit;">
                        <i class="far fa-bell"></i>
                        <span class="notif-badge" id="notifBadge" style="display:none;">0</span>
                    </a>
                    
                    <div class="user-menu" id="userMenuToggle" data-dropdown="topUserDropdown">
                        <div class="user-avatar"><?= htmlspecialchars($initials ?: 'U') ?></div>
                        <span class="text-sm fw-500 hidden md:block" style="margin-left:6px;"><?= htmlspecialchars($firstName) ?></span>
                        <i class="fas fa-chevron-down text-xs text-muted" style="margin-left:4px;"></i>
                        
                        <div class="dropdown-menu user-dropdown" id="topUserDropdown" style="margin-top:8px;padding:8px 0;min-width:180px;">
                            <a href="<?= APP_URL ?>/profile" class="dropdown-item" style="display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-primary);text-decoration:none;font-size:0.875rem;"><i class="far fa-user"></i> My Profile</a>
                            <a href="<?= APP_URL ?>/settings" class="dropdown-item" style="display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-primary);text-decoration:none;font-size:0.875rem;"><i class="fas fa-cog"></i> Settings</a>
                            <a href="<?= APP_URL ?>/settings/security" class="dropdown-item" style="display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--text-primary);text-decoration:none;font-size:0.875rem;"><i class="fas fa-shield-alt"></i> Security & 2FA</a>
                            <div style="height:1px;background:var(--border-color);margin:6px 0;"></div>
                            <a href="<?= APP_URL ?>/logout" class="dropdown-item text-danger" style="display:flex;align-items:center;gap:8px;padding:8px 16px;color:var(--danger);text-decoration:none;font-size:0.875rem;"><i class="fas fa-sign-out-alt"></i> Logout</a>
                        </div>
                    </div>
                </div>
            </header>
            
            <!-- PAGE CONTENT -->
            <main class="page-content">
                <?php include __DIR__ . '/../partials/flash.php'; ?>
                
                <?= $content ?? '' ?>
            </main>
        </div>
    </div>

    <!-- Confirm Modal -->
    <div class="modal-overlay hidden" id="confirm-modal">
        <div class="modal modal-sm">
            <div class="modal-header">
                <h3 class="modal-title">Confirm Action</h3>
                <button class="modal-close" type="button" onclick="closeModal('confirm-modal')"><i class="fas fa-times"></i></button>
            </div>
            <div class="modal-body">
                <p id="confirm-message">Are you sure you want to proceed?</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" onclick="closeModal('confirm-modal')">Cancel</button>
                <button class="btn btn-primary" type="button" id="confirm-btn-yes">Yes, Proceed</button>
            </div>
        </div>
    </div>

    <!-- Bootstrap 5 JS (modals/tabs used by dashboard/finance views) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Main JS -->
    <script src="<?= APP_URL ?>/assets/js/main.js?v=<?= @filemtime(ROOT_PATH . '/assets/js/main.js') ?: APP_VERSION ?>"></script>

    <script>
    (function initIdleTimeout() {
        // Keep IDLE_LIMIT_MS in sync with IDLE_TIMEOUT_SECONDS in config/config.php.
        // This is the real "5 minutes of inactivity" enforcement — it tracks actual
        // mouse/keyboard/touch input, unlike the server-side check (a coarser
        // backstop for when JS is unavailable, which also counts background
        // AJAX polling as "activity").
        const IDLE_LIMIT_MS = 5 * 60 * 1000;
        const WARN_AT_MS = 30 * 1000; // show a heads-up toast with this much time left
        let lastActivity = Date.now();
        let warned = false;

        ['mousemove', 'mousedown', 'keydown', 'scroll', 'touchstart'].forEach(evt => {
            document.addEventListener(evt, () => {
                lastActivity = Date.now();
                warned = false;
            }, { passive: true });
        });

        setInterval(() => {
            const remaining = IDLE_LIMIT_MS - (Date.now() - lastActivity);

            if (remaining <= 0) {
                window.location.href = '<?= APP_URL ?>/logout?idle=1';
                return;
            }

            if (remaining <= WARN_AT_MS && !warned) {
                warned = true;
                if (typeof showToast === 'function') {
                    showToast('You will be logged out soon due to inactivity — move your mouse to stay signed in.', 'warning', WARN_AT_MS);
                }
            }
        }, 1000);
    })();
    </script>

    <?php if ($__showTrialBanner): ?>
    <script>
    (function initTrialCountdown() {
        const banner = document.getElementById('trialBanner');
        const text   = document.getElementById('trialBannerText');
        if (!banner || !text) return;

        const endTime = new Date(banner.dataset.trialEnd).getTime();

        function render() {
            const remaining = endTime - Date.now();

            if (remaining <= 0) {
                text.textContent = 'Your trial has ended — redirecting to payment…';
                banner.classList.add('trial-banner-urgent');
                clearInterval(timer);
                // The server enforces this on the next request regardless;
                // this just gets them there without waiting for a click.
                window.location.href = '<?= APP_URL ?>/billing/pay';
                return;
            }

            const totalSeconds = Math.floor(remaining / 1000);
            const days    = Math.floor(totalSeconds / 86400);
            const hours   = Math.floor((totalSeconds % 86400) / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;

            let parts;
            if (days > 0) {
                parts = `${days}d ${hours}h ${minutes}m`;
            } else if (hours > 0) {
                parts = `${hours}h ${minutes}m ${seconds}s`;
            } else {
                parts = `${minutes}m ${seconds}s`;
            }

            text.textContent = `Your free trial ends in ${parts} — upgrade to keep access.`;
            banner.classList.toggle('trial-banner-urgent', remaining <= 24 * 60 * 60 * 1000);
        }

        render();
        const timer = setInterval(render, 1000);
    })();
    </script>
    <?php endif; ?>
</body>
</html>
