<?php
/**
 * Content Builder — front-end resolver.
 *
 * Maps an incoming slug to a rendered page. Wire your router/rewrite so
 * /<slug> (pages) and /<type>/<slug> (posts/CPTs) reach this file. See the
 * .htaccess snippet in the README.
 *
 * Fires 'content_head_tags' so the SEO plugin (or any plugin) can inject
 * <meta> tags, and 'content_footer' for trailing scripts.
 */
require_once dirname(__DIR__, 3) . '/config.php';

$type = preg_replace('/[^a-z0-9_-]/', '', $_GET['type'] ?? 'page');
$slug = preg_replace('/[^a-z0-9_\-\/]/', '', $_GET['slug'] ?? 'home');

$post = ContentBuilderAPI::getPostBySlug($type, $slug);

if (!$post || $post['status'] !== 'published') {
    http_response_code(404);
    $headTags = '<title>404 — Not found</title>';
    $bodyHtml = '<main class="cb-page"><h1>404</h1><p>That page could not be found.</p></main>';
} else {
    // Let plugins (SEO) contribute <head> tags. Default to a <title>.
    $default  = '<title>' . e($post['title'] ?: 'Untitled') . '</title>';
    $headTags = Hook::applyFilters('content_head_tags', $default, $post);
    $bodyHtml = '<main class="cb-page">'
              . ContentBuilderAPI::renderLayout($post['layout'])
              . '</main>';
}

$footer = Hook::applyFilters('content_footer', '', $post ?? null);

/*
 * Minimal standalone shell. If your platform has a public theme, replace
 * everything below with:  include SLATE_ROOT . '/public/theme/page.php';
 * passing $headTags and $bodyHtml.
 */
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= $headTags ?>
    <link rel="stylesheet" href="<?= e(SLATE_URL) ?>/plugins/content-builder/admin/assets/builder.css">
</head>
<body class="cb-public">
    <?= $bodyHtml ?>
    <?= $footer ?>
</body>
</html>
