<?php
declare(strict_types=1);

// boot application (config, autoload, services)
require_once __DIR__ . '/../config/fileload.php';

$uriPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$uriPath = preg_replace('~/{2,}~', '/', $uriPath);
$uriPath = trim($uriPath, '/');

// Sicherheitscheck
if (str_contains($uriPath, '..')) {
    http_response_code(400);
    exit('Bad request');
}

// Root → page/index.php
if ($uriPath === '' || $uriPath === 'index' || $uriPath === 'index.php') {
    $target = __DIR__ . '/page/index.php';
} else {
    $base = __DIR__ . '/page/' . $uriPath;
    // 1) Verzeichnis mit index.php
    if (is_dir($base) && is_file($base . '/index.php')) {
        $target = $base . '/index.php';
    }
    // 2) Datei
    elseif (is_file($base . '.php')) {

        $target = $base . '.php';
    }
    // 3) 404
    elseif (is_file($base)) {

        $target = $base;
    }
    // 3) 404
    else {
        http_response_code(404);
        $target = __DIR__ . '/page/404.php';
    }
}
// ------------------------------------
// Layout-Regel
// ------------------------------------
$skipLayout = false;

// Beispiel: alles unter /page/raw/* ohne Layout
if (str_starts_with(realpath($target), realpath(__DIR__ . '/page/retool'))) {
    $skipLayout = true;
}

// ------------------------------------
// Ausgabe
// ------------------------------------
if (!$skipLayout) {
    tpl('layout_start', 'structure');
}

require $target;

if (!$skipLayout) {
    tpl('layout_end', 'structure');
}