<?php
require_once __DIR__ . '/../include/bootstrap.php';
require_once __DIR__ . '/../admin/pages/PageManager.php';

$slug = $_GET['slug'] ?? '';

if (empty($slug)) {
    http_response_code(404);
    include __DIR__ . '/../404.php';
    exit;
}

$pageManager = new PageManager();
$page = $pageManager->findBySlug($slug);

if (!$page || ($page['status'] ?? 'draft') !== 'published') {
    http_response_code(404);
    include __DIR__ . '/../404.php';
    exit;
}

$page_title = html_entity_decode($page['title'] ?? '', ENT_QUOTES, 'UTF-8');
$meta_title = !empty($page['meta_title']) ? html_entity_decode($page['meta_title'], ENT_QUOTES, 'UTF-8') : $page_title;
$meta_description = html_entity_decode($page['meta_description'] ?? '', ENT_QUOTES, 'UTF-8');
$page_content = $page['content'] ?? '';
$page_template = $page['template'] ?? 'default';
$show_footer = !empty($page['show_footer']);

include __DIR__ . '/../include/header.php';

$template_file = __DIR__ . '/../templates/pages/' . $page_template . '.php';
if (!file_exists($template_file)) {
    $template_file = __DIR__ . '/../templates/pages/default.php';
}

include $template_file;

if ($show_footer) {
    include __DIR__ . '/../include/footer.php';
}
