<?php
/**
 * Front Controller
 *
 * Entry point for all requests. Connects this site to the shared engine.
 * Apache/Nginx rewrites all requests to this file.
 *
 * Flow:
 * 1. Load engine config (path to shared engine)
 * 2. If engine found → Bootstrap::run() → full CMS
 * 3. If engine missing → serve static fallback
 */

// Site root is ONE level up from public/
$siteRoot = dirname(__DIR__);

// Load engine config
$engineConfig = [];
$engineConfigFile = $siteRoot . '/config/engine.php';
if (is_file($engineConfigFile)) {
    $engineConfig = require $engineConfigFile;
}

$enginePath = $engineConfig['path'] ?? null;

// === ENGINE MODE: Full CMS ===
if ($enginePath && is_dir($enginePath) && is_file($enginePath . '/core/Bootstrap.php')) {
    require_once $enginePath . '/core/Bootstrap.php';
    Bootstrap::run($siteRoot, $enginePath);
    exit;
}

// === FALLBACK MODE: Engine not available ===
// Serve cached pages or show maintenance page

$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($requestUri, PHP_URL_PATH);
$path = rtrim($path, '/') ?: '/';

// Try cached page first (fastest, most complete)
$cacheFile = $siteRoot . '/storage/cache/pages/' . md5($path) . '.html';
if (is_file($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
    readfile($cacheFile);
    exit;
}

// Try to serve a page file directly (minimal mode)
$pageName = ($path === '/') ? 'index' : ltrim($path, '/');
$pageName = basename(preg_replace('/[^a-zA-Z0-9_-]/', '', $pageName));
$pageFile = $siteRoot . '/pages/' . $pageName . '.php';

if (is_file($pageFile)) {
    if (!defined('ENGINE_PATH')) define('ENGINE_PATH', '');
    if (!defined('SITE_ROOT')) define('SITE_ROOT', $siteRoot);
    if (!defined('CONFIG_PATH')) define('CONFIG_PATH', $siteRoot . '/config');
    if (!defined('STORAGE_PATH')) define('STORAGE_PATH', $siteRoot . '/storage');
    $config = is_file(CONFIG_PATH . '/site.php') ? require CONFIG_PATH . '/site.php' : [];

    // Stub helper functions so pages don't fatally crash without the engine
    if (!function_exists('site_url')) {
        function site_url(string $path = '/'): string {
            return $path;
        }
    }

    // Minimal head when engine is unavailable (uses site-local CSS fallback)
    $pageTitle = $config['site_name'] ?? 'Site';
    $pageDescription = $config['site_description'] ?? '';
    $siteLang = $config['site_language'] ?? 'en';
    echo '<!DOCTYPE html><html lang="' . htmlspecialchars($siteLang) . '"><head>';
    echo '<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">';
    echo '<title>' . htmlspecialchars($pageTitle) . '</title>';
    // Load site-local fallback CSS if available
    $fallbackBase = $siteRoot . '/public/css/base';
    if (is_dir($fallbackBase)) {
        foreach (['variables.css', 'reset.css', 'layout.css', 'components.css'] as $f) {
            if (is_file($fallbackBase . '/' . $f)) {
                echo '<link rel="stylesheet" href="/css/base/' . $f . '">';
            }
        }
    }
    // Site CSS
    if (!empty($config['site_css']) && is_array($config['site_css'])) {
        foreach ($config['site_css'] as $css) {
            echo '<link rel="stylesheet" href="' . htmlspecialchars($css) . '">';
        }
    }
    echo '</head><body>';

    include $pageFile;

    echo '</body></html>';
    exit;
}

// Nothing found — maintenance page
http_response_code(503);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Temporarily Unavailable</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #f8fafc; color: #334155; }
        .maintenance { text-align: center; max-width: 500px; padding: 2rem; }
        h1 { font-size: 1.5rem; margin-bottom: 0.5rem; }
        p { color: #64748b; line-height: 1.6; }
    </style>
</head>
<body>
    <div class="maintenance">
        <h1>Temporarily Unavailable</h1>
        <p>We're performing scheduled maintenance. Please check back shortly.</p>
    </div>
</body>
</html>
