<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/seo.php';

$slug = $_GET['slug'] ?? '';
$type = $_GET['type'] === 'news' ? 'news' : 'article';

$stmt = db()->prepare('SELECT * FROM blog_posts WHERE slug = ? AND type = ? LIMIT 1');
$stmt->execute([$slug, $type]);
$post = $stmt->fetch();

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

$basePath = $type === 'news' ? '/news' : '/blog';
$indexLabel = $type === 'news' ? 'News & Media' : 'Blog';

/* Build a table of contents by tagging each <h2> with an id */
$toc = [];
$content = preg_replace_callback('/<h2>(.*?)<\/h2>/', function ($m) use (&$toc) {
    $text = strip_tags($m[1]);
    $id = 'section-' . (count($toc) + 1) . '-' . preg_replace('/[^a-z0-9]+/', '-', strtolower($text));
    $id = trim($id, '-');
    $toc[] = ['id' => $id, 'text' => $text];
    return '<h2 id="' . $id . '">' . $m[1] . '</h2>';
}, $post['content']);

$related = db()->prepare("SELECT * FROM blog_posts WHERE type = ? AND id != ? ORDER BY published_at DESC LIMIT 3");
$related->execute([$type, $post['id']]);
$relatedPosts = $related->fetchAll();

$seo = [
    'title' => ($post['meta_title'] ?: $post['title']) . ' | ' . SITE_NAME,
    'description' => $post['meta_description'] ?: $post['excerpt'],
    'path' => $basePath . '/' . $post['slug'],
    'image' => rtrim(SITE_URL, '/') . '/' . $post['cover_image'],
    'type' => 'article',
];
$extraSchema = json_ld([
    '@context' => 'https://schema.org',
    '@type' => 'Article',
    'headline' => $post['title'],
    'description' => $post['excerpt'],
    'image' => rtrim(SITE_URL, '/') . '/' . $post['cover_image'],
    'author' => ['@type' => 'Organization', 'name' => $post['author']],
    'publisher' => ['@type' => 'Organization', 'name' => SITE_NAME],
    'datePublished' => date('c', strtotime($post['published_at'])),
]) . schema_breadcrumb([
    ['name' => $indexLabel, 'url' => $basePath],
    ['name' => $post['title'], 'url' => $basePath . '/' . $post['slug']],
]);

include __DIR__ . '/../includes/header.php';
?>
<section class="section-pad-sm">
  <div class="container-narrow">
    <?= breadcrumb_html([
        ['name' => $indexLabel, 'url' => $basePath],
        ['name' => $post['title'], 'url' => $basePath . '/' . $post['slug']],
    ]) ?>
    <div class="meta mb-4"><span class="badge badge-outline"><?= e($post['category']) ?></span><span class="text-muted text-sm"><?= time_ago_or_date($post['published_at']) ?></span><span class="text-muted text-sm">By <?= e($post['author']) ?></span></div>
    <h1><?= e($post['title']) ?></h1>
    <p class="lede"><?= e($post['excerpt']) ?></p>
  </div>
</section>

<section>
  <div class="container-narrow">
    <div class="media-frame rounded-lg aspect-video mb-8"><img src="/<?= e($post['cover_image']) ?>" alt="<?= e($post['title']) ?>" loading="eager" width="860" height="480"></div>
  </div>
</section>

<section class="section-pad-sm">
  <div class="container-narrow">
    <?php if (!empty($toc)): ?>
    <div class="toc-card mb-8">
      <h4>On This Page</h4>
      <ol>
        <?php foreach ($toc as $t): ?><li><a href="#<?= e($t['id']) ?>"><?= e($t['text']) ?></a></li><?php endforeach; ?>
      </ol>
    </div>
    <?php endif; ?>

    <div class="article-body"><?= $content ?></div>

    <div class="cta-band mt-9">
      <h2 style="font-size:var(--fs-xl);">Ready to Take the Next Step?</h2>
      <p style="color:var(--color-fog);">Speak to a Kigali Yacu advisor about your specific situation.</p>
      <div class="actions">
        <a href="/contact" class="btn btn-accent">Contact an Advisor</a>
        <a href="/vip-alerts" class="btn btn-outline-light">Join VIP Alerts</a>
      </div>
    </div>
  </div>
</section>

<?php if (!empty($relatedPosts)): ?>
<section class="section-pad" style="background:var(--color-cream);">
  <div class="container">
    <h2 class="text-center mb-6">Related Articles</h2>
    <div class="grid grid-3">
      <?php foreach ($relatedPosts as $rp): ?>
        <a href="<?= $rp['type'] === 'news' ? '/news' : '/blog' ?>/<?= e($rp['slug']) ?>" class="post-card">
          <div class="media-frame rounded-lg"><img src="/<?= e($rp['cover_image']) ?>" alt="<?= e($rp['title']) ?>" loading="lazy" width="400" height="250"></div>
          <div class="body">
            <div class="meta"><span><?= e($rp['category']) ?></span></div>
            <h3><?= e($rp['title']) ?></h3>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
  </div>
</section>
<?php endif; ?>
<?php include __DIR__ . '/../includes/footer.php'; ?>
