<?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 and delegated-users pages
    if (in_array($page, ['dashboard', 'delegated-users'])) {
        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', 'valkey-admin'
    ];
    
    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',
    'user-management' => 'User Management',
    'delegated-users' => 'Delegated Users',
    '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',
    'ai-monitor' => 'AI Monitor',
    'ai-monitor-customer' => 'Site Monitoring',
    'issues' => 'Issues',
];

$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>

        <!-- Bootstrap 5 -->
        <link href="bootstrap5/css/bootstrap.min.css" rel="stylesheet">
        <link href="css/bootstrap5-whp-theme.css" 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="#"><?php echo htmlspecialchars($server_name); ?></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">
                        <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">
                <div class="list-group list-group-flush">
                    <a href="index.php?page=dashboard" class="list-group-item list-group-item-action py-3 <?php echo $page === 'dashboard' ? 'active' : ''; ?>">
                        <i class="fa fa-th-large me-3"></i>Dashboard
                    </a>
                    <?php if (canAccessPage('filemanager', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="./filemanager/" target="_blank" class="list-group-item list-group-item-action py-3">
                        <i class="fa fa-file me-3"></i>File Manager
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('database-management', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=database-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'database-management' ? 'active' : ''; ?>">
                        <i class="fa fa-database me-3"></i>MySQL Management
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('phpmyadmin-sso', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="./phpmyadmin-sso.php" target="_blank" class="list-group-item list-group-item-action py-3">
                        <i class="fa fa-database me-3"></i>phpMyAdmin
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('postgresql-management', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=postgresql-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'postgresql-management' ? 'active' : ''; ?>">
                        <i class="fa fa-database me-3"></i>PostgreSQL Management
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('adminer-sso', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="./adminer-sso.php" target="_blank" class="list-group-item list-group-item-action py-3">
                        <i class="fa fa-database me-3"></i>Adminer
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('email-management', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=email-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'email-management' ? 'active' : ''; ?>">
                        <i class="fa fa-envelope me-3"></i>Email Management
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('backups', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=backups" class="list-group-item list-group-item-action py-3 <?php echo $page === 'backups' ? 'active' : ''; ?>">
                        <i class="fa fa-cloud-upload me-3"></i>Backup Management
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('account-valkey', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=account-valkey" class="list-group-item list-group-item-action py-3 <?php echo $page === 'account-valkey' ? 'active' : ''; ?>">
                        <i class="fa fa-database me-3"></i>Valkey Cache
                    </a>
                    <?php endif; ?>
                    <?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
                    <a href="index.php?page=valkey-admin" class="list-group-item list-group-item-action py-3 <?php echo $page === 'valkey-admin' ? 'active' : ''; ?>">
                        <i class="fa fa-server me-3"></i>Valkey Admin
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('domains', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=domains" class="list-group-item list-group-item-action py-3 <?php echo $page === 'domains' ? 'active' : ''; ?>">
                        <i class="fa fa-globe me-3"></i>Domains
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('sites', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=sites" class="list-group-item list-group-item-action py-3 <?php echo $page === 'sites' ? 'active' : ''; ?>">
                        <i class="fa fa-server me-3"></i>Sites
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('site-builder', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=site-builder" class="list-group-item list-group-item-action py-3 <?php echo $page === 'site-builder' ? 'active' : ''; ?>">
                        <i class="fa fa-paint-brush me-3"></i>Site Builder <span class="badge bg-info ms-1" style="font-size: 9px; vertical-align: middle;">BETA</span>
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('terminal', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=terminal" class="list-group-item list-group-item-action py-3 <?php echo $page === 'terminal' ? 'active' : ''; ?>">
                        <i class="fa fa-terminal me-3"></i>Terminal
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('wordpress', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=wordpress" class="list-group-item list-group-item-action py-3 <?php echo $page === 'wordpress' ? 'active' : ''; ?>">
                        <i class="fa fa-wordpress me-3"></i>WordPress Management
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('cpanel-import', $is_delegated_user, $delegated_permissions)): ?>
                    <a href="index.php?page=cpanel-import" class="list-group-item list-group-item-action py-3 <?php echo $page === 'cpanel-import' ? 'active' : ''; ?>">
                        <i class="fa fa-upload me-3"></i>cPanel Import
                    </a>
                    <?php endif; ?>
                    <?php if (canAccessPage('ai-monitor-customer', $is_delegated_user, $delegated_permissions) && (!defined('AUTH_USER') || AUTH_USER !== 'root')): ?>
                    <a href="index.php?page=ai-monitor-customer" class="list-group-item list-group-item-action py-3 <?php echo $page === 'ai-monitor-customer' ? 'active' : ''; ?>">
                        <i class="fa fa-stethoscope me-3"></i>Site Monitoring
                    </a>
                    <?php endif; ?>
                    <?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
                    <a href="index.php?page=user-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'user-management' ? 'active' : ''; ?>">
                        <i class="fa fa-users me-3"></i>User Management
                    </a>
                    <?php endif; ?>
                    <a href="index.php?page=delegated-users" class="list-group-item list-group-item-action py-3 <?php echo $page === 'delegated-users' ? 'active' : ''; ?>">
                        <i class="fa fa-user-plus me-3"></i>Delegated Users
                    </a>
                    <?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
                    <a href="index.php?page=security-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'security-management' ? 'active' : ''; ?>">
                        <i class="fa fa-shield me-3"></i>Security Management
                    </a>
                    <a href="index.php?page=announcements-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'announcements-management' ? 'active' : ''; ?>">
                        <i class="fa fa-bullhorn me-3"></i>Announcements Management
                    </a>
                    <a href="index.php?page=update-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'update-management' ? 'active' : ''; ?>">
                        <i class="fa fa-refresh me-3"></i>Update Management
                    </a>
                    <a href="index.php?page=docker-management" class="list-group-item list-group-item-action py-3 <?php echo $page === 'docker-management' ? 'active' : ''; ?>">
                                                        <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>Docker Management
                    </a>
                    <a href="index.php?page=user-resources" class="list-group-item list-group-item-action py-3 <?php echo $page === 'user-resources' ? 'active' : ''; ?>">
                        <i class="fa fa-pie-chart me-3"></i>User Resources
                    </a>
                    <a href="index.php?page=server-settings" class="list-group-item list-group-item-action py-3 <?php echo $page === 'server-settings' ? 'active' : ''; ?>">
                        <i class="fa fa-cog me-3"></i>Server Settings
                    </a>
                    <a href="index.php?page=ai-monitor" class="list-group-item list-group-item-action py-3 <?php echo $page === 'ai-monitor' ? 'active' : ''; ?>">
                        <i class="fa fa-stethoscope me-3"></i>AI Monitor
                    </a>
                    <a href="index.php?page=issues" class="list-group-item list-group-item-action py-3 <?php echo $page === 'issues' ? 'active' : ''; ?>">
                        <i class="fa fa-exclamation-triangle me-3"></i>Issues
                        <?php
                            try {
                                if (isset($whp_db) && $whp_db) {
                                    $_sc = (int)$whp_db->query("SELECT COUNT(*) FROM whp.ai_monitor_issues WHERE status='open'")->fetchColumn();
                                    if ($_sc > 0) echo '<span class="badge bg-danger ms-1">' . $_sc . '</span>';
                                }
                            } catch (Throwable $_e) { /* silent — table may not exist pre-migration */ }
                        ?>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <section class="page">
            <div id="wrapper" class="container-fluid" style="margin-top: 80px; padding: 20px;">
                <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"></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>