<?php
require_once __DIR__ . '/manual_content.php';

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

function enrepManualAssetUrl(string $src, bool $forPdf = false): string
{
    $src = ltrim($src, '/\\');
    if ($src === '') {
        return '';
    }

    if ($forPdf) {
        $path = __DIR__ . '/../../' . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $src);
        return file_exists($path) ? $path : $src;
    }

    $root = defined('ROOT_URL') ? rtrim((string)ROOT_URL, '/') : '';
    return $root . '/' . str_replace('\\', '/', $src);
}

function enrepManualFigureHtml(array $figure, bool $forPdf = false): string
{
    $src = enrepManualAssetUrl((string)($figure['src'] ?? ''), $forPdf);
    if ($src === '') {
        return '';
    }

    $alt = enrepManualEscape((string)($figure['alt'] ?? 'Manual illustration'));
    $caption = trim((string)($figure['caption'] ?? ''));

    $html = '<figure class="manual-figure">';
    $html .= '<img src="' . enrepManualEscape($src) . '" alt="' . $alt . '">';
    if ($caption !== '') {
        $html .= '<figcaption>' . enrepManualEscape($caption) . '</figcaption>';
    }
    $html .= '</figure>';

    return $html;
}

function enrepManualSectionHtml(array $section, bool $forPdf = false): string
{
    $html = '<section class="manual-section" id="' . enrepManualEscape((string)$section['id']) . '">';
    $html .= '<h2>' . enrepManualEscape((string)$section['title']) . '</h2>';
    $html .= '<p class="manual-summary">' . enrepManualEscape((string)$section['summary']) . '</p>';

    if (!empty($section['figure']) && is_array($section['figure'])) {
        $html .= enrepManualFigureHtml($section['figure'], $forPdf);
    }

    if (!empty($section['body']) && is_array($section['body'])) {
        foreach ($section['body'] as $paragraph) {
            $html .= '<p>' . enrepManualEscape((string)$paragraph) . '</p>';
        }
    }

    if (!empty($section['features']) && is_array($section['features'])) {
        $html .= '<div class="manual-feature-list">';
        foreach ($section['features'] as $feature) {
            $html .= '<article class="manual-feature">';
            $html .= '<h3>' . enrepManualEscape((string)($feature['title'] ?? 'Feature')) . '</h3>';
            $html .= '<p>' . enrepManualEscape((string)($feature['text'] ?? '')) . '</p>';
            $html .= '</article>';
        }
        $html .= '</div>';
    }

    if (!empty($section['items']) && is_array($section['items'])) {
        $html .= '<h3>Typical Steps</h3><ul class="manual-action-list">';
        foreach ($section['items'] as $item) {
            $html .= '<li>' . enrepManualEscape((string)$item) . '</li>';
        }
        $html .= '</ul>';
    }

    if (!empty($section['best_practice']) && is_array($section['best_practice'])) {
        $html .= '<div class="manual-best-practice"><h3>Good Practice</h3><ul>';
        foreach ($section['best_practice'] as $item) {
            $html .= '<li>' . enrepManualEscape((string)$item) . '</li>';
        }
        $html .= '</ul></div>';
    }

    $html .= '</section>';
    return $html;
}

function enrepManualTocHtml(array $sections): string
{
    $html = '<nav class="manual-toc"><h2>Contents</h2><ol>';
    foreach ($sections as $section) {
        $html .= '<li><a href="#' . enrepManualEscape((string)$section['id']) . '">' . enrepManualEscape((string)$section['title']) . '</a></li>';
    }
    $html .= '<li><a href="#manual-maintenance">Manual Maintenance</a></li>';
    $html .= '</ol></nav>';
    return $html;
}

function enrepManualSidebarHtml(array $sections): string
{
    $html = '<aside class="manual-sidebar"><div class="manual-sidebar-title">Contents</div>';
    $html .= '<button type="button" class="manual-nav-link active" data-manual-section="welcome">Welcome</button>';
    foreach ($sections as $section) {
        $html .= '<button type="button" class="manual-nav-link" data-manual-section="' . enrepManualEscape((string)$section['id']) . '">' . enrepManualEscape((string)$section['title']) . '</button>';
    }
    $html .= '<button type="button" class="manual-nav-link" data-manual-section="manual-maintenance">Manual Maintenance</button>';
    $html .= '</aside>';
    return $html;
}

function enrepManualWelcomeHtml(): string
{
    return '<section class="manual-section manual-welcome" id="manual-welcome">'
        . '<h2>Welcome</h2>'
        . '<p class="manual-summary">This manual gives practical guidance for using EnRep day to day.</p>'
        . '<p>EnRep is organised around the work you do for a client: maintaining the client record, keeping the asset schedule accurate, completing inspections, issuing reports, and managing written schemes where they apply.</p>'
        . '<p>Choose a topic from the contents list to read that section. The PDF download contains the full manual in one document for printing, sharing, or offline reference.</p>'
        . '<div class="manual-best-practice"><h3>Using This Manual</h3><ul>'
        . '<li>Start with the section that matches the task you are doing now.</li>'
        . '<li>Use the good-practice notes when you are unsure how much detail to enter.</li>'
        . '<li>Use Manual Maintenance to see what the manual covers and when it should be reviewed.</li>'
        . '</ul></div>'
        . '</section>';
}

function enrepManualTemplateHtml(array $sections): string
{
    $html = '<div id="manualTemplates" class="manual-templates" hidden>';
    $html .= '<template id="manual-template-welcome">' . enrepManualWelcomeHtml() . '</template>';
    foreach ($sections as $section) {
        $html .= '<template id="manual-template-' . enrepManualEscape((string)$section['id']) . '">' . enrepManualSectionHtml($section, false) . '</template>';
    }
    $html .= '<template id="manual-template-manual-maintenance">' . enrepManualMaintenanceHtml() . '</template>';
    $html .= '</div>';
    return $html;
}

function enrepManualMaintenanceHtml(): string
{
    $coverage = enrepManualCoverageRegister();
    $checklist = enrepManualUpdateChecklist();

    $html = '<section class="manual-section manual-maintenance" id="manual-maintenance">';
    $html .= '<h2>Manual Maintenance</h2>';
    $html .= '<p class="manual-summary">This register tracks what the manual currently covers and when it should be reviewed.</p>';
    $html .= '<div class="table-responsive"><table class="table table-sm table-striped manual-register"><thead><tr><th>Area</th><th>Included</th><th>Review When</th></tr></thead><tbody>';
    foreach ($coverage as $row) {
        $html .= '<tr><td>' . enrepManualEscape((string)$row['area']) . '</td><td>' . enrepManualEscape((string)$row['covered']) . '</td><td>' . enrepManualEscape((string)$row['update_trigger']) . '</td></tr>';
    }
    $html .= '</tbody></table></div>';
    $html .= '<h3>Update Checklist</h3><ul>';
    foreach ($checklist as $item) {
        $html .= '<li>' . enrepManualEscape((string)$item) . '</li>';
    }
    $html .= '</ul></section>';

    return $html;
}

function enrepManualBodyHtml(bool $forPdf = false): string
{
    $meta = enrepManualMeta();
    $sections = enrepManualSections();
    $html = '<div class="manual-document' . ($forPdf ? ' manual-pdf' : '') . '">';
    $html .= '<header class="manual-hero">';
    $html .= '<h1>' . enrepManualEscape((string)$meta['title']) . '</h1>';
    $html .= '<p>' . enrepManualEscape((string)$meta['subtitle']) . '</p>';
    $html .= '<div class="manual-meta">Version ' . enrepManualEscape((string)$meta['version']) . ' | Last reviewed ' . enrepManualEscape((string)$meta['last_reviewed']) . ' | Owner ' . enrepManualEscape((string)$meta['owner']) . '</div>';
    $html .= '</header>';
    $html .= enrepManualTocHtml($sections);
    foreach ($sections as $section) {
        $html .= enrepManualSectionHtml($section, $forPdf);
    }
    $html .= enrepManualMaintenanceHtml();
    $html .= '</div>';

    return $html;
}

function enrepManualCss(): string
{
    $cssFile = __DIR__ . '/manual.css';
    return file_exists($cssFile) ? (string)file_get_contents($cssFile) : '';
}
