<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require DENTAL_ROOT . '/app/layout.php';

function public_website_render_plain_content(string $content): void
{
    $lines = preg_split('/\R/', $content) ?: [];
    $paragraph = [];
    $listOpen = false;
    $flushParagraph = static function () use (&$paragraph): void {
        if (!$paragraph) return;
        echo '<p>' . nl2br(e(implode("\n", $paragraph))) . '</p>';
        $paragraph = [];
    };
    $closeList = static function () use (&$listOpen): void {
        if ($listOpen) {
            echo '</ul>';
            $listOpen = false;
        }
    };
    foreach ($lines as $line) {
        $trim = trim($line);
        if ($trim === '') {
            $flushParagraph();
            $closeList();
            continue;
        }
        if (preg_match('/^-\s+(.+)$/', $trim, $match)) {
            $flushParagraph();
            if (!$listOpen) {
                echo '<ul class="public-page-bullets">';
                $listOpen = true;
            }
            echo '<li>' . e($match[1]) . '</li>';
            continue;
        }
        if (str_starts_with($trim, '### ')) {
            $flushParagraph();
            $closeList();
            echo '<h3>' . e(substr($trim, 4)) . '</h3>';
            continue;
        }
        if (str_starts_with($trim, '## ')) {
            $flushParagraph();
            $closeList();
            echo '<h2>' . e(substr($trim, 3)) . '</h2>';
            continue;
        }
        $paragraph[] = $trim;
    }
    $flushParagraph();
    $closeList();
}

function public_website_feature_cards(string $raw): array
{
    $cards = [];
    foreach (public_lines($raw) as $line) {
        $parts = array_map('trim', explode('|', $line, 2));
        if (($parts[0] ?? '') === '') continue;
        $cards[] = ['title' => substr($parts[0], 0, 90), 'body' => substr($parts[1] ?? '', 0, 260)];
    }
    return array_slice($cards, 0, 9);
}

function public_website_safe_cta(string $url): bool
{
    if ($url === '' || preg_match('/\s/', $url) || preg_match('/^(javascript|data):/i', $url)) return false;
    return (bool)preg_match('/^(https?:\/\/|mailto:|tel:|[A-Za-z0-9_\-.\/]+(?:\.php)?(?:[?#][^\s]*)?|#[A-Za-z0-9_-]+)$/', $url);
}

$slug = (string) ($_GET['slug'] ?? '');
$previewMode = !empty($_GET['preview']);
$previewId = preg_replace('/[^a-zA-Z0-9_-]/', '', (string)($_GET['id'] ?? ''));
$canPreview = $previewMode && current_user() && (has_role('super_admin') || has_role('clinic_admin'));
if ($canPreview && $previewId !== '') {
    $page = public_website_page_find($previewId, false);
} else {
    $page = public_website_page_find($slug, true);
}
if (!$page) {
    http_response_code(404);
    render_header('Page not found', true);
    render_public_nav('');
    echo '<main><section class="public-section"><div class="public-section-heading"><span class="eyebrow">Not found</span><h1>Public page not found</h1><p>This webpage is unpublished, removed, or the link is incorrect.</p><a class="btn primary" href="index.php">Return Home</a></div></section></main>';
    render_public_footer();
    render_footer(true);
    exit;
}

$layout = (string)($page['layout_style'] ?? 'split');
$theme = (string)($page['theme_style'] ?? 'clinic');
$imagePosition = (string)($page['image_position'] ?? 'right');
$heroImage = (string)($page['hero_image'] ?? '');
$contentImage = (string)($page['content_image'] ?? '');
$cards = public_website_feature_cards((string)($page['feature_cards'] ?? ''));
$ctaLabel = trim((string)($page['cta_label'] ?? ''));
$ctaUrl = trim((string)($page['cta_url'] ?? ''));
$showCta = $ctaLabel !== '' && public_website_safe_cta($ctaUrl);
$heroStyle = ($heroImage && $imagePosition === 'background') ? ' style="background-image:linear-gradient(90deg,rgba(9,22,34,.86),rgba(9,22,34,.48)),url(' . e($heroImage) . ')"' : '';

render_header((string) $page['title'], true);
render_public_nav('page:' . (string) $page['slug']);
?>
<main>
    <section class="public-custom-hero page-layout-<?= e($layout) ?> page-theme-<?= e($theme) ?> page-image-<?= e($imagePosition) ?>"<?= $heroStyle ?>>
        <?php if ($heroImage && $imagePosition !== 'background' && in_array($imagePosition, ['left', 'top'], true)): ?>
            <figure class="public-page-hero-image"><img src="<?= e($heroImage) ?>" alt="<?= e((string)($page['hero_image_alt'] ?? $page['title'])) ?>"></figure>
        <?php endif; ?>
        <div class="public-custom-hero-copy">
            <?php if ($canPreview): ?><div class="public-preview-banner">Draft preview · only visible to signed-in website managers</div><?php endif; ?>
            <span class="eyebrow">Clinic information</span>
            <h1><?= e((string) $page['title']) ?></h1>
            <?php if (trim((string) $page['excerpt']) !== ''): ?><p><?= e((string) $page['excerpt']) ?></p><?php endif; ?>
            <?php if ($showCta): ?><a class="btn primary large-button" href="<?= e($ctaUrl) ?>"><?= e($ctaLabel) ?> →</a><?php endif; ?>
        </div>
        <?php if ($heroImage && $imagePosition !== 'background' && !in_array($imagePosition, ['left', 'top'], true)): ?>
            <figure class="public-page-hero-image"><img src="<?= e($heroImage) ?>" alt="<?= e((string)($page['hero_image_alt'] ?? $page['title'])) ?>"></figure>
        <?php endif; ?>
    </section>

    <section class="public-section public-custom-page page-layout-<?= e($layout) ?>">
        <div class="public-page-body-grid <?= $contentImage ? 'has-content-image' : '' ?>">
            <article class="card public-page-content">
                <?php public_website_render_plain_content((string) $page['content']); ?>
            </article>
            <?php if ($contentImage): ?>
                <figure class="card public-page-side-image"><img src="<?= e($contentImage) ?>" alt="<?= e((string)($page['content_image_alt'] ?? $page['title'])) ?>"></figure>
            <?php endif; ?>
        </div>
        <?php if ($cards): ?>
            <div class="public-page-feature-grid">
                <?php foreach ($cards as $index => $card): ?>
                    <article><span><?= str_pad((string)($index + 1), 2, '0', STR_PAD_LEFT) ?></span><h3><?= e($card['title']) ?></h3><?php if ($card['body'] !== ''): ?><p><?= e($card['body']) ?></p><?php endif; ?></article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
</main>
<?php
render_public_footer();
render_footer(true);
