<?php
// Initialize CSRF token for login page (needed for theme toggle API calls)
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// 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';
$server_description = $server_settings['server_description'] ?? 'Web Hosting Panel Server';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?php
    $theme_pref = $_SESSION['theme_preference'] ?? 'auto';
    // Convert 'auto' to actual theme based on system preference
    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($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="css/waves.min.css" type="text/css" rel="stylesheet"><link rel="stylesheet" href="css/nanoscroller.css">
        <!--        <link rel="stylesheet" href="css/nanoscroller.css">-->
        <link href="css/style.css" type="text/css" rel="stylesheet">
        <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet">
        <link href="css/themify-icons.css" rel="stylesheet">
        <link href="css/color.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="account<?php echo (isset($_SESSION['large_fonts']) && $_SESSION['large_fonts']) ? ' large-fonts' : ''; ?>">
        <!-- Theme Toggle for Login Page -->
        <div style="position: absolute; top: 1rem; right: 1rem; z-index: 1000;">
            <button id="themeToggleBtn"
                    class="btn btn-sm btn-outline-secondary"
                    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 for Login Page -->
        <div class="login-font-toggle" style="top: 4rem; right: 1rem;">
            <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>
        
        <div class="container">
            <div class="row">
                <div class="account-col text-center">
                    <h1><?php echo htmlspecialchars($server_name); ?></h1>
                    <p class="text-muted mb-3"><?php echo htmlspecialchars($server_description); ?></p>
                    <h3>Log into your account</h3>
                    
                    <?php if (isset($_SESSION['login_error'])): ?>
                    <div class="alert alert-danger">
                        <i class="fa fa-exclamation-triangle"></i> <?php echo htmlspecialchars($_SESSION['login_error']); ?>
                    </div>
                    <?php 
                        unset($_SESSION['login_error']);
                    endif; ?>
                    
                    <form class="mt-4" role="form" action="index.php" method="post">
                        <div class="mb-4">
                            <label for="username" class="form-label visually-hidden">Username</label>
                            <input type="text" class="form-control form-control-lg" id="username" name="user" placeholder="Username" required>
                        </div>
                        <div class="mb-4">
                            <label for="password" class="form-label visually-hidden">Password</label>
                            <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Password" required>
                        </div>
                        <div class="mb-3 text-start">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="stay_logged_in" name="stay_logged_in" value="1">
                                <label class="form-check-label" for="stay_logged_in">
                                    Stay logged in for 7 days
                                </label>
                            </div>
                        </div>
                        <div class="d-grid mb-4">
                            <button type="submit" class="btn btn-primary btn-lg">Login</button>
                        </div>
                        <p class="text-center"><?php echo htmlspecialchars($server_name); ?> &copy; <?php echo date("Y"); ?></p>
                    </form>
                </div>
            </div>
        </div>
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <script type="text/javascript" src="bootstrap5/js/bootstrap.bundle.min.js"></script>
        <script src="js/pace.min.js"></script>
        
        <!-- 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'
                        },
                        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 $_SESSION['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>
