<?php
declare(strict_types=1);

/**
 * Simple documentation viewer (Markdown → HTML via marked).
 */

$docsDir = __DIR__;
$docMap = [];

foreach (glob($docsDir . '/*.md') ?: [] as $path) {
    $base = basename($path, '.md');
    if (preg_match('/^[A-Z0-9_]+$/', $base) !== 1) {
        continue;
    }
    $docMap[$base] = $path;
}

ksort($docMap);

$requested = isset($_GET['doc']) ? (string) $_GET['doc'] : '';
$activeDoc = null;
$markdown = null;
$pageTitle = 'Dokumentation';

if ($requested !== '') {
    if (!isset($docMap[$requested])) {
        http_response_code(404);
        $pageTitle = 'Nicht gefunden';
    } else {
        $activeDoc = $requested;
        $markdown = file_get_contents($docMap[$requested]);
        if ($markdown === false) {
            http_response_code(500);
            $pageTitle = 'Fehler';
            $markdown = null;
        } else {
            $pageTitle = docTitle($activeDoc);
        }
    }
}

function docTitle(string $key): string
{
    return ucwords(strtolower(str_replace('_', ' ', $key)));
}

function escape(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$baseHref = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/docs')), '/') . '/';
if ($baseHref === '/') {
    $baseHref = '/docs/';
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape($pageTitle); ?> – PSA Dokumentation</title>
    <link rel="stylesheet" href="<?php echo escape($baseHref); ?>assets/docs.css">
</head>
<body>
    <header class="docs-header">
        <div class="docs-header-inner">
            <a class="docs-brand" href="<?php echo escape($baseHref); ?>index.php">PSA Dokumentation</a>
            <a class="docs-back" href="../index.php">Zur Anwendung</a>
        </div>
    </header>
    <div class="docs-layout">
        <nav class="docs-nav" aria-label="Dokumentation">
            <p class="docs-nav-title">Inhalt</p>
            <ul>
                <?php foreach ($docMap as $key => $_path): ?>
                    <li>
                        <a href="<?php echo escape($baseHref); ?>index.php?doc=<?php echo escape($key); ?>"
                           <?php echo $key === $activeDoc ? 'aria-current="page"' : ''; ?>>
                            <?php echo escape(docTitle($key)); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </nav>
        <main class="docs-main">
            <?php if ($requested === ''): ?>
                <h1>Dokumentation</h1>
                <p>Technische und fachliche Hinweise zum PSA-Bestellsystem.</p>
                <ul class="docs-index-list">
                    <?php foreach ($docMap as $key => $_path): ?>
                        <li>
                            <a href="<?php echo escape($baseHref); ?>index.php?doc=<?php echo escape($key); ?>">
                                <?php echo escape(docTitle($key)); ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php elseif ($markdown === null): ?>
                <h1><?php echo escape($pageTitle); ?></h1>
                <p>Das angeforderte Dokument ist nicht verfügbar.</p>
                <p><a href="<?php echo escape($baseHref); ?>index.php">Zur Übersicht</a></p>
            <?php else: ?>
                <article id="doc-content" class="markdown-body"></article>
                <script type="application/json" id="doc-source"><?php
                    echo json_encode(
                        $markdown,
                        JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE
                    );
                ?></script>
            <?php endif; ?>
        </main>
    </div>
    <?php if ($markdown !== null): ?>
        <script src="<?php echo escape($baseHref); ?>assets/marked.min.js"></script>
        <script>
            (function () {
                var source = document.getElementById('doc-source');
                var target = document.getElementById('doc-content');
                if (!source || !target || typeof marked === 'undefined') {
                    return;
                }
                var text = JSON.parse(source.textContent || '""');
                target.innerHTML = marked.parse(text, { gfm: true, breaks: false });
                target.querySelectorAll('a[href]').forEach(function (link) {
                    var href = link.getAttribute('href');
                    if (!href || /^[a-z]+:/i.test(href) || href.charAt(0) === '#') {
                        return;
                    }
                    var name = href.split('/').pop().replace(/\.md$/i, '');
                    if (/^[A-Z0-9_]+$/i.test(name)) {
                        link.setAttribute('href', 'index.php?doc=' + encodeURIComponent(name.toUpperCase()));
                    }
                });
            })();
        </script>
    <?php endif; ?>
</body>
</html>
