<?php
declare(strict_types=1);

// Single entry point for every secured JSON file under /secure/.
// Validates "Authorization: Bearer <token>" before serving the requested file.

$storeRoot = __DIR__ . '/_store';
$tokens = require __DIR__ . '/_config/tokens.php';

function respond_error(int $status, string $message): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['error' => $message]);
    exit;
}

function get_bearer_token(): ?string {
    $authHeader = null;

    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('apache_request_headers')) {
        foreach (apache_request_headers() as $key => $value) {
            if (strcasecmp($key, 'Authorization') === 0) {
                $authHeader = $value;
                break;
            }
        }
    }

    if (!$authHeader || stripos($authHeader, 'Bearer ') !== 0) {
        return null;
    }

    return trim(substr($authHeader, 7));
}

// Path requested, e.g. /secure/trudel/v2/prod/locker-Le21Mars.json -> trudel/v2/prod/locker-Le21Mars.json
$requestPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
$requestPath = rawurldecode((string) $requestPath);

$scriptDir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
$relative = $requestPath;
if ($scriptDir !== '' && strpos($requestPath, $scriptDir) === 0) {
    $relative = substr($requestPath, strlen($scriptDir));
}
$relative = ltrim($relative, '/');

if ($relative === '') {
    respond_error(404, 'Not found');
}

$segments = explode('/', $relative);
foreach ($segments as $segment) {
    if ($segment === '' || $segment === '.' || $segment === '..') {
        respond_error(400, 'Invalid path');
    }
}

$client = $segments[0];

$token = get_bearer_token();
if ($token === null) {
    respond_error(401, 'Unauthorized');
}

if (!isset($tokens[$client])) {
    respond_error(404, 'Not found');
}

if (!hash_equals($tokens[$client], $token)) {
    respond_error(403, 'Invalid API key');
}

$realStoreRoot = realpath($storeRoot);
$candidate = $storeRoot . '/' . implode('/', $segments);
$realCandidate = realpath($candidate);

if (
    $realStoreRoot === false ||
    $realCandidate === false ||
    strpos($realCandidate, $realStoreRoot . DIRECTORY_SEPARATOR) !== 0 ||
    !is_file($realCandidate) ||
    strtolower(pathinfo($realCandidate, PATHINFO_EXTENSION)) !== 'json'
) {
    respond_error(404, 'Not found');
}

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
readfile($realCandidate);
