<?php
// Include PHP version check early for security
require_once __DIR__ . '/version_check.php';

// Buffer handling moved to buffer_controller.php

// Bootstrap dependencies in correct order
require_once __DIR__ . '/../config/config.php';

// Include buffer controller 
require_once __DIR__ . '/buffer_controller.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';

// Check country blocking early (before session initialization to avoid unnecessary session creation)
// This must be called after functions.php is loaded (where checkCountryBlocking is defined)
if (function_exists('checkCountryBlocking')) {
    checkCountryBlocking();
}

// Include centralized session manager
require_once __DIR__ . '/session_manager.php';

// Initialize session using centralized manager
SessionManager::initialize();
if (function_exists('refreshUserSessionFromDb')) {
    refreshUserSessionFromDb();
}

// --- START LANGUAGE LOADER ---
// Base directory for language files, dynamically set by SITE_LANGUAGE
// Fallback to 'english-us' if SITE_LANGUAGE is not defined or is empty.
$_site_language_folder = (defined('SITE_LANGUAGE') && !empty(SITE_LANGUAGE)) ? SITE_LANGUAGE : 'english-us';
$_base_lang_dir = __DIR__ . '/../languages/' . $_site_language_folder . '/';

// Declare global language arrays
global $lang, $lang_frontend, $lang_alerts, $lang_navigation, $lang_email, $lang_admin, $lang_config;

// Load consolidated language strings
$lang_path = $_base_lang_dir . 'lang.php';
$lang = file_exists($lang_path) ? include($lang_path) : [];

// --- BACKWARD COMPATIBILITY LAYER ---
// Map consolidated keys to legacy global variables to avoid breaking existing code
$lang_frontend = $lang;
$lang_alerts = $lang;
$lang_navigation = $lang;
$lang_email = $lang;
$lang_admin = $lang;
$lang_config = $lang;
// --- END LANGUAGE LOADER ---
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php echo isset($page_title) ? $page_title . ' - ' . (defined('SEO_TITLE') && SEO_TITLE ? SEO_TITLE : SITE_NAME) : (defined('SEO_TITLE') && SEO_TITLE ? SEO_TITLE : SITE_NAME); ?>
    </title>
    <?php if (defined('SEO_DESCRIPTION') && SEO_DESCRIPTION): ?>
        <meta name="description" content="<?php echo htmlspecialchars(SEO_DESCRIPTION); ?>">
    <?php endif; ?>
    <?php if (defined('SEO_KEYWORDS') && SEO_KEYWORDS): ?>
        <meta name="keywords" content="<?php echo htmlspecialchars(SEO_KEYWORDS); ?>">
    <?php endif; ?>
    <?php if (defined('SEO_AUTHOR') && SEO_AUTHOR): ?>
        <meta name="author" content="<?php echo htmlspecialchars(SEO_AUTHOR); ?>">
    <?php endif; ?>
    <?php if (SEO_IMAGE !== ''): ?>
        <meta property="og:image" content="<?php echo SEO_IMAGE; ?>" />
    <?php endif; ?>
    <link rel="icon" type="image/png" href="<?php echo getCleanUrl('assets/favicon.png'); ?>" />

    <!-- Premium Typography -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Outfit:wght@400;500;600;700&display=swap"
        rel="stylesheet">

    <link href="<?php echo BOOTSTRAP_CSS; ?>" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo BOOTSTRAP_ICONS; ?>">
    <link href="<?php echo getCleanUrl(defined('CSS_FILE') ? CSS_FILE : 'style_default.css'); ?>" rel="stylesheet">
    <link href="<?php echo getCleanUrl('includes/css/mobile-fixes.css'); ?>" rel="stylesheet">

    <!-- Enhanced file upload functionality -->
    <script src="<?php echo getCleanUrl('includes/js/file-upload-enhancement.js'); ?>" defer></script>

    <?php if (defined('HCAPTCHA_ENABLED') && HCAPTCHA_ENABLED && defined('HCAPTCHA_SITE_KEY') && !empty(HCAPTCHA_SITE_KEY)): ?>
        <!-- hCaptcha for spam protection -->
        <script src="https://js.hcaptcha.com/1/api.js" async defer></script>
    <?php endif; ?>

    <?php
    // Custom JavaScript code injection
    if (defined('CUSTOM_JAVASCRIPT_CODE') && !empty(CUSTOM_JAVASCRIPT_CODE)) {
        $customJS = base64_decode(CUSTOM_JAVASCRIPT_CODE, true);
        // Validate decoded content is valid base64
        if ($customJS === false) {
            error_log("Invalid base64 encoded CUSTOM_JAVASCRIPT_CODE in header.php");
            $customJS = '';
        }
        if ($customJS !== false && !empty(trim($customJS))) {
            // Basic security check - ensure it doesn't contain suspicious patterns
            $suspiciousPatterns = [
                '/<\s*script[^>]*src\s*=/i',  // External script loading
                '/document\.write\s*\(/i',     // document.write calls
                '/eval\s*\(/i',                // eval() calls
                '/new\s+Function\s*\(/i',      // Function constructor
                '/setTimeout\s*\(\s*["\'].*?["\']/i', // setTimeout with string
                '/setInterval\s*\(\s*["\'].*?["\']/i', // setInterval with string
            ];

            $isSafe = true;
            foreach ($suspiciousPatterns as $pattern) {
                if (preg_match($pattern, $customJS)) {
                    $isSafe = false;
                    break;
                }
            }

            if ($isSafe) {
                echo "\n    <!-- Custom JavaScript Code -->\n";
                echo "    <script>\n";
                echo $customJS;
                echo "\n    </script>\n";
            } else {
                error_log("Custom JavaScript code blocked due to potentially unsafe content.");
            }
        }
    }
    ?>
    <?php if (GOOGLE_ANALYTICS !== ''): ?>
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo GOOGLE_ANALYTICS; ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag() { dataLayer.push(arguments); }
            gtag('js', new Date());

            gtag('config', '<?php echo GOOGLE_ANALYTICS; ?>');
        </script>
    <?php endif; ?>
    <!-- Include Trumbowyg JS -->

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Summernote -->
    <link href="<?php echo getCleanUrl('includes/css/summernote-bs5.css'); ?>" rel="stylesheet">
    <script src="<?php echo getCleanUrl('includes/js/summernote-bs5.js'); ?>"></script>
    <script src="<?php echo getCleanUrl('includes/js/summernote-magic.js'); ?>"></script>
    <?php
    // Custom JavaScript code injection
    if (defined('CUSTOM_JAVASCRIPT_HEADER') && !empty(CUSTOM_JAVASCRIPT_HEADER)) {
        $decodedValue = base64_decode(CUSTOM_JAVASCRIPT_HEADER, true);
        // Validate decoded content is valid base64
        if ($decodedValue === false) {
            error_log("Invalid base64 encoded CUSTOM_JAVASCRIPT_HEADER in header.php");
            $decodedValue = '';
        }
        echo $decodedValue;
    }
    ?>
</head>

<body>
    <?php
    // Dynamic Header Loading System
    // Whitelist of allowed header styles for security
    $allowedHeaderStyles = ['default', 'centered', 'minimal', 'vertical', 'custom'];
    $headerStyle = defined('STYLE_HEADER') ? strtolower(STYLE_HEADER) : 'default';

    // Validate against whitelist
    if (!in_array($headerStyle, $allowedHeaderStyles)) {
        error_log("Invalid STYLE_HEADER value detected: " . htmlspecialchars($headerStyle, ENT_QUOTES, 'UTF-8') . " - using default");
        $headerStyle = 'default';
    }

    $headerFile = __DIR__ . '/headers/header_' . $headerStyle . '.php';

    // Validate file path is within allowed directory
    $realHeaderFile = realpath($headerFile);
    $allowedDir = realpath(__DIR__ . '/headers/');

    // Security check: ensure file is within allowed directory
    if ($realHeaderFile === false || $allowedDir === false || strpos($realHeaderFile, $allowedDir) !== 0) {
        error_log("Security: Attempted to access invalid header file path");
        $headerFile = __DIR__ . '/headers/header_default.php';
    }

    // Fallback to default if file doesn't exist
    if (!file_exists($headerFile)) {
        $headerFile = __DIR__ . '/headers/header_default.php';
    }

    // Final validation before include
    $realHeaderFile = realpath($headerFile);
    if ($realHeaderFile && $allowedDir && strpos($realHeaderFile, $allowedDir) === 0 && file_exists($realHeaderFile)) {
        include $realHeaderFile;
    } else {
        // Ultimate fallback - basic navbar
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
            <div class="container">
                <a class="navbar-brand" href="' . getCleanUrl('index') . '">' . SITE_NAME . '</a>
            </div>
        </nav>';
    }
    ?>

    <main class="container py-4">
        <?php if (isset($_SESSION['alert'])): ?>
            <?php echo $_SESSION['alert']; ?>
            <?php unset($_SESSION['alert']); ?>
        <?php endif; ?>

        <!-- Session Timeout Warning Modal -->
        <?php if (isLoggedIn()): ?>
            <div class="modal fade" id="sessionTimeoutModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static"
                data-bs-keyboard="false">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header bg-warning">
                            <h5 class="modal-title">
                                <i class="bi bi-exclamation-triangle-fill"></i>
                                <?php echo $lang_alerts['SESSION_EXPIRING_SOON_TITLE'] ?? 'Session Expiring Soon'; ?>
                            </h5>
                        </div>
                        <div class="modal-body">
                            <p><?php echo $lang_alerts['SESSION_WILL_EXPIRE_TEXT'] ?? 'Your session will expire in'; ?>
                                <span id="sessionCountdown" class="fw-bold text-danger">5:00</span>.
                            </p>
                            <p><?php echo $lang_alerts['SESSION_EXTEND_PROMPT'] ?? 'Would you like to extend your session?'; ?>
                            </p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary"
                                id="sessionLogoutBtn"><?php echo $lang_navigation['MODAL_BUTTON_LOGOUT_NOW'] ?? 'Logout Now'; ?></button>
                            <button type="button" class="btn btn-primary" id="sessionExtendBtn">
                                <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                                <?php echo $lang_navigation['MODAL_BUTTON_EXTEND_SESSION'] ?? 'Extend Session'; ?>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                // Session timeout warning system
                document.addEventListener('DOMContentLoaded', function () {
                    // Check if required functions and Bootstrap are available
                    if (typeof bootstrap === 'undefined') {
                        console.error('Bootstrap is not loaded - session timeout modal will not work');
                        return;
                    }

                    <?php
                    // Calculate session expiry time with better error handling
                    $expiryTimestamp = null;
                    if (isset($_SESSION['expires_at'])) {
                        try {
                            $expiryDateTime = new DateTime($_SESSION['expires_at']);
                            $expiryTimestamp = $expiryDateTime->getTimestamp() * 1000; // Convert to milliseconds for JavaScript
                        } catch (Exception $e) {
                            error_log("Session expiry parsing error: " . $e->getMessage());
                            $expiryTimestamp = null;
                        }
                    }

                    if ($expiryTimestamp === null) {
                        // Fallback calculation
                        $lifetime = isset($_SESSION['remember_me']) && $_SESSION['remember_me']
                            ? (defined('SESSION_REMEMBER_ME_LIFETIME') ? SESSION_REMEMBER_ME_LIFETIME : 604800)
                            : (defined('SESSION_LIFETIME') ? SESSION_LIFETIME : 1440);
                        $expiryTimestamp = (time() + $lifetime) * 1000;
                    }
                    ?>

                    let sessionExpiryTime = <?php echo $expiryTimestamp; ?>;
                    const warningTime = 5 * 60 * 1000; // 5 minutes before expiry

                    // Check if CSRF token generation function exists
                    let csrfToken = '';
                    <?php if (function_exists('generate_csrf_token')): ?>
                        csrfToken = '<?php echo generate_csrf_token(); ?>';
                    <?php else: ?>
                        console.warn('CSRF token function not available');
                    <?php endif; ?>

                    let countdownInterval = null;
                    let sessionCheckInterval = null;
                    let warningShown = false;

                    // --- AUTO SESSION EXTEND ON ACTIVITY ---
                    let lastActivity = Date.now();
                    let autoExtendTimeout = null;
                    const AUTO_EXTEND_INTERVAL = 5 * 60 * 1000; // 5 minutes
                    let lastExtendTime = 0;
                    function scheduleAutoExtend() {
                        if (autoExtendTimeout) clearTimeout(autoExtendTimeout);
                        autoExtendTimeout = setTimeout(tryAutoExtendSession, AUTO_EXTEND_INTERVAL);
                    }
                    function tryAutoExtendSession() {
                        // Only extend if user is logged in and session is not expired
                        if (!csrfToken) return;
                        const now = Date.now();
                        // Throttle: only extend if last extension was > 4 min ago
                        if (now - lastExtendTime < 4 * 60 * 1000) {
                            scheduleAutoExtend();
                            return;
                        }
                        const formData = new FormData();
                        formData.append('csrf_token', csrfToken);
                        fetch('<?php echo getCleanUrl("session_refresh"); ?>', {
                            method: 'POST',
                            body: formData
                        })
                            .then(res => res.json())
                            .then(data => {
                                if (data && data.success) {
                                    sessionExpiryTime = data.expires_at;
                                    lastExtendTime = Date.now();
                                    scheduleAutoExtend();
                                } else if (data && data.error) {
                                    // Session expired or error, redirect to login
                                    window.location.href = '<?php echo getCleanUrl("login"); ?>';
                                }
                            })
                            .catch(() => {
                                // Network error, optionally handle
                            });
                    }
                    ['mousemove', 'keydown', 'mousedown', 'touchstart'].forEach(event => {
                        document.addEventListener(event, () => {
                            lastActivity = Date.now();
                            scheduleAutoExtend();
                        });
                    });
                    scheduleAutoExtend();
                    // --- END AUTO SESSION EXTEND ---

                    function updateCountdown() {
                        try {
                            const now = new Date().getTime();
                            const timeLeft = sessionExpiryTime - now;
                            if (timeLeft <= 0) {
                                // Session expired, cleanup and redirect
                                cleanup();
                                window.location.href = '<?php echo getCleanUrl("logout"); ?>';
                                return;
                            }
                            if (timeLeft <= warningTime && !warningShown) {
                                showWarningModal();
                            }
                        } catch (error) {
                            console.error('Session countdown error:', error);
                        }
                    }
                    function showWarningModal() {
                        try {
                            const modalElement = document.getElementById('sessionTimeoutModal');
                            if (!modalElement) {
                                console.error('Session timeout modal not found');
                                return;
                            }
                            const modal = new bootstrap.Modal(modalElement);
                            modal.show();
                            warningShown = true;
                            // Start countdown in modal
                            if (countdownInterval) clearInterval(countdownInterval);
                            countdownInterval = setInterval(function () {
                                try {
                                    const now = new Date().getTime();
                                    const timeLeft = sessionExpiryTime - now;
                                    if (timeLeft <= 0) {
                                        cleanup();
                                        window.location.href = '<?php echo getCleanUrl("logout"); ?>';
                                        return;
                                    }
                                    const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
                                    const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
                                    const countdownElement = document.getElementById('sessionCountdown');
                                    if (countdownElement) {
                                        countdownElement.textContent =
                                            minutes + ':' + (seconds < 10 ? '0' : '') + seconds;
                                    }
                                } catch (error) {
                                    console.error('Countdown update error:', error);
                                }
                            }, 1000);
                        } catch (error) {
                            console.error('Error showing warning modal:', error);
                        }
                    }
                    function cleanup() {
                        if (countdownInterval) {
                            clearInterval(countdownInterval);
                            countdownInterval = null;
                        }
                        if (sessionCheckInterval) {
                            clearInterval(sessionCheckInterval);
                            sessionCheckInterval = null;
                        }
                    }
                    // Check session expiry every 30 seconds
                    sessionCheckInterval = setInterval(updateCountdown, 30000);
                    updateCountdown(); // Check immediately
                    // Cleanup on page unload
                    window.addEventListener('beforeunload', cleanup);
                    // Handle extend session button
                    document.getElementById('sessionExtendBtn').addEventListener('click', function () {
                        const btn = this;
                        const spinner = btn.querySelector('.spinner-border');
                        btn.disabled = true;
                        spinner.classList.remove('d-none');
                        // Send session refresh request
                        const formData = new FormData();
                        formData.append('csrf_token', csrfToken);
                        fetch('<?php echo getCleanUrl("session_refresh"); ?>', {
                            method: 'POST',
                            body: formData
                        })
                            .then(response => {
                                const contentType = response.headers.get('content-type');
                                if (!contentType || !contentType.includes('application/json')) {
                                    return response.text().then(text => {
                                        throw new Error(`Expected JSON response but got ${contentType || 'unknown content type'}. Response starts with: ${text.substring(0, 50)}...`);
                                    });
                                }
                                return response.json();
                            })
                            .then(data => {
                                if (data && data.success) {
                                    sessionExpiryTime = data.expires_at;
                                    warningShown = false;
                                    if (countdownInterval) {
                                        clearInterval(countdownInterval);
                                        countdownInterval = null;
                                    }
                                    const modal = bootstrap.Modal.getInstance(document.getElementById('sessionTimeoutModal'));
                                    if (modal) {
                                        modal.hide();
                                    }
                                    const alertDiv = document.createElement('div');
                                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                                    alertDiv.innerHTML = `
                            <i class="bi bi-check-circle-fill"></i> ${data.message || ('<?php echo addslashes($lang_alerts['SESSION_EXTENDED_SUCCESSFULLY'] ?? 'Session extended successfully'); ?>')}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        `;
                                    const mainElement = document.querySelector('main');
                                    if (mainElement) {
                                        mainElement.insertBefore(alertDiv, mainElement.firstChild);
                                    }
                                    setTimeout(() => {
                                        if (alertDiv && alertDiv.parentNode) {
                                            alertDiv.remove();
                                        }
                                    }, 3000);
                                } else {
                                    throw new Error(data.error || 'Session extension failed - no success flag');
                                }
                            })
                            .catch(error => {
                                console.error('Session refresh error details:', error);
                                console.error('Error stack:', error.stack);
                                const errorMsg = error.message || ('<?php echo addslashes($lang_alerts['SESSION_UNKNOWN_ERROR'] ?? 'Unknown error occurred'); ?>');
                                if (!errorMsg.includes(('<?php echo addslashes($lang_alerts['SESSION_EXTENDED_SUCCESSFULLY'] ?? 'Session extended successfully'); ?>'))) {
                                    alert(('<?php echo addslashes($lang_alerts['SESSION_EXTENSION_FAILED_PREFIX'] ?? 'Session extension failed: '); ?>') + errorMsg + '. Please try logging in again if the issue persists.');
                                }
                            })
                            .finally(() => {
                                btn.disabled = false;
                                spinner.classList.add('d-none');
                            });
                    });
                    // Handle logout button
                    document.getElementById('sessionLogoutBtn').addEventListener('click', function () {
                        window.location.href = '<?php echo getCleanUrl("logout"); ?>';
                    });
                });
            </script>
        <?php endif; ?>