<?php
/**
 * router.php — Router for PHP built-in CLI server (`php -S`).
 *
 * The `php -S` server does NOT process .htaccess, so extensionless API routes
 * (`/api/device/config` without .php) would return 404. This router maps them
 * to the API front controller and passes everything else (static files and .php pages)
 * through as-is.
 *
 * Recommended usage for development/testing:
 *     php -S 0.0.0.0:8080 router.php
 *
 * In production (Apache/Nginx) this file is NOT used: api/.htaccess handles it there.
 */

declare(strict_types=1);

$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
$path = '/' . ltrim($uri, '/');

// Clean API routes (without .php) -> front controller.
if (preg_match('#^/api/device/(config|login|activate|parental)/?$#', $path)
    || preg_match('#^/api/(tmdb|ads|sports)/?$#', $path)) {
    require __DIR__ . '/api/index.php';
    return true;
}

// If the resource exists on disk, let the built-in server serve it.
$file = __DIR__ . $path;
if ($path !== '/' && is_file($file)) {
    return false; // delegates to the default static/php handler
}

// Root -> index.php (login/dashboard redirect).
if ($path === '/' || $path === '') {
    require __DIR__ . '/index.php';
    return true;
}

// Rest: let the server handle it (404 if it does not exist).
return false;