<?php
declare(strict_types=1);

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

// Staging-Access-Protection (Basic Auth)
$uriPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$uriPath = preg_replace('~/{2,}~', '/', $uriPath);
$uriPath = trim($uriPath, '/');
$isRetoolPath = ($uriPath === 'retool' || str_starts_with($uriPath, 'retool/'));
if (defined('APP_ENV') && APP_ENV === 'staging' && !$isRetoolPath) {
    $authUser = getenv('STAGING_AUTH_USER') ?: 'staging';
    $authPass = getenv('STAGING_AUTH_PASS') ?: 'staging123';
    $remoteUser = $_SERVER['REMOTE_USER'] ?? null;
    $user = $_SERVER['PHP_AUTH_USER'] ?? null;
    $pass = $_SERVER['PHP_AUTH_PW'] ?? null;

    // If Apache already authenticated the request via .htaccess, trust that layer.
    $hasUpstreamBasicAuth = is_string($remoteUser) && $remoteUser !== '';

    if (!$hasUpstreamBasicAuth && ($user !== $authUser || $pass !== $authPass)) {
        header('WWW-Authenticate: Basic realm="Staging"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Unauthorized';
        exit;
    }
}

// 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;
$targetReal = realpath($target);

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

// ------------------------------------
// Ausgabe
// ------------------------------------
// Erst Inhalt laden (ohne Ausgabe), damit Header/Redirects vor HTML funktionieren
ob_start();
require $target;
$content = ob_get_clean();

// Wenn bereits Header gesendet wurden (z. B. eigener Redirect/Content-Type), Layout überspringen
if (headers_sent()) {
    $skipLayout = true;
}

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

echo $content;

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