<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$routes = require DENTAL_ROOT . '/config/routes.php';
$slugMap = is_file(DENTAL_ROOT . '/config/route_slugs.php')
    ? require DENTAL_ROOT . '/config/route_slugs.php'
    : [];
$slugToRoute = [];
foreach ($slugMap as $routeName => $slug) {
    if (is_string($routeName) && is_string($slug) && $routeName !== '' && $slug !== '') {
        $slugToRoute[$slug] = $routeName;
    }
}

$route = trim((string) ($_GET['route'] ?? ''));
$slug = trim((string) ($_GET['slug'] ?? ''));

if ($slug !== '') {
    if (!preg_match('/^[A-Za-z0-9_-]+$/', $slug)) {
        http_response_code(404);
        exit('Page not found.');
    }
    $route = $slugToRoute[$slug] ?? str_replace('-', '_', $slug);
}

if ($route === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $route)) {
    http_response_code(404);
    exit('Page not found.');
}

if (!isset($routes[$route]) || !is_file($routes[$route])) {
    http_response_code(404);
    exit('Page not found.');
}

$canonicalSlug = $slugMap[$route] ?? str_replace('_', '-', $route);
$requestMethod = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
$requestPath = trim((string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH), '/');
$baseDir = trim(str_replace('\\', '/', dirname((string) ($_SERVER['SCRIPT_NAME'] ?? ''))), '/.');
if ($baseDir !== '' && str_starts_with($requestPath, $baseDir . '/')) {
    $requestPath = substr($requestPath, strlen($baseDir) + 1);
}
$requestedLeaf = basename($requestPath);

// Serve both established flat PHP URLs and clean slugs without an extra
// browser redirect. Most application links intentionally remain compatible
// with flat URLs, and redirecting every click through a canonical slug creates
// unnecessary hops and can form a loop when a shared-host proxy rewrites the
// request URI differently from Apache. A canonical Link header preserves the
// preferred clean URL for crawlers without changing the browser location.
if ($requestMethod === 'GET'
    && $canonicalSlug !== ''
    && $requestedLeaf === $route . '.php'
    && !headers_sent()) {
    $query = $_GET;
    unset($query['route'], $query['slug']);
    $target = $canonicalSlug . ($query ? '?' . http_build_query($query) : '');
    header('Link: <' . $target . '>; rel="canonical"', false);
}

$GLOBALS['DENTAL_ROUTE'] = $route;
$GLOBALS['DENTAL_ROUTE_SLUG'] = $canonicalSlug;
require $routes[$route];
