<?php
// Start output buffering at the very beginning

ob_start();

// Include header (which will handle loading functions.php and config)
include_once 'includes/header.php';

// Load dynamic homepage layout based on STYLE_HOME config
// Whitelist of allowed homepage styles for security
$allowedHomeStyles = ['default', 'hero', 'list', 'minimum', 'store', 'custom'];
$homeStyle = defined('STYLE_HOME') ? strtolower(STYLE_HOME) : 'default';

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

$homeFile = __DIR__ . '/includes/homepages/home_' . $homeStyle . '.php';

// Validate file path is within allowed directory
$realHomeFile = realpath($homeFile);
$allowedDir = realpath(__DIR__ . '/includes/homepages/');

// Security check: ensure file is within allowed directory
if ($realHomeFile === false || $allowedDir === false || strpos($realHomeFile, $allowedDir) !== 0) {
    error_log("Security: Attempted to access invalid homepage file path");
    $homeFile = __DIR__ . '/includes/homepages/home_default.php';
}

// Fallback to default if specified file doesn't exist
if (!file_exists($homeFile)) {
    $homeFile = __DIR__ . '/includes/homepages/home_default.php';
}

// Final validation before include
$realHomeFile = realpath($homeFile);
if ($realHomeFile && $allowedDir && strpos($realHomeFile, $allowedDir) === 0 && file_exists($realHomeFile)) {
    include $realHomeFile;
} else {
    // Ultimate fallback if no homepage files exist
    echo '<div class="container py-4">';
    echo '<div class="alert alert-warning">' . ($lang_frontend['ERROR_HOMEPAGE_LAYOUT_NOT_FOUND'] ?? 'Homepage layout file not found. Please check your installation.') . '</div>';
    echo '</div>';
}

// Include footer
include 'includes/footer.php';
?>