<?php
require_once __DIR__ . '/includes/db.php';

$id = (int)($_GET['id'] ?? 0);

if (db_is_ready() && (int)db_value('SELECT COUNT(*) FROM blog_posts') > 0) {
    $row = db_row(
        'SELECT * FROM blog_posts WHERE id = :id AND published = 1',
        ['id' => $id]
    );
    if (!$row) { header('Location: blog.php'); exit; }
    $post = [
        'id'          => (int)$row['id'],
        'slug'        => $row['slug'],
        'title'       => $row['title'],
        'date'        => $row['posted_at'],
        'excerpt'     => $row['excerpt'],
        'body'        => $row['body'],
        'cover_image' => $row['cover_image'] ?? null,
        'author'      => $row['author'] ?? null,
    ];
} else {
    $posts = require __DIR__ . '/data/blog.php';
    $post = null;
    foreach ($posts as $p) { if ((int)$p['id'] === $id) { $post = $p; break; } }
    if (!$post) { header('Location: blog.php'); exit; }
    $post['cover_image'] = $post['cover_image'] ?? null;
    $post['author']      = $post['author']      ?? null;
}

$page_title = $post['title'];
$page_description = $post['excerpt'];
require 'includes/header.php';
?>

<section class="section">
    <div class="container" style="max-width:980px;">

        <p style="font-size:.82rem;margin:0 0 2rem;">
            <a href="blog.php" style="color:var(--ink-muted);text-decoration:none;">← Back to news</a>
        </p>

        <!-- Post header: thumbnail + title + date -->
        <div class="blog-post-head">
            <?php if (!empty($post['cover_image'])): ?>
                <div class="blog-post-thumb">
                    <img src="<?= htmlspecialchars($post['cover_image']) ?>"
                         alt="<?= htmlspecialchars($post['title']) ?>">
                </div>
            <?php endif; ?>
            <div class="blog-post-head-text">
                <h1><?= htmlspecialchars($post['title']) ?></h1>
                <p class="blog-post-meta">
                    <?= htmlspecialchars(date('F j, Y', strtotime($post['date']))) ?>
                    <?php if (!empty($post['author'])): ?>
                        &nbsp;·&nbsp; By <?= htmlspecialchars($post['author']) ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>

        <hr class="blog-post-divider">

        <!-- Full body -->
        <article class="blog-post-body">
            <h2><?= htmlspecialchars($post['title']) ?></h2>
            <?= $post['body'] ?>
        </article>

        <div class="blog-post-footer">
            <p class="muted">
                Enjoyed this post? <a href="become-member.php">Become a member</a> and get updates
                like this in your inbox every month.
            </p>
            <a href="blog.php" class="btn btn-outline">← Back to all news</a>
        </div>

    </div>
</section>

<?php require 'includes/footer.php'; ?>