<?php
$page_title = 'Buy Local News';
$page_description = 'Latest news, member spotlights, event recaps and insights from Buy Local Lowveld.';

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

if (db_is_ready() && (int)db_value('SELECT COUNT(*) FROM blog_posts') > 0) {
    $rows = db_all(
        'SELECT id, slug, title, excerpt, posted_at, cover_image, author
           FROM blog_posts
           WHERE published = 1
           ORDER BY posted_at DESC'
    );
} else {
    // Fallback to static data — normalise shape
    $static = require __DIR__ . '/data/blog.php';
    $rows = array_map(fn($p) => [
        'id'          => (int)$p['id'],
        'slug'        => $p['slug'] ?? '',
        'title'       => $p['title'],
        'excerpt'     => $p['excerpt'] ?? '',
        'posted_at'   => $p['date'] ?? date('Y-m-d'),
        'cover_image' => null,
        'author'      => null,
    ], $static);
}

require 'includes/header.php';
?>

<!-- Dark hero banner -->
<section class="blog-hero">
    <div class="container">
        <h1>BUY LOCAL<br><span>NEWS</span></h1>
    </div>
</section>

<section class="section">
    <div class="container">
        <?php if (empty($rows)): ?>
            <p class="muted" style="text-align:center;">No posts published yet.</p>
        <?php else: ?>
        <div class="blog-grid">
            <?php foreach ($rows as $post):
                $img = !empty($post['cover_image']) ? $post['cover_image'] : null;
            ?>
                <a href="blog-post.php?id=<?= (int)$post['id'] ?>" class="blog-tile">
                    <div class="blog-tile-img">
                        <?php if ($img): ?>
                            <img src="<?= htmlspecialchars($img) ?>"
                                 alt="<?= htmlspecialchars($post['title']) ?>"
                                 loading="lazy">
                        <?php else: ?>
                            <div class="blog-tile-img-fallback">
                                <?= htmlspecialchars(strtoupper(mb_substr($post['title'], 0, 2))) ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="blog-tile-body">
                        <h3><?= htmlspecialchars($post['title']) ?></h3>
                        <p class="blog-tile-date">
                            <?= htmlspecialchars(date('F j, Y', strtotime($post['posted_at']))) ?>
                        </p>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</section>

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