<?php

declare(strict_types=1);

require __DIR__ . '/inc/config.php';
require __DIR__ . '/inc/functions.php';
require __DIR__ . '/inc/Parsedown.php';

$parsedown = new Parsedown();
$parsedown->setSafeMode(true);

$currentPath = normalize_path($_SERVER['REQUEST_URI'] ?? '/');
$filePath = path_to_file($currentPath);

$topMenu = discover_sections();
$activeSection = current_section($currentPath);
$sideMenu = $activeSection ? discover_section_pages($activeSection) : [];
$breadcrumbs = build_breadcrumbs($currentPath);

$headerDoc = read_optional_markdown(CONTENT_DIR . '/_site/header.md');
$footerDoc = read_optional_markdown(CONTENT_DIR . '/_site/footer.md');

$siteHeaderHtml = $parsedown->text(render_includes($headerDoc['markdown']));
$siteFooterHtml = $parsedown->text(render_includes($footerDoc['markdown']));

if ($filePath === null) {
    http_response_code(404);
    $pageTitle = 'Not Found';
    $pageDescription = '';
    $htmlContent = <<<HTML
<h1>404 Not Found</h1>
<p>The requested page could not be found.</p>
HTML;
    require __DIR__ . '/inc/layout.php';
    exit;
}

$doc = parse_markdown_file($filePath);
$pageTitle = page_title($doc, 'Untitled');
$pageDescription = page_description($doc);
$htmlContent = $parsedown->text(render_includes($doc['markdown']));

require __DIR__ . '/inc/layout.php';
