<?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 (!empty($page['blocks']) && empty($page['content'])) {
  // content kept for backward compatibility; builder saves HTML here too
  $page['content'] = '';
}
?>
<main class="content-area">
  <div class="smurf-divider"></div>
  <div class="content-wrapper">
    <section class="content-card">
      <?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'; ?>
