<?php
/**
 * Helper function to manage output buffering consistently across all pages
 * This helps prevent "headers already sent" errors
 */

// Start output buffering if it's not already started
if (!ob_get_level()) {
    ob_start();
}

/**
 * Function to safely redirect using header()
 * 
 * @param string $url The URL to redirect to
 * @param bool $exit Whether to exit after redirect (default: true)
 */
function safe_redirect($url, $exit = true) {
    // Make sure all output buffers are flushed before redirect
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // Start a new buffer
    ob_start();
    
    // Perform the redirect
    header("Location: $url");
    
    // End the buffer and flush it
    ob_end_flush();
    
    // Exit if requested
    if ($exit) {
        exit();
    }
}
?>
