<?php
declare(strict_types=1);

require_once __DIR__ . '/app/bootstrap.php';

$route = cw_match_route(cw_request_path());
$cwWafScope = preg_replace('/[^a-z0-9_-]/', '', strtolower((string)($route['waf_scope'] ?? 'public'))) ?: 'public';
$cwWafLimits = !empty($route['form']) && is_array($route['waf_limits'] ?? null)
    ? (array)$route['waf_limits']
    : [];
cw_public_site_guard(!empty($route['legal']), $cwWafScope, $cwWafLimits);
if (!empty($route['form'])) cw_frontend_session();

// Standalone-Routen sind fuer kontrollierte vollstaendige Dokumente gedacht,
// z. B. mit Modulen ausgelieferte Hilfen. WAF/Site-Guard laufen weiterhin
// vorher; nur das Projekt-Header-/Footer-Template wird bewusst uebersprungen.
if (!empty($route['standalone']) && !empty($route['dynamic']) && is_callable($route['render'] ?? null)) {
    ($route['render'])($route);
    exit;
}

$site = cw_site_config();
$pageTitle = (string)($route['title'] ?? '');
$pageDescription = (string)($route['description'] ?? '');
$currentRoute = (string)($route['key'] ?? '404');
$pageCanonical = (string)($route['canonical'] ?? '');
$pageOgTitle = (string)($route['og_title'] ?? $pageTitle);
$pageOgDescription = (string)($route['og_description'] ?? $pageDescription);
$pageOgUrl = (string)($route['og_url'] ?? $pageCanonical);
$pageOgType = (string)($route['og_type'] ?? 'website');
$pageOgImage = (string)($route['og_image'] ?? '');
$pageStylesheets = array_values(array_filter((array)($route['stylesheets'] ?? []), 'is_string'));
$pageScripts = array_values(array_filter((array)($route['scripts'] ?? []), 'is_string'));

// Statische Seiten im Bereichsmodus werden vollständig gepuffert, damit
// page.css und page.js unabhängig vom verwendeten Projekt-Header sauber in
// head/body injiziert werden können. Frontend-Werkzeuge nutzen denselben
// Dokumentpuffer nur bei vorhandener Admin-Session.
$cwStaticPageFile = '';
$cwSectionedPage = false;
if (empty($route['dynamic'])) {
    $cwStaticPageFile = basename((string)($route['file'] ?? ''));
    $cwSectionedPage = $cwStaticPageFile !== '' && function_exists('cw_page_sections_enabled') && cw_page_sections_enabled($cwStaticPageFile);
}
$cwFrontendToolsCapture = function_exists('cw_frontend_tools_should_capture') && cw_frontend_tools_should_capture();
$cwFrontendDocumentFilterCapture = function_exists('cw_frontend_document_filters_active') && cw_frontend_document_filters_active();
$cwDocumentCapture = $cwFrontendToolsCapture || $cwSectionedPage || $cwFrontendDocumentFilterCapture;
if ($cwDocumentCapture) ob_start();

if ($currentRoute === '404') {
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
    $cwVersion = is_file(__DIR__ . '/VERSION') ? trim((string)file_get_contents(__DIR__ . '/VERSION')) : 'unknown';
    header('X-CW-404-Template: ' . $cwVersion);
}

require project_root() . '/project/templates/header.php';

if (!empty($route['dynamic']) && is_callable($route['render'] ?? null)) {
    ($route['render'])($route);
} else {
    $pageFile = project_root() . '/project/pages/' . $cwStaticPageFile;
    if (!is_file($pageFile)) {
        http_response_code(500);
        echo '<section class="py-6"><div class="container-xxl"><h1>Seitenvorlage fehlt</h1></div></section>';
    } elseif ($cwSectionedPage) {
        cw_page_sections_render($cwStaticPageFile);
    } else {
        require $pageFile;
    }
}

require project_root() . '/project/templates/footer.php';

if ($cwDocumentCapture) {
    $cwFrontendDocument = (string)ob_get_clean();
    if ($cwSectionedPage) $cwFrontendDocument = cw_page_sections_inject_assets($cwFrontendDocument, $cwStaticPageFile);
    if ($cwFrontendToolsCapture) $cwFrontendDocument = cw_frontend_tools_inject_document($cwFrontendDocument, $route);
    if ($cwFrontendDocumentFilterCapture) $cwFrontendDocument = cw_frontend_document_apply_filters($cwFrontendDocument, $route);
    echo $cwFrontendDocument;
}
