<?php

/**
 * ITSWEBER CMS – Front Controller
 *
 * All requests are routed through this file.
 */

// Define base path (one level up from public/)
define('BASE_PATH', dirname(__DIR__));

// ── Maintenance mode check ────────────────────────────────────────────────────
// Two distinct flags:
//   storage/.maintenance      – set/cleared automatically by BackupService
//                               during backup restore / CMS update operations
//   storage/.maintenance_mode – set/cleared by admin via Maintenance settings
//
// Either flag blocks the public frontend (HTTP 503). Admin and installer paths
// are always passed through so the admin can manage the site while it is down.
$_iw_flagBackup = BASE_PATH . '/storage/.maintenance';
$_iw_flagMode   = BASE_PATH . '/storage/.maintenance_mode';

if (is_file($_iw_flagBackup) || is_file($_iw_flagMode)) {
    $requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';

    // Allowlist: admin area + installer
    $iw_allowed = false;
    foreach (['/admin', '/installer'] as $_iw_prefix) {
        if (strncmp($requestPath, $_iw_prefix, strlen($_iw_prefix)) === 0) {
            $iw_allowed = true;
            break;
        }
    }

    if (!$iw_allowed) {
        // Read user-controlled maintenance config for custom title/message
        $iw_cfg = [];
        if (is_file($_iw_flagMode)) {
            $iw_raw = @file_get_contents($_iw_flagMode);
            if ($iw_raw !== false) {
                $iw_cfg = json_decode($iw_raw, true) ?? [];
            }
        }

        // Raw values – page.php handles escaping to support nl2br on messages
        $mainTitle   = $iw_cfg['title']     ?? 'Wartung – Gleich zurück';
        $mainMessage = $iw_cfg['message']   ?? 'Diese Website wird gerade aktualisiert oder gewartet. Bitte versuchen Sie es in wenigen Momenten erneut.';
        $mainSite    = $iw_cfg['site_name'] ?? '';

        http_response_code(503);
        header('Retry-After: 300');
        header('Content-Type: text/html; charset=UTF-8');
        include BASE_PATH . '/app/Maintenance/page.php';
        exit;
    }
}
// ─────────────────────────────────────────────────────────────────────────────

// Autoloader
require_once BASE_PATH . '/app/Core/Autoloader.php';
Autoloader::register(BASE_PATH);

// Helper functions
require_once BASE_PATH . '/app/Helpers/functions.php';

// Set timezone
date_default_timezone_set('Europe/Berlin');

// Initialize application
$app = \App\Core\App::init(BASE_PATH);

// Load active plugins (Phase 17)
// Plugins are loaded after bootstrap but before route dispatch, so they can
// register hooks. Only runs when the CMS is fully installed.
if ($app->isInstalled()) {
    \App\Services\PluginLoader::loadActive(BASE_PATH);
}

// Load routes
$router = $app->service('router');

// Route loading order is critical:
// Installer and admin routes must be registered BEFORE the frontend catch-all /{slug}.
// Otherwise /admin would match /{slug} (slug='admin') before reaching the admin routes.

// 1. Installer routes (own namespace, most specific)
if (file_exists(BASE_PATH . '/app/Config/installer_routes.php')) {
    require_once BASE_PATH . '/app/Config/installer_routes.php';
}

// 2. Admin routes (specific paths under /admin)
if (file_exists(BASE_PATH . '/app/Config/admin_routes.php')) {
    require_once BASE_PATH . '/app/Config/admin_routes.php';
}

// 3. Frontend routes (contains catch-all /{slug} — must be last)
if (file_exists(BASE_PATH . '/app/Config/routes.php')) {
    require_once BASE_PATH . '/app/Config/routes.php';
}

// Dispatch
$app->run();
