<?php
// Authentication and session logic here if needed
if (!defined('AUTH_USER')) {
    // This should be set by auto-prepend or login logic
    header('Location: login.php');
    exit();
}

// Function to load server settings
function loadServerSettings() {
    $settings = [];
    if (file_exists('/docker/whp/settings.json')) {
        $settings = json_decode(file_get_contents('/docker/whp/settings.json'), true) ?: [];
    }
    return $settings;
}

// Load server settings
$server_settings = loadServerSettings();
$server_name = $server_settings['server_name'] ?? 'Web Hosting Panel';

// Check if user is a delegated user and get their permissions
$is_delegated_user = isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'delegated';
$delegated_permissions = [];
$delegated_display_name = '';

if ($is_delegated_user) {
    // Load delegated user permissions from session
    $delegated_permissions = $_SESSION['delegated_permissions'] ?? [];
    $delegated_display_name = $_SESSION['delegated_display_name'] ?? '';
}

// Function to check if delegated user has permission for a menu item
function canAccessPage($page, $is_delegated_user, $delegated_permissions) {
    if (!$is_delegated_user) {
        // Account type restrictions for system users
        $account_type = $_SESSION['account_type'] ?? 'full';
        if ($account_type === 'domain_dns') {
            return in_array($page, ['dashboard', 'domains']);
        }
        if ($account_type === 'mail_dns') {
            return in_array($page, ['dashboard', 'domains', 'email-management']);
        }
        return true; // 'full' can access everything
    }
    
    // Map pages to permission requirements
    $page_permissions = [
        'domains' => 'can_manage_domains',
        'sites' => 'can_manage_sites',
        'site-builder' => 'can_manage_sites',
        'database-management' => 'can_manage_databases',
        'postgresql-management' => 'can_manage_databases',
        'email-management' => 'can_manage_email',
        'backups' => 'can_manage_backups',
        'wordpress' => 'can_manage_wordpress',
        'terminal' => 'can_view_terminal',
        'filemanager' => 'can_manage_files', // For file manager links
        'phpmyadmin-sso' => 'can_manage_databases',
        'adminer-sso' => 'can_manage_databases',
    ];
    
    // Always allow dashboard, delegated-users, and active-sessions pages.
    // active-sessions only ever shows the caller's own sessions for non-root,
    // so every authenticated user (including delegated) can reach it to manage
    // their own logged-in devices.
    if (in_array($page, ['dashboard', 'delegated-users', 'active-sessions'])) {
        return true;
    }
    
    // Root-only pages (delegated users never have access)
    $root_only_pages = [
        'user-management', 'security-management', 'announcements-management',
        'update-management', 'docker-management', 'user-resources',
        'server-settings', 'cpanel-import', 'cpanel-import-results',
        'valkey-admin', 'disk-usage', 'container-boot', 'site-audit',
        'account-suspensions'
    ];
    
    if (in_array($page, $root_only_pages)) {
        return false;
    }
    
    // Check specific permission for page
    if (isset($page_permissions[$page])) {
        return !empty($delegated_permissions[$page_permissions[$page]]);
    }
    
    return true; // Default allow for unknown pages
}

// Whitelist of allowed pages
$allowed_pages = [
    'dashboard' => 'Dashboard',
    'database-management' => 'Database Management',
    'postgresql-management' => 'PostgreSQL Management',
    'email-management' => 'Email Management',
    'backups' => 'Backup Management',
    'account-valkey' => 'Valkey Cache',
    'valkey-admin'   => 'Valkey Admin',
    'wordpress' => 'WordPress Management',
    'cpanel-import' => 'cPanel Import',
    'cpanel-import-results' => 'cPanel Import Results',
    'user-management' => 'User Management',
    'delegated-users' => 'Delegated Users',
    'active-sessions' => 'Active Sessions',
    'security-management' => 'Security Management',
    'announcements-management' => 'Announcements Management',
    'update-management' => 'Update Management',
    'docker-management' => 'Docker Management',
    'user-resources' => 'User Resources',
    'domains' => 'Domains',
    'sites' => 'Sites',
    'site-builder' => 'Site Builder',
    'terminal' => 'Terminal',
    'server-settings' => 'Server Settings',
    'disk-usage' => 'Disk Usage',
    'ai-monitor' => 'AI Monitor',
    'ai-monitor-customer' => 'Site Monitoring',
    'ai-monitor-ignore-rules' => 'AI Monitor Ignore Rules',
    'coraza-rules' => 'Coraza Rules',
    'issues' => 'Issues',
    'site-traffic' => 'Site Traffic',
    'container-boot' => 'Container Boot & Health',
    'site-audit' => 'Site Disable Audit',
    'account-suspensions' => 'Account Suspensions',
];

$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';
if (!array_key_exists($page, $allowed_pages)) {
    $page = 'dashboard';
}

?>
<!DOCTYPE html>
<html lang="en" data-theme="<?php
    $theme_pref = $_SESSION['theme_preference'] ?? 'auto';
    // Convert 'auto' to actual theme based on time or just default to dark
    echo ($theme_pref === 'auto') ? 'dark' : htmlspecialchars($theme_pref);
?>">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <title><?php echo htmlspecialchars($allowed_pages[$page]) . ' - ' . htmlspecialchars($server_name); ?></title>

        <?php $whp_css_v = @file_exists('/etc/whp-version') ? trim(@file_get_contents('/etc/whp-version')) : '0'; ?>
        <!-- Bootstrap 5 -->
        <link href="bootstrap5/css/bootstrap.min.css" rel="stylesheet">
        <link href="css/bootstrap5-whp-theme.css?v=<?php echo htmlspecialchars($whp_css_v); ?>" type="text/css" rel="stylesheet">
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet">
        
        <!-- Optional: Keep only essential CSS -->
        <link href="css/waves.min.css" type="text/css" rel="stylesheet">
        <link href="css/morris-0.4.3.min.css" rel="stylesheet">
        <link href="css/fullcalendar.min.css" rel="stylesheet">
        <link href="js/c3/c3.min.css" rel="stylesheet">

        <!-- Additional theme CSS if needed -->
        <link href="css/themify-icons.css" rel="stylesheet">
        <link href="css/announcements.css" rel="stylesheet">
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body class="fixed-navbar fixed-sidebar<?php echo (isset($_SESSION['large_fonts']) && $_SESSION['large_fonts']) ? ' large-fonts' : ''; ?>">
        <!-- Static navbar -->
        <!-- Simple splash screen-->
        <div class="splash"><div class="splash-title"><div class="spinner">
                    <img src="images/loading-new.gif" alt=""/>
                </div> </div> </div>
        <!--[if lt IE 7]>
        <p class="alert alert-danger">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->


        <!-- Bootstrap 5 Navbar -->
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top" id="header">
            <div class="container-fluid">
                <!-- Sidebar Toggle Button -->
                <button class="btn btn-outline-light me-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
                    <i class="fa fa-bars"></i>
                </button>
                
                <!-- Brand -->
                <a class="navbar-brand" href="#">
                    <span class="brand-full"><?php echo htmlspecialchars($server_name); ?></span>
                    <span class="brand-short">WHP</span>
                </a>
                
                <!-- User Dropdown -->
                <div class="navbar-nav ms-auto">
                    <!-- Theme Toggle Button -->
                    <div class="font-size-toggle-wrapper">
                        <button id="themeToggleBtn"
                                class="btn btn-sm btn-outline-light me-2"
                                data-theme-pref="<?php echo htmlspecialchars($_SESSION['theme_preference'] ?? 'auto'); ?>"
                                title="Theme: Auto (follows system)"
                                aria-label="Toggle theme (Auto/Light/Dark)">
                            <i class="fa fa-adjust"></i>
                            <span id="themeLabel" class="ms-1">Auto</span>
                        </button>
                    </div>

                    <!-- Font Size Toggle Switch -->
                    <div class="font-size-toggle-wrapper font-size-toggle-wrapper--fontsize">
                        <label class="font-size-toggle-label" for="fontSizeToggle">
                            <span class="font-size-icons">
                                <span class="font-size-small">A</span>
                                <span class="font-size-large">A</span>
                            </span>
                            <div class="toggle-switch" title="Toggle larger font size for better readability">
                                <input type="checkbox" 
                                       id="fontSizeToggle" 
                                       <?php echo (isset($_SESSION['large_fonts']) && $_SESSION['large_fonts']) ? 'checked' : ''; ?>
                                       aria-label="Toggle larger font size"
                                       aria-describedby="fontSizeDescription"
                                       role="switch">
                                <span class="toggle-slider"></span>
                            </div>
                            <span class="visually-hidden" id="fontSizeDescription">Toggle between normal and large font sizes for better readability</span>
                        </label>
                    </div>
                    
                    <span class="navbar-text text-light me-3">
                        Welcome, <?php 
                        if ($is_delegated_user && !empty($delegated_display_name)) {
                            echo htmlspecialchars($delegated_display_name);
                        } else {
                            echo htmlspecialchars(AUTH_USER);
                        }
                        ?>
                    </span>
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fa fa-user"></i>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#changePasswordModal">
                                <i class="fa fa-key me-2"></i>Change Password</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="index.php?whp-action=logout">
                                <i class="fa fa-sign-out me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>
        
        <!-- Bootstrap 5 Offcanvas Sidebar -->
        <div class="offcanvas offcanvas-start bg-light" tabindex="-1" id="sidebarMenu" aria-labelledby="sidebarMenuLabel">
            <div class="offcanvas-header border-bottom">
                <h6 class="offcanvas-title" id="sidebarMenuLabel">Navigation</h6>
                <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
            </div>
            <div class="offcanvas-body p-0">
                <?php
                    // ---- Sidebar groups -----------------------------------------------------
                    // Each group is built up below, then rendered as a collapsible submenu
                    // when it has 2+ items. Single items (or a group with only one visible
                    // item) collapse back to a flat link.

                    $is_root_user = (defined('AUTH_USER') && AUTH_USER === 'root');

                    // Helper: returns the rendered HTML for a child link.
                    $sidebar_child = function (string $url, string $iconHtml, string $label,
                                               string $pageKey, string $page, bool $newTab = false,
                                               string $extraHtml = '') {
                        $isActive = $pageKey !== '' && $page === $pageKey;
                        $target = $newTab ? ' target="_blank"' : '';
                        return '<a href="' . htmlspecialchars($url) . '"' . $target
                            . ' class="list-group-item list-group-item-action ps-5 py-2 ' . ($isActive ? 'active' : '') . '">'
                            . $iconHtml . htmlspecialchars($label) . $extraHtml . '</a>';
                    };

                    $sidebar_top = function (string $url, string $iconHtml, string $label,
                                             string $pageKey, string $page, bool $newTab = false,
                                             string $extraHtml = '') {
                        $isActive = $pageKey !== '' && $page === $pageKey;
                        $target = $newTab ? ' target="_blank"' : '';
                        return '<a href="' . htmlspecialchars($url) . '"' . $target
                            . ' class="list-group-item list-group-item-action py-3 ' . ($isActive ? 'active' : '') . '">'
                            . $iconHtml . htmlspecialchars($label) . $extraHtml . '</a>';
                    };

                    $render_group = function (string $id, string $iconHtml, string $label,
                                              array $children, string $page, string $extraHtml = '') {
                        // children is an array of pre-rendered <a> strings (already filtered).
                        if (empty($children)) return '';
                        // Detect active page among children for auto-expand + active-on-parent.
                        $childPageKeys = [];
                        foreach ($children as $child) {
                            if (preg_match('/page=([a-z0-9_-]+)/', $child, $m)) $childPageKeys[] = $m[1];
                        }
                        $groupActive = in_array($page, $childPageKeys, true);
                        $expanded = $groupActive ? 'true' : 'false';
                        $showCls  = $groupActive ? 'show' : '';
                        $activeCls = $groupActive ? 'active' : '';

                        ob_start(); ?>
                        <a href="#<?php echo $id; ?>"
                           class="list-group-item list-group-item-action py-3 d-flex justify-content-between align-items-center <?php echo $activeCls; ?>"
                           data-bs-toggle="collapse" aria-expanded="<?php echo $expanded; ?>"
                           aria-controls="<?php echo $id; ?>">
                            <span><?php echo $iconHtml; ?><?php echo htmlspecialchars($label); ?></span>
                            <span>
                                <?php echo $extraHtml; ?>
                                <i class="fa fa-caret-down"></i>
                            </span>
                        </a>
                        <div class="collapse <?php echo $showCls; ?>" id="<?php echo $id; ?>">
                            <?php foreach ($children as $c) echo $c; ?>
                        </div>
                        <?php
                        return (string)ob_get_clean();
                    };

                    // Open-issues badge for the AI Monitor group (already wired earlier).
                    $open_issues_count = 0;
                    try {
                        if (isset($whp_db) && $whp_db) {
                            $open_issues_count = (int)$whp_db->query(
                                "SELECT COUNT(*) FROM whp.ai_monitor_issues WHERE status='open'"
                            )->fetchColumn();
                        }
                    } catch (Throwable $_e) { /* table may not exist pre-migration */ }

                    // Inline SVGs / icon fragments used in multiple places.
                    $icon_fa = function (string $cls): string {
                        return '<i class="fa ' . $cls . ' me-3"></i>';
                    };
                    $icon_fa_sub = function (string $cls): string {
                        return '<i class="fa ' . $cls . ' me-2"></i>';
                    };
                    $icon_docker = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" class="me-3" style="width: 1em; height: 1em; fill: currentColor;"><path d="M349.9 236.3h-66.1v-59.4h66.1v59.4zm0-204.3h-66.1v60.7h66.1V32zm78.2 144.8H362v59.4h66.1v-59.4zm-156.3-72.1h-66.1v60.1h66.1v-60.1zm78.1 0h-66.1v60.1h66.1v-60.1zm276.8 100c-14.4-9.7-47.6-13.2-73.1-8.4-3.3-24-16.7-44.9-41.1-63.7l-14-9.3-9.3 14c-18.4 27.8-23.4 73.6-3.7 103.8-8.7 4.7-25.8 11.1-48.4 10.7H2.4c-8.7 50.8 5.8 116.8 44 162.1 37.1 43.9 92.7 66.2 165.4 66.2 157.4 0 273.9-72.5 328.4-204.2 21.4 .4 67.6 .1 91.3-45.2 1.5-2.5 6.6-13.2 8.5-17.1l-13.3-8.9zm-511.1-27.9h-66v59.4h66.1v-59.4zm78.1 0h-66.1v59.4h66.1v-59.4zm78.1 0h-66.1v59.4h66.1v-59.4zm-78.1-72.1h-66.1v60.1h66.1v-60.1z"/></svg>';
                ?>

                <div class="list-group list-group-flush">

                    <?php // Dashboard (top-level) ?>
                    <?php echo $sidebar_top('index.php?page=dashboard', $icon_fa('fa-th-large'),
                                            'Dashboard', 'dashboard', $page); ?>

                    <?php // ---- Sites & Content group --------------------------------------- ?>
                    <?php
                    $sitesChildren = [];
                    if (canAccessPage('sites', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=sites', $icon_fa_sub('fa-server'), 'Sites', 'sites', $page);
                    }
                    if (canAccessPage('site-traffic', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=site-traffic', $icon_fa_sub('fa-line-chart'), 'Traffic', 'site-traffic', $page);
                    }
                    if (canAccessPage('site-builder', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=site-builder', $icon_fa_sub('fa-paint-brush'),
                            'Site Builder', 'site-builder', $page, false,
                            ' <span class="badge bg-info ms-1" style="font-size: 9px; vertical-align: middle;">BETA</span>');
                    }
                    if (canAccessPage('domains', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=domains', $icon_fa_sub('fa-globe'), 'Domains', 'domains', $page);
                    }
                    if (canAccessPage('wordpress', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=wordpress', $icon_fa_sub('fa-wordpress'), 'WordPress', 'wordpress', $page);
                    }
                    if (canAccessPage('filemanager', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('./filemanager/', $icon_fa_sub('fa-file'), 'File Manager', '', $page, true);
                    }
                    if (canAccessPage('terminal', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=terminal', $icon_fa_sub('fa-terminal'), 'Terminal', 'terminal', $page);
                    }
                    if (canAccessPage('cpanel-import', $is_delegated_user, $delegated_permissions)) {
                        $sitesChildren[] = $sidebar_child('index.php?page=cpanel-import', $icon_fa_sub('fa-upload'), 'cPanel Import', 'cpanel-import', $page);
                    }
                    echo $render_group('sites-submenu', $icon_fa('fa-server'), 'Sites & Content', $sitesChildren, $page);
                    ?>

                    <?php // ---- Databases & Cache group -------------------------------------- ?>
                    <?php
                    $dbChildren = [];
                    if (canAccessPage('database-management', $is_delegated_user, $delegated_permissions)) {
                        $dbChildren[] = $sidebar_child('index.php?page=database-management', $icon_fa_sub('fa-database'), 'MySQL Management', 'database-management', $page);
                    }
                    if (canAccessPage('phpmyadmin-sso', $is_delegated_user, $delegated_permissions)) {
                        $dbChildren[] = $sidebar_child('./phpmyadmin-sso.php', $icon_fa_sub('fa-database'), 'phpMyAdmin', '', $page, true);
                    }
                    if (canAccessPage('postgresql-management', $is_delegated_user, $delegated_permissions)) {
                        $dbChildren[] = $sidebar_child('index.php?page=postgresql-management', $icon_fa_sub('fa-database'), 'PostgreSQL', 'postgresql-management', $page);
                    }
                    if (canAccessPage('adminer-sso', $is_delegated_user, $delegated_permissions)) {
                        $dbChildren[] = $sidebar_child('./adminer-sso.php', $icon_fa_sub('fa-database'), 'Adminer', '', $page, true);
                    }
                    if (canAccessPage('account-valkey', $is_delegated_user, $delegated_permissions)) {
                        $dbChildren[] = $sidebar_child('index.php?page=account-valkey', $icon_fa_sub('fa-bolt'), 'Valkey Cache', 'account-valkey', $page);
                    }
                    echo $render_group('databases-submenu', $icon_fa('fa-database'), 'Databases & Cache', $dbChildren, $page);
                    ?>

                    <?php // Email + Backups (single items, top-level) ?>
                    <?php if (canAccessPage('email-management', $is_delegated_user, $delegated_permissions)): ?>
                    <?php echo $sidebar_top('index.php?page=email-management', $icon_fa('fa-envelope'),
                                            'Email', 'email-management', $page); ?>
                    <?php endif; ?>
                    <?php if (canAccessPage('backups', $is_delegated_user, $delegated_permissions)): ?>
                    <?php echo $sidebar_top('index.php?page=backups', $icon_fa('fa-cloud-upload'),
                                            'Backups', 'backups', $page); ?>
                    <?php endif; ?>

                    <?php // ---- AI Monitor (root only — already a submenu) ------------------- ?>
                    <?php if ($is_root_user): ?>
                    <?php
                    $monitorChildren = [];
                    $monitorChildren[] = $sidebar_child('index.php?page=ai-monitor',          $icon_fa_sub('fa-dashboard'),           'Dashboard',     'ai-monitor', $page);
                    $issuesBadge = $open_issues_count > 0
                        ? ' <span class="badge bg-danger ms-1">' . $open_issues_count . '</span>' : '';
                    $monitorChildren[] = $sidebar_child('index.php?page=issues',              $icon_fa_sub('fa-exclamation-triangle'),'Issues',        'issues',     $page, false, $issuesBadge);
                    $monitorChildren[] = $sidebar_child('index.php?page=ai-monitor-customer', $icon_fa_sub('fa-bar-chart'),           'Site Reports',  'ai-monitor-customer', $page);
                    $monitorChildren[] = $sidebar_child('index.php?page=ai-monitor-ignore-rules', $icon_fa_sub('fa-ban'),               'Ignore Rules',  'ai-monitor-ignore-rules', $page);
                    $parentBadge = $open_issues_count > 0
                        ? '<span class="badge bg-danger me-2">' . $open_issues_count . '</span>' : '';
                    echo $render_group('ai-monitor-submenu', $icon_fa('fa-stethoscope'),
                                       'AI Monitor', $monitorChildren, $page, $parentBadge);
                    ?>
                    <?php endif; ?>

                    <?php // ---- Security (root only) ---------------------------------------- ?>
                    <?php if ($is_root_user): ?>
                    <?php
                    $securityChildren = [];
                    $securityChildren[] = $sidebar_child('index.php?page=security-management', $icon_fa_sub('fa-shield'),             'Security Management', 'security-management', $page);
                    $securityChildren[] = $sidebar_child('index.php?page=coraza-rules',        $icon_fa_sub('fa-filter'),             'Coraza Rules',        'coraza-rules',        $page);
                    echo $render_group('security-submenu', $icon_fa('fa-lock'),
                                       'Security', $securityChildren, $page);
                    ?>
                    <?php endif; ?>

                    <?php // Customer-side Site Monitoring (non-root, single link). ?>
                    <?php if (canAccessPage('ai-monitor-customer', $is_delegated_user, $delegated_permissions) && !$is_root_user): ?>
                    <?php echo $sidebar_top('index.php?page=ai-monitor-customer',
                                            $icon_fa('fa-stethoscope'),
                                            'Site Monitoring', 'ai-monitor-customer', $page); ?>
                    <?php endif; ?>

                    <?php // ---- Users group --------------------------------------------------- ?>
                    <?php
                    $usersChildren = [];
                    if ($is_root_user) {
                        $usersChildren[] = $sidebar_child('index.php?page=user-management',  $icon_fa_sub('fa-users'),       'User Management', 'user-management', $page);
                        $usersChildren[] = $sidebar_child('index.php?page=user-resources',   $icon_fa_sub('fa-pie-chart'),   'User Resources',  'user-resources',  $page);
                    }
                    $usersChildren[] = $sidebar_child('index.php?page=delegated-users',  $icon_fa_sub('fa-user-plus'), 'Delegated Users', 'delegated-users', $page);
                    $usersChildren[] = $sidebar_child('index.php?page=active-sessions',  $icon_fa_sub('fa-sign-out'),  'Active Sessions', 'active-sessions', $page);
                    echo $render_group('users-submenu', $icon_fa('fa-users'), 'Users', $usersChildren, $page);
                    ?>

                    <?php // ---- Server Admin group (root) ------------------------------------- ?>
                    <?php if ($is_root_user): ?>
                    <?php
                    $adminChildren = [
                        $sidebar_child('index.php?page=server-settings',         $icon_fa_sub('fa-cog'),         'Server Settings',          'server-settings',         $page),
                        $sidebar_child('index.php?page=disk-usage',              $icon_fa_sub('fa-hdd-o'),       'Disk Usage',               'disk-usage',              $page),
                        $sidebar_child('index.php?page=announcements-management',$icon_fa_sub('fa-bullhorn'),    'Announcements Management', 'announcements-management',$page),
                        $sidebar_child('index.php?page=update-management',       $icon_fa_sub('fa-refresh'),     'Update Management',        'update-management',       $page),
                        $sidebar_child('index.php?page=docker-management',       '<i class="fa fa-cube me-2"></i>',
                                       'Docker Management', 'docker-management', $page),
                        $sidebar_child('index.php?page=valkey-admin',            $icon_fa_sub('fa-bolt'),        'Valkey Admin',             'valkey-admin',            $page),
                        $sidebar_child('index.php?page=container-boot',          $icon_fa_sub('fa-cogs'),        'Container Boot & Health', 'container-boot',          $page),
                        $sidebar_child('index.php?page=site-audit',              $icon_fa_sub('fa-history'),      'Site Disable Audit',       'site-audit',              $page),
                        $sidebar_child('index.php?page=account-suspensions',     $icon_fa_sub('fa-ban'),          'Account Suspensions',      'account-suspensions',     $page),
                    ];
                    echo $render_group('admin-submenu', $icon_fa('fa-sliders'),
                                       'Server Admin', $adminChildren, $page);
                    ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Critical disk-usage banner (root only, severity >= 95%). Cheap
             enough to include unconditionally; the include short-circuits
             for non-root and for healthy disks. -->
        <?php @include __DIR__ . '/includes/critical-banner.php'; ?>

        <!-- Main Content -->
        <section class="page">
            <div id="wrapper" class="container-fluid whp-content-wrapper">
                <div class="content-wrapper container">
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="page-title">
                                <div class="d-flex justify-content-between align-items-start mb-4">
                                    <div>
                                        <h1 class="mb-1">
                                            <?php echo htmlspecialchars($allowed_pages[$page]); ?>
                                        </h1>
                                        <?php if ($page === 'dashboard'): ?>
                                        <p class="text-muted mb-0">Welcome, <?php echo htmlspecialchars(AUTH_USER); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <nav aria-label="breadcrumb">
                                        <div class="bg-white rounded p-2 border">
                                            <ol class="breadcrumb mb-0">
                                                <li class="breadcrumb-item">
                                                    <a href="index.php?page=dashboard" class="text-decoration-none text-primary">
                                                        <i class="fa fa-home"></i>
                                                    </a>
                                                </li>
                                                <?php if ($page !== 'dashboard'): ?>
                                                <li class="breadcrumb-item active text-dark" aria-current="page">
                                                    <?php echo htmlspecialchars($allowed_pages[$page]); ?>
                                                </li>
                                                <?php endif; ?>
                                            </ol>
                                        </div>
                                    </nav>
                                </div>
                            </div>
                        </div>
                    </div><!-- end .page title-->
                    
                    <?php
                    // Display permission error message if one exists
                    display_permission_error();
                    ?>
                    <?php
                    // Dynamically include the requested page content
                    $page_file = __DIR__ . '/pages/' . $page . '.php';
                    if (file_exists($page_file)) {
                        include $page_file;
                    } else {
                        echo '<div class="alert alert-danger">Page not found.</div>';
                    }
                    ?>
                </div>
            </div>
        </section>

        <!-- Footer -->
        <footer class="text-center text-muted py-3">
            <small>
                Web Hosting Panel - 
                <?php 
                if (file_exists('/etc/whp-version')) {
                    echo htmlspecialchars(trim(file_get_contents('/etc/whp-version')));
                } else {
                    echo 'Development';
                }
                ?>
            </small>
        </footer>

        <!-- Core JavaScript -->
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="bootstrap5/js/bootstrap.bundle.min.js"></script>

        <!-- Bootstrap 5 Native Implementation -->
        <script type="text/javascript" src="js/bootstrap5-native.js?v=<?php echo htmlspecialchars($whp_css_v); ?>"></script>

        <!-- Local-time conversion: rewrites server-rendered UTC timestamps
             (emitted via libs/time_helpers.php's whp_local_time()) into the
             user's locale + timezone. MutationObserver picks up AJAX inserts
             automatically; callers can also invoke window.whpRefreshTimes() -->
        <script type="text/javascript" src="js/whp-times.js"></script>
        
        <!-- Chart Libraries -->
        <script src="js/chartjs/Chart.min.js"></script>
        <script src="js/moment.min.js"></script>
        <script src="js/c3/d3.v3.min.js" charset="utf-8"></script>
        <script src="js/c3/c3.min.js"></script>
        
        <!-- Optional: Dashboard specific scripts -->
        <script src="js/jquery.sparkline.min.js"></script>
        <script src="js/morris_chart/raphael-2.1.0.min.js"></script>
        <script src="js/morris_chart/morris.js"></script>
        
        <?php include 'includes/password-modal.php'; ?>
        
        <!-- Font Size Toggle Script -->
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            const fontToggle = document.getElementById('fontSizeToggle');
            if (fontToggle) {
                fontToggle.addEventListener('change', function() {
                    const isChecked = this.checked;
                    
                    // Send AJAX request to set font size preference
                    fetch('api/font-size-toggle.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'X-CSRF-Token': '<?php echo get_csrf_token(); ?>'
                        },
                        body: 'action=set&value=' + (isChecked ? '1' : '0')
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Toggle the class on body based on the response
                            document.body.classList.toggle('large-fonts', data.large_fonts);
                            
                            // Update aria-pressed for screen readers
                            fontToggle.setAttribute('aria-checked', data.large_fonts ? 'true' : 'false');
                            
                            // Announce change to screen readers
                            const announcement = document.createElement('div');
                            announcement.setAttribute('role', 'status');
                            announcement.setAttribute('aria-live', 'polite');
                            announcement.className = 'visually-hidden';
                            announcement.textContent = data.large_fonts ? 'Large font size enabled' : 'Normal font size enabled';
                            document.body.appendChild(announcement);
                            setTimeout(() => announcement.remove(), 1000);
                        }
                    })
                    .catch(error => console.error('Error toggling font size:', error));
                });
            }

            // Theme Toggle Functionality (3-state: auto/light/dark)
            const themeToggleBtn = document.getElementById('themeToggleBtn');
            const themeLabel = document.getElementById('themeLabel');

            if (themeToggleBtn) {
                // Theme configuration
                const themeConfig = {
                    'auto': { icon: 'fa-adjust', label: 'Auto', title: 'Theme: Auto (follows system)', next: 'light' },
                    'light': { icon: 'fa-sun-o', label: 'Light', title: 'Theme: Light', next: 'dark' },
                    'dark': { icon: 'fa-moon-o', label: 'Dark', title: 'Theme: Dark', next: 'auto' }
                };

                let currentPref = themeToggleBtn.getAttribute('data-theme-pref') || 'auto';

                // Function to apply theme
                function applyTheme(themePref) {
                    const html = document.documentElement;
                    let actualTheme = themePref;

                    // Handle auto theme - detect system preference
                    if (themePref === 'auto') {
                        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                        actualTheme = prefersDark ? 'dark' : 'light';
                    }

                    // Apply theme attribute
                    html.setAttribute('data-theme', actualTheme);

                    // Update button appearance
                    const config = themeConfig[themePref];
                    const iconElement = themeToggleBtn.querySelector('i');
                    iconElement.className = 'fa ' + config.icon;
                    themeLabel.textContent = config.label;
                    themeToggleBtn.title = config.title;
                    themeToggleBtn.setAttribute('data-theme-pref', themePref);
                    currentPref = themePref;
                }

                // Apply initial theme on page load
                applyTheme(currentPref);

                // Listen for system theme changes if using auto mode
                window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
                    if (currentPref === 'auto') {
                        applyTheme('auto');
                    }
                });

                // Handle button click - cycle through themes
                themeToggleBtn.addEventListener('click', function() {
                    const nextTheme = themeConfig[currentPref].next;

                    // Apply theme immediately for smooth transition
                    applyTheme(nextTheme);

                    // Send AJAX request to save preference
                    fetch('api/theme-toggle.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                            'X-CSRF-Token': '<?php echo get_csrf_token(); ?>'
                        },
                        body: 'action=set&theme=' + encodeURIComponent(nextTheme)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Announce change to screen readers
                            const announcement = document.createElement('div');
                            announcement.setAttribute('role', 'status');
                            announcement.setAttribute('aria-live', 'polite');
                            announcement.className = 'visually-hidden';
                            announcement.textContent = 'Theme changed to ' + themeConfig[nextTheme].label;
                            document.body.appendChild(announcement);
                            setTimeout(() => announcement.remove(), 1000);
                        } else {
                            console.error('Failed to save theme preference:', data.error);
                        }
                    })
                    .catch(error => {
                        console.error('Error toggling theme:', error);
                    });
                });
            }
        });
        </script>
    </body>
</html>