<?php
declare(strict_types=1);

$pages = [
    'deployment' => [
        'title' => 'Deployment',
        'file' => '/var/www/html/vip_media_app/ACTIVATION_DEPLOYMENT.md',
    ],
    'api' => [
        'title' => 'API Endpoints',
        'file' => '/var/www/html/vip_media_app/API_ENDPOINTS.md',
    ],
    'redirect-loop' => [
        'title' => 'Redirect Loop Analysis',
        'file' => '/var/www/html/vip_media_app/REDIRECT_LOOP_ANALYSIS.md',
    ],
];

$slug = isset($_GET['p']) ? preg_replace('/[^a-z0-9\-]/', '', (string) $_GET['p']) : '';

if ($slug === '' && isset($_SERVER['PATH_INFO'])) {
    $slug = trim((string) $_SERVER['PATH_INFO'], '/');
    $slug = preg_replace('/[^a-z0-9\-]/', '', $slug);
}

// Pretty URLs: /docs/deployment → docs/index.php via nginx or PATH_INFO
$requestUri = $_SERVER['REQUEST_URI'] ?? '';
if ($slug === '' && preg_match('#/docs/([a-z0-9\-]+)/?$#', $requestUri, $m)) {
    $slug = $m[1];
}

if ($slug !== '' && isset($pages[$slug])) {
    $path = $pages[$slug]['file'];
    $title = $pages[$slug]['title'];
    if (!is_readable($path)) {
        http_response_code(404);
        echo 'Document not found.';
        exit;
    }
    $body = file_get_contents($path);
    header('Content-Type: text/plain; charset=utf-8');
    header('Content-Disposition: inline');
    echo "# {$title}\n\n";
    echo $body !== false ? $body : '';
    exit;
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Activation Server — Documentation</title>
    <style>
        body { font-family: system-ui, sans-serif; background: #0f1419; color: #e8eef5; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
        a { color: #3dd68c; }
        li { margin: 0.5rem 0; }
    </style>
</head>
<body>
    <h1>Documentation</h1>
    <ul>
        <?php foreach ($pages as $key => $p): ?>
        <li><a href="/docs/<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($p['title'], ENT_QUOTES, 'UTF-8') ?></a></li>
        <?php endforeach; ?>
    </ul>
    <p><a href="/">← Activation Server</a></p>
</body>
</html>
