<?php
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';

$slug = trim($_GET['slug'] ?? '');
$slug = preg_replace('/[^a-zA-Z0-9\-]/', '', $slug);

$dataFile = __DIR__ . '/data/pages.json';
$pages = [];
if (file_exists($dataFile)) {
  $pages = json_decode(file_get_contents($dataFile), true);
  if (!is_array($pages)) $pages = [];
}

$page = $slug !== '' && isset($pages[$slug]) ? $pages[$slug] : null;
$title = $page['title'] ?? 'Page';
$published = !empty($page['published']);
$image = trim((string)($page['image'] ?? ''));
$summary = trim((string)($page['summary'] ?? ''));
$buttonText = trim((string)($page['button_text'] ?? ''));
$buttonUrl = trim((string)($page['button_url'] ?? ''));
$layoutStyle = trim((string)($page['layout_style'] ?? 'standard'));
if ($layoutStyle === '') $layoutStyle = 'standard';
$templateClass = preg_replace('/[^a-z0-9\-]/i', '', strtolower($layoutStyle));
if ($templateClass === '') $templateClass = 'standard';
$contentWrapClass = in_array($templateClass, ['fullwidth','gallery','schedule-grid','top50'], true) ? 'content-wrapper content-wrapper-wide' : 'content-wrapper';
if (!empty($page['blocks']) && empty($page['content'])) {
  // content kept for backward compatibility; builder saves HTML here too
  $page['content'] = '';
}
?>
<main class="content-area custom-page template-<?= htmlspecialchars($templateClass, ENT_QUOTES, "UTF-8") ?>">
  <div class="smurf-divider"></div>
  <div class="<?= htmlspecialchars($contentWrapClass, ENT_QUOTES, "UTF-8") ?>">
    <section class="content-card custom-page-shell">
      <?php if (!$page): ?>
        <h1 class="page-title">Page Not Found</h1>
        <p>This page does not exist.</p>
      <?php elseif (!$published): ?>
        <h1 class="page-title"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></h1>
        <p>This page is not published.</p>
      <?php else: ?>
        <?php if ($image !== ''): ?>
          <div class="hero-image"><img src="<?= htmlspecialchars($image, ENT_QUOTES, 'UTF-8') ?>" alt=""></div>
        <?php endif; ?>
        <h1 class="page-title"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></h1>
        <?php if ($summary !== ''): ?>
          <p class="page-summary"><?= nl2br(htmlspecialchars($summary, ENT_QUOTES, 'UTF-8')) ?></p>
        <?php endif; ?>
        <div class="rich-content page-layout-<?= htmlspecialchars($layoutStyle, ENT_QUOTES, "UTF-8") ?>">
          <?= $page['content'] ?? '' ?>
        </div>
        <?php if ($buttonText !== '' && $buttonUrl !== ''): ?>
          <div class="page-cta center-text">
            <a href="<?= htmlspecialchars($buttonUrl, ENT_QUOTES, 'UTF-8') ?>" class="btn btn-accent"><?= htmlspecialchars($buttonText, ENT_QUOTES, 'UTF-8') ?></a>
          </div>
        <?php endif; ?>
      <?php endif; ?>
    </section>
  </div>
</main>

<?php include __DIR__ . '/includes/footer.php'; ?>
