<?php
declare(strict_types=1);

// Front controller: every request that is not a real file comes here.

if (PHP_SAPI === 'cli-server') {
    $file = __DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if (is_file($file) && $file !== __FILE__) {
        return false; // PHP's built-in dev server serves static files itself
    }
}

require __DIR__ . '/../src/bootstrap.php';

use App\Auth;

header('X-Frame-Options: DENY');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: same-origin');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'");

Auth::startSession();

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = (string) parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$base = rtrim((string) config('base_path', ''), '/');
if ($base !== '' && str_starts_with($path, $base)) {
    $path = substr($path, strlen($base));
}
$path = '/' . trim($path, '/');

if ($method === 'POST' && !csrf_ok()) {
    if (str_starts_with($path, '/api/')) {
        http_response_code(400);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'expired']);
        exit;
    }
    flash('error', 'Your form expired. Please try again.');
    redirect(Auth::player() !== null ? '/play' : '/login');
}

$routes = require APP_ROOT . '/src/routes.php';
$handler = $routes[$method . ' ' . $path] ?? null;

if ($handler === null) {
    App\View::render('not_found', ['title' => 'Not found', 'noindex' => true], 404);
}

$handler();
