<?php

/**
 * Front-Controller: jede Anfrage außer statischen Dateien läuft hier durch.
 */

declare(strict_types=1);

use Galerie\Infrastructure\Config;
use Galerie\Support\BasePath;
use Galerie\Support\CanonicalUrl;
use Psr\Http\Message\ResponseFactoryInterface;
use Slim\Factory\AppFactory;
use Slim\Interfaces\RouteParserInterface;

$root = dirname(__DIR__);

if (PHP_VERSION_ID < 70400) {
    http_response_code(500);
    exit('Die Galerie benötigt PHP 7.4 oder neuer.');
}

// Beim Veröffentlichen werden die Programmordner getauscht – in diesen Sekunden
// kurz „Einen Moment“ statt halb geladenem Code und Fehlermeldungen
$wartung = $root . '/storage/wartung.lock';
if (is_file($wartung) && time() - (int) @filemtime($wartung) < 180) {
    http_response_code(503);
    header('Retry-After: 5');
    header('Cache-Control: no-store');
    header('Content-Type: text/html; charset=utf-8');
    exit('<!doctype html><html lang="de"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
        . '<meta http-equiv="refresh" content="5"><title>Einen Moment …</title>'
        . '<body style="margin:0;display:grid;place-items:center;min-height:100vh;font-family:system-ui,sans-serif;background:#f6f4f0;color:#1c1b19">'
        . '<p style="text-align:center">Die Seite wird gerade aktualisiert.<br>Einen Moment bitte – sie lädt sich gleich von selbst neu.</p></body></html>');
}

if (!is_file($root . '/vendor/autoload.php')) {
    http_response_code(503);
    header('Retry-After: 5');
    exit('Die Seite wird gerade aktualisiert.');
}

require $root . '/vendor/autoload.php';

if (!is_file($root . '/.env')) {
    header('Location: ' . BasePath::detect($_SERVER) . '/setup.php', true, 302);
    exit;
}

mb_internal_encoding('UTF-8');
date_default_timezone_set('Europe/Vienna');

$container = (require $root . '/app/container.php')($root);

// Aufruf über eine ältere Adresse (z. B. www.lieschnig.at/foto) → dauerhaft zur Adresse aus APP_URL
$config = $container->get(Config::class);
if (!$config->bool('debug')) {
    $methode = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
    $ziel = CanonicalUrl::redirectTarget($config->string('appUrl'), $methode, (string) ($_SERVER['HTTP_HOST'] ?? ''),
        $config->string('basePath'), (string) ($_SERVER['REQUEST_URI'] ?? '/'), (string) ($_SERVER['HTTP_REFERER'] ?? ''));
    if ($ziel !== null) {
        header('Location: ' . $ziel, true, in_array($methode, ['GET', 'HEAD', 'OPTIONS'], true) ? 301 : 303);
        exit;
    }
}

AppFactory::setContainer($container);
$app = AppFactory::create();
$app->setBasePath($config->string('basePath'));

$container->set(ResponseFactoryInterface::class, $app->getResponseFactory());
$container->set(RouteParserInterface::class, $app->getRouteCollector()->getRouteParser());

(require $root . '/app/routes.php')($app);
(require $root . '/app/middleware.php')($app);

$app->run();
