<?php
/**
 * Buffer Controller - Manages output buffering and timezone for the application
 */

// Set timezone before any output
if (defined('TIMEZONE')) {
    date_default_timezone_set(TIMEZONE);
} else {
    date_default_timezone_set('UTC');
}

// Configure error handling based on environment
error_reporting(E_ALL);
// Only display errors in development or when DEBUG_MODE is enabled
$is_development = (defined('DEBUG_MODE') && DEBUG_MODE === true) ||
    (defined('BASE_URL') &&
        (strpos(BASE_URL, 'localhost') !== false ||
            strpos(BASE_URL, '127.0.0.1') !== false ||
            strpos(BASE_URL, 'dev') !== false ||
            strpos(BASE_URL, 'test') !== false));

ini_set('display_errors', $is_development ? 1 : 0);
ini_set('display_startup_errors', $is_development ? 1 : 0);

// Start output buffering if not already started
if (ob_get_level() == 0) {
    ob_start();
}

// Function to safely handle output buffering
function cleanBuffer()
{
    try {
        // Get the current buffer level
        $level = ob_get_level();

        // Clean all output buffers
        while ($level > 0) {
            if (!ob_end_clean()) {
                break;
            }
            $level--;
        }
        return true;
    } catch (Exception $e) {
        error_log("Buffer cleaning error: " . $e->getMessage());
        return false;
    }
}

// Function to safely flush buffer
function flushBuffer()
{
    try {
        // Get current buffer content and clean it
        $content = ob_get_clean();

        // If we have content, send it
        if ($content) {
            echo $content;
        }

        // Flush output
        flush();
        return true;
    } catch (Exception $e) {
        error_log("Buffer flush error: " . $e->getMessage());
        return false;
    }
}

// Set cache control headers
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");
?>