<?php
/**
 * Visualizador de Documentação Markdown
 * Renderiza arquivos .md de forma apresentável
 */

// Verificar se o arquivo foi especificado
$file = $_GET['file'] ?? '';
if (empty($file)) {
    header('Location: index.html');
    exit;
}

// Validar o arquivo (apenas .md na pasta docs)
$file = basename($file);
if (!preg_match('/^[a-zA-Z0-9_-]+\.md$/', $file) || !file_exists($file)) {
    http_response_code(404);
    echo '<h1>Arquivo não encontrado</h1>';
    exit;
}

// Ler o conteúdo do arquivo
$content = file_get_contents($file);
if ($content === false) {
    http_response_code(500);
    echo '<h1>Erro ao ler arquivo</h1>';
    exit;
}

// Função simples para converter Markdown básico para HTML
function markdownToHtml($markdown)
{
    // Converter headers
    $markdown = preg_replace('/^### (.*$)/m', '<h3>$1</h3>', $markdown);
    $markdown = preg_replace('/^## (.*$)/m', '<h2>$1</h2>', $markdown);
    $markdown = preg_replace('/^# (.*$)/m', '<h1>$1</h1>', $markdown);

    // Converter listas
    $markdown = preg_replace('/^\* (.*$)/m', '<li>$1</li>', $markdown);
    $markdown = preg_replace('/^- (.*$)/m', '<li>$1</li>', $markdown);
    $markdown = preg_replace('/^(\d+)\. (.*$)/m', '<li>$2</li>', $markdown);

    // Converter código inline
    $markdown = preg_replace('/`([^`]+)`/', '<code>$1</code>', $markdown);

    // Converter blocos de código
    $markdown = preg_replace_callback('/```(\w+)?\n(.*?)\n```/s', function ($matches) {
        $lang = $matches[1] ?? '';
        $code = htmlspecialchars($matches[2], ENT_QUOTES, 'UTF-8');

        // Detectar se é JSON baseado no conteúdo ou linguagem
        if ($lang === 'json' || (empty($lang) && preg_match('/^\s*[\{\[]/', trim($matches[2])))) {
            $lang = 'json';
        }

        return '<pre><code class="language-' . $lang . '">' . $code . '</code></pre>';
    }, $markdown);

    $markdown = preg_replace_callback('/```\n(.*?)\n```/s', function ($matches) {
        $code = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');

        // Detectar se é JSON baseado no conteúdo
        $lang = '';
        if (preg_match('/^\s*[\{\[]/', trim($matches[1]))) {
            $lang = 'language-json';
        }

        return '<pre><code class="' . $lang . '">' . $code . '</code></pre>';
    }, $markdown);

    // Converter links
    $markdown = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2" target="_blank">$1</a>', $markdown);

    // Converter texto em negrito
    $markdown = preg_replace('/\*\*([^*]+)\*\*/', '<strong>$1</strong>', $markdown);
    $markdown = preg_replace('/__([^_]+)__/', '<strong>$1</strong>', $markdown);

    // Converter texto em itálico
    $markdown = preg_replace('/\*([^*]+)\*/', '<em>$1</em>', $markdown);
    $markdown = preg_replace('/_([^_]+)_/', '<em>$1</em>', $markdown);

    // Converter quebras de linha
    $markdown = preg_replace('/\n\n/', '</p><p>', $markdown);
    $markdown = '<p>' . $markdown . '</p>';

    // Limpar parágrafos vazios
    $markdown = preg_replace('/<p><\/p>/', '', $markdown);
    $markdown = preg_replace('/<p>\s*<\/p>/', '', $markdown);

    return $markdown;
}

$htmlContent = markdownToHtml($content);
$fileName = str_replace('.md', '', $file);
$pageTitle = ucwords(str_replace(['_', '-'], ' ', $fileName));
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($pageTitle); ?> - Documentação API</title>
    <link rel="icon"
        href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>📚</text></svg>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css">
    <style>
        :root {
            --primary-color: #2563eb;
            --primary-dark: #1d4ed8;
            --secondary-color: #10b981;
            --accent-color: #f59e0b;
            --text-primary: #1f2937;
            --text-secondary: #6b7280;
            --bg-primary: #ffffff;
            --bg-secondary: #f8fafc;
            --border-color: #e5e7eb;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: var(--text-primary);
            line-height: 1.6;
            min-height: 100vh;
        }

        .header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 20px 0;
            box-shadow: var(--shadow-lg);
        }

        .header-content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header h1 {
            font-size: 1.8rem;
            font-weight: 600;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            color: white;
            text-decoration: none;
            transform: translateY(-2px);
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        .content {
            background: var(--bg-primary);
            border-radius: 15px;
            padding: 40px;
            box-shadow: var(--shadow-lg);
            margin-bottom: 40px;
        }

        .content h1 {
            color: var(--primary-color);
            font-size: 2.5rem;
            margin-bottom: 20px;
            font-weight: 700;
            border-bottom: 3px solid var(--primary-color);
            padding-bottom: 15px;
        }

        .content h2 {
            color: var(--text-primary);
            font-size: 2rem;
            margin: 40px 0 20px 0;
            font-weight: 600;
            border-left: 4px solid var(--secondary-color);
            padding-left: 20px;
        }

        .content h3 {
            color: var(--text-primary);
            font-size: 1.5rem;
            margin: 30px 0 15px 0;
            font-weight: 600;
        }

        .content p {
            margin-bottom: 20px;
            color: var(--text-secondary);
            font-size: 1.1rem;
            line-height: 1.8;
        }

        .content ul,
        .content ol {
            margin: 20px 0;
            padding-left: 30px;
        }

        .content li {
            margin-bottom: 10px;
            color: var(--text-secondary);
            font-size: 1.1rem;
        }

        .content code {
            background: var(--bg-secondary);
            color: var(--primary-color);
            padding: 2px 8px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            border: 1px solid var(--border-color);
        }

        .content pre {
            background: #1f2937;
            color: #f9fafb;
            padding: 25px;
            border-radius: 10px;
            overflow-x: auto;
            margin: 25px 0;
            box-shadow: var(--shadow-md);
            white-space: pre;
            line-height: 1.6;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        }

        .content pre code {
            background: none;
            color: inherit;
            padding: 0;
            border: none;
            font-size: 0.9rem;
            line-height: 1.5;
            white-space: pre;
            overflow-x: auto;
            display: block;
            font-family: inherit;
        }

        /* Melhorar exibição de JSON */
        .content pre code.language-json,
        .content pre code[class*="language-json"] {
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            line-height: 1.6;
            tab-size: 2;
            white-space: pre;
        }

        /* Garantir que espaços e quebras sejam preservados */
        .content pre,
        .content pre code {
            white-space: pre !important;
            word-wrap: normal;
            overflow-wrap: normal;
        }

        .content a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
            transition: color 0.3s ease;
        }

        .content a:hover {
            color: var(--primary-dark);
            text-decoration: underline;
        }

        .content strong {
            color: var(--text-primary);
            font-weight: 600;
        }

        .content em {
            color: var(--text-secondary);
            font-style: italic;
        }

        .footer {
            text-align: center;
            padding: 40px 0;
            color: var(--text-secondary);
        }

        .footer a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
        }

        .footer a:hover {
            text-decoration: underline;
        }

        .toc {
            background: var(--bg-primary);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 40px;
            box-shadow: var(--shadow-md);
        }

        .toc h3 {
            color: var(--primary-color);
            margin-bottom: 20px;
            font-size: 1.3rem;
        }

        .toc ul {
            list-style: none;
            padding: 0;
        }

        .toc li {
            margin-bottom: 8px;
        }

        .toc a {
            color: var(--text-secondary);
            text-decoration: none;
            padding: 5px 0;
            display: block;
            transition: color 0.3s ease;
        }

        .toc a:hover {
            color: var(--primary-color);
        }

        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }

            .container {
                padding: 20px 10px;
            }

            .content {
                padding: 30px 20px;
            }

            .content h1 {
                font-size: 2rem;
            }

            .content h2 {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <header class="header">
        <div class="header-content">
            <h1>📚 <?php echo htmlspecialchars($pageTitle); ?></h1>
            <a href="index.html" class="back-btn">← Voltar à Documentação</a>
        </div>
    </header>

    <div class="container">
        <div class="content">
            <?php echo $htmlContent; ?>
        </div>

        <footer class="footer">
            <p><strong>Desenvolvido por <a href="https://pontti.com.br" target="_blank">Systhema
                        Tecnologia</a></strong></p>
            <p>📧 desenvolvimento@Systhema.com.br | 📞 (81) 99710-2197</p>
            <p>© 2025 Systhema Tecnologia - Todos os direitos reservados</p>
        </footer>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
</body>

</html>