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

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 9;
$offset = ($page - 1) * $perPage;

$total = (int)db()->query("SELECT COUNT(*) FROM blog_posts WHERE type='article'")->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));

$stmt = db()->prepare("SELECT * FROM blog_posts WHERE type='article' ORDER BY published_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute();
$posts = $stmt->fetchAll();

$seo = [
    'title' => 'Real Estate Blog & Market Insights | ' . SITE_NAME,
    'description' => 'Buying guides, financing tips and market insights for Rwanda\'s real estate market — from Kigali Yacu Properties.',
    'path' => '/blog',
];
include __DIR__ . '/../includes/header.php';
?>
<section class="section-pad-sm">
  <div class="container">
    <?= breadcrumb_html([['name' => 'Blog', 'url' => '/blog']]) ?>
    <div class="section-head center">
      <div class="eyebrow" style="justify-content:center;">Journal</div>
      <h1>Real Estate Insights for Rwanda</h1>
      <p>Buying guides, financing explainers and market analysis to help you make confident property decisions.</p>
    </div>
    <div class="grid grid-3">
      <?php foreach ($posts as $i => $post): ?>
        <a href="/blog/<?= e($post['slug']) ?>" class="post-card reveal" data-delay="<?= $i % 3 + 1 ?>">
          <div class="media-frame rounded-lg"><img src="/<?= e($post['cover_image']) ?>" alt="<?= e($post['title']) ?>" loading="lazy" width="400" height="250"></div>
          <div class="body">
            <div class="meta"><span><?= e($post['category']) ?></span><span><?= time_ago_or_date($post['published_at']) ?></span></div>
            <h3><?= e($post['title']) ?></h3>
            <p class="excerpt"><?= e($post['excerpt']) ?></p>
          </div>
        </a>
      <?php endforeach; ?>
    </div>
    <?= paginate_query('/blog', $_GET, $page, $totalPages) ?>
  </div>
</section>
<?php include __DIR__ . '/../includes/footer.php'; ?>
