<?php
/**
 * Headers Manager - Centralized header management to prevent "headers already sent" errors
 * 
 * Include this file at the top of any script that needs to send headers or perform redirects
 */

// Make sure output buffering is active
if (ob_get_level() == 0) {
    ob_start();
}

global $lang_frontend; // Relies on header.php to have loaded this. Fallback in function will be used if not.

/**
 * Safe redirect function that handles output buffering
 * 
 * @param string $url URL to redirect to
 * @param int $status HTTP status code (default: 302)
 * @return void
 */
function safeRedirect($url, $status = 302) {
    // Log the redirect attempt
    error_log("Attempting redirect to: $url with status $status");
    error_log("Current buffer level: " . ob_get_level());
    
    // Check if headers have been sent
    if (headers_sent($file, $line)) {
        error_log("Headers already sent in $file on line $line");
        
        // Try JavaScript redirect as fallback
        echo "<script>window.location.href='" . htmlspecialchars($url) . "';</script>";
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url) . '" />';
        echo '</noscript>';
        echo '<p>' . ($lang_frontend['REDIRECT_FALLBACK_TEXT'] ?? 'If you are not redirected, ') . '<a href="' . htmlspecialchars($url) . '">' . ($lang_frontend['REDIRECT_FALLBACK_LINK_TEXT'] ?? 'click here') . '</a>.</p>';
    } else {
        // Simplified redirect - just clean buffers and redirect
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        
        // Simple header redirect
        header("Location: $url");
        
        // Log successful redirect
        error_log("Redirect headers sent successfully to: $url");
    }
    
    // Always exit after redirect
    exit();
}

// Set common headers to prevent caching issues
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
