<?php
/**
 * Theme — renders the public-facing page shell (header, nav, content, footer).
 *
 * A built-in simple theme so pages look complete out of the box. Everything
 * is driven by site settings (ContentBuilderAPI::getSiteSetting) and the
 * menus assigned to the 'header' / 'footer' locations.
 *
 * To use your own theme later, you can bypass this entirely from
 * public/router.php — but this gives a clean default with zero setup.
 */
class Theme {

    /**
     * Render a complete HTML document.
     *
     * @param string $headTags  contents for <head> (title, meta — from SEO hook)
     * @param string $bodyHtml  the rendered page blocks
     * @param array|null $post   the current post (for context), or null on 404
     */
    public static function renderPage(string $headTags, string $bodyHtml, ?array $post = null): string {
        $siteName   = e(ContentBuilderAPI::getSiteSetting('site_name', 'My Site'));
        $logoUrl    = trim((string)ContentBuilderAPI::getSiteSetting('logo_url', ''));
        $tagline    = ContentBuilderAPI::getSiteSetting('tagline', '');
        $showHeader = ContentBuilderAPI::getSiteSetting('show_header', '1') !== '0';
        $showFooter = ContentBuilderAPI::getSiteSetting('show_footer', '1') !== '0';
        $footerText = ContentBuilderAPI::getSiteSetting('footer_text', '');
        $headerStyle= ContentBuilderAPI::getSiteSetting('header_style', 'simple');
        $footerStyle= ContentBuilderAPI::getSiteSetting('footer_style', 'simple');
        $homeUrl    = rtrim(SLATE_URL, '/') . '/p/home';

        $header = $showHeader ? self::renderHeader($siteName, $logoUrl, $tagline, $homeUrl, $headerStyle) : '';
        $footer = $showFooter ? self::renderFooter($siteName, $footerText, $footerStyle) : '';

        // Page width: per-page meta override, else global default.
        $width = '';
        if (is_array($post) && !empty($post['id'])) {
            $width = (string)ContentBuilderAPI::getMeta((int)$post['id'], 'cb_width', '');
        }
        if ($width === '') $width = (string)ContentBuilderAPI::getSiteSetting('layout_width', 'boxed');
        $width = in_array($width, ['full','boxed','canvas'], true) ? $width : 'boxed';
        $widthClass = 'cb-w-' . $width;

        // Allow plugins to inject just before </body> (analytics, etc.)
        $extraFooter = Hook::applyFilters('content_footer', '', $post);

        // Inline the theme CSS for zero extra requests + max reliability
        // (no dependency on /plugins/*/assets being publicly served).
        $themeCss = self::css();
        $tokenCss = Branding::cssVars();

        ob_start();
        ?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= $headTags ?>

    <style><?= $tokenCss . "\n" . $themeCss ?></style>
</head>
<body class="cb-public <?= e($widthClass) ?>">
    <?= $header ?>
    <?= $bodyHtml ?>
    <?= $footer ?>
    <?= $extraFooter ?>
</body>
</html>
<?php
        return ob_get_clean();
    }

    /** The theme CSS, read from the bundled file once and inlined. */
    protected static function css(): string {
        static $css = null;
        if ($css !== null) return $css;
        $file = ContentBuilderAPI::pluginDir() . '/assets/css/public.css';
        $css = is_file($file) ? (string)file_get_contents($file) : '';
        return $css;
    }

    protected static function renderHeader(string $siteName, string $logoUrl, string $tagline, string $homeUrl, string $style = 'simple'): string {
        $menu = ContentBuilderAPI::getMenuByLocation('header');
        $styleClass = 'cb-header-' . preg_replace('/[^a-z]/', '', $style);
        ob_start();
        ?>
        <header class="cb-site-header <?= e($styleClass) ?>">
            <div class="cb-site-header-inner">
                <a class="cb-brand" href="<?= e($homeUrl) ?>">
                    <?php if ($logoUrl !== ''): ?>
                        <img class="cb-brand-logo" src="<?= e($logoUrl) ?>" alt="<?= $siteName ?>"
                             onerror="this.style.display='none';this.insertAdjacentHTML('afterend','<span class=\'cb-brand-name\'><?= addslashes($siteName) ?></span>');">
                    <?php else: ?>
                        <span class="cb-brand-name"><?= $siteName ?></span>
                        <?php if ($tagline !== ''): ?>
                            <span class="cb-brand-tagline"><?= e($tagline) ?></span>
                        <?php endif; ?>
                    <?php endif; ?>
                </a>
                <?php if ($menu && !empty($menu['items'])): ?>
                    <nav class="cb-nav" aria-label="Primary">
                        <?php foreach ($menu['items'] as $item):
                            $label = (string)($item['label'] ?? '');
                            $url   = (string)($item['url'] ?? '#');
                            if ($label === '') continue; ?>
                            <a class="cb-nav-link" href="<?= e($url) ?>"><?= e($label) ?></a>
                        <?php endforeach; ?>
                    </nav>
                <?php endif; ?>
            </div>
        </header>
        <?php
        return ob_get_clean();
    }

    protected static function renderFooter(string $siteName, string $footerText, string $style = 'simple'): string {
        $menu = ContentBuilderAPI::getMenuByLocation('footer');
        $styleClass = 'cb-footer-' . preg_replace('/[^a-z]/', '', $style);
        $year = date('Y');
        ob_start();
        ?>
        <footer class="cb-site-footer <?= e($styleClass) ?>">
            <div class="cb-site-footer-inner">
                <?php if ($menu && !empty($menu['items'])): ?>
                    <nav class="cb-footer-nav" aria-label="Footer">
                        <?php foreach ($menu['items'] as $item):
                            $label = (string)($item['label'] ?? '');
                            $url   = (string)($item['url'] ?? '#');
                            if ($label === '') continue; ?>
                            <a class="cb-footer-link" href="<?= e($url) ?>"><?= e($label) ?></a>
                        <?php endforeach; ?>
                    </nav>
                <?php endif; ?>
                <p class="cb-footer-copy">
                    <?= $footerText !== '' ? e($footerText) : '&copy; ' . $year . ' ' . $siteName ?>
                </p>
            </div>
        </footer>
        <?php
        return ob_get_clean();
    }
}
