<?php
/**
 * EduTrack Blog — public listing page.
 */

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

$conn = blog_db();

// Pagination
$per_page    = 9;
$page        = max(1, (int) ($_GET['page'] ?? 1));
$offset      = ($page - 1) * $per_page;
$category    = trim($_GET['cat'] ?? '');
$safe_cat    = htmlspecialchars($category);

// Count total published
if ($category !== '') {
    $st = $conn->prepare('SELECT COUNT(*) FROM blog_posts WHERE status="published" AND category=?');
    $st->bind_param('s', $category);
} else {
    $st = $conn->prepare('SELECT COUNT(*) FROM blog_posts WHERE status="published"');
}
$st->execute();
$st->bind_result($total);
$st->fetch();
$st->close();
$total_pages = (int) ceil($total / $per_page);

// Fetch posts
if ($category !== '') {
    $st = $conn->prepare(
        'SELECT slug, title, meta_description, category, tags, excerpt, reading_time_minutes, published_at
         FROM blog_posts WHERE status="published" AND category=?
         ORDER BY published_at DESC LIMIT ? OFFSET ?'
    );
    $st->bind_param('sii', $category, $per_page, $offset);
} else {
    $st = $conn->prepare(
        'SELECT slug, title, meta_description, category, tags, excerpt, reading_time_minutes, published_at
         FROM blog_posts WHERE status="published"
         ORDER BY published_at DESC LIMIT ? OFFSET ?'
    );
    $st->bind_param('ii', $per_page, $offset);
}
$st->execute();
$result = $st->get_result();
$posts  = $result->fetch_all(MYSQLI_ASSOC);
$st->close();

// All categories for filter
$cats_res  = $conn->query('SELECT DISTINCT category FROM blog_posts WHERE status="published" AND category != "" ORDER BY category ASC');
$all_cats  = $cats_res ? $cats_res->fetch_all(MYSQLI_ASSOC) : [];

$page_title = $category ? "{$safe_cat} — " . BLOG_SITE_NAME : BLOG_SITE_NAME;
$canonical  = BLOG_BASE_URL . '/index.php' . ($category ? '?cat=' . urlencode($category) : '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= htmlspecialchars($page_title) ?></title>
  <meta name="description" content="<?= htmlspecialchars(BLOG_DESCRIPTION) ?>">
  <link rel="canonical" href="<?= $canonical ?>">
  <link rel="alternate" type="application/rss+xml" title="<?= htmlspecialchars(BLOG_SITE_NAME) ?>" href="<?= BLOG_BASE_URL ?>/rss.php">
  <!-- Open Graph -->
  <meta property="og:title"       content="<?= htmlspecialchars($page_title) ?>">
  <meta property="og:description" content="<?= htmlspecialchars(BLOG_DESCRIPTION) ?>">
  <meta property="og:type"        content="website">
  <meta property="og:url"         content="<?= $canonical ?>">
  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link rel="stylesheet" href="assets/blog.css">
  <!-- JSON-LD WebSite schema -->
  <script type="application/ld+json">
  {"@context":"https://schema.org","@type":"WebSite","name":"<?= BLOG_SITE_NAME ?>","url":"<?= BLOG_BASE_URL ?>","description":"<?= BLOG_DESCRIPTION ?>"}
  </script>
</head>
<body class="blog-body">

<!-- NAV -->
<nav class="blog-nav">
  <div class="container d-flex align-items-center justify-content-between py-3">
    <a class="blog-brand" href="<?= BLOG_BASE_URL ?>/index.php">
      <span class="brand-dot"></span> EduTrack Blog
    </a>
    <div class="d-flex align-items-center gap-3">
         <a href="https://edutrack.oricnetwork.com/" class="btn btn-sm btn-secondary px-3" target="_blank">Back to Homepage</a>
      <a href="<?= BLOG_BASE_URL ?>/rss.php" class="text-muted small" title="RSS Feed"><i class="fas fa-rss"></i></a>
      <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-sm btn-primary px-3" target="_blank">Get EduTrack Free</a>
    </div>
  </div>
</nav>

<!-- HERO -->
<section class="blog-hero text-center py-5">
  <div class="container">
    <h1 class="hero-title">School Management Insights<br>for Ghana &amp; Africa</h1>
    <p class="hero-sub">Practical guides for headteachers, bursars, and school administrators</p>
    <!-- category pills -->
    <div class="cat-pills d-flex flex-wrap justify-content-center gap-2 mt-4">
      <a href="<?= BLOG_BASE_URL ?>/index.php" class="cat-pill <?= $category === '' ? 'active' : '' ?>">All</a>
      <?php foreach ($all_cats as $c): ?>
        <a href="<?= BLOG_BASE_URL ?>/index.php?cat=<?= urlencode($c['category']) ?>"
           class="cat-pill <?= $category === $c['category'] ? 'active' : '' ?>">
          <?= htmlspecialchars($c['category']) ?>
        </a>
      <?php endforeach ?>
    </div>
  </div>
</section>

<!-- POSTS GRID -->
<main class="container py-5">
  <?php if (empty($posts)): ?>
    <div class="text-center py-5">
      <i class="fas fa-pencil-alt fa-3x text-muted mb-3"></i>
      <p class="text-muted">No posts yet. Check back soon!</p>
    </div>
  <?php else: ?>
    <div class="row g-4">
    <?php foreach ($posts as $p):
        $post_url = BLOG_BASE_URL . '/post.php?slug=' . urlencode($p['slug']);
        $pub_date = $p['published_at'] ? date('d M Y', strtotime($p['published_at'])) : '';
    ?>
      <div class="col-md-6 col-xl-4">
        <article class="post-card h-100">
          <div class="post-card-body d-flex flex-column h-100">
            <div class="post-meta mb-2">
              <span class="post-category"><?= htmlspecialchars($p['category'] ?? '') ?></span>
              <span class="post-date ms-2"><?= $pub_date ?></span>
            </div>
            <h2 class="post-title">
              <a href="<?= $post_url ?>"><?= htmlspecialchars($p['title']) ?></a>
            </h2>
            <p class="post-excerpt flex-grow-1"><?= htmlspecialchars($p['excerpt'] ?? '') ?></p>
            <div class="d-flex align-items-center justify-content-between mt-3">
              <span class="read-time"><i class="far fa-clock me-1"></i><?= (int)$p['reading_time_minutes'] ?> min read</span>
              <a href="<?= $post_url ?>" class="read-more">Read more <i class="fas fa-arrow-right"></i></a>
            </div>
          </div>
        </article>
      </div>
    <?php endforeach ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <nav class="mt-5 d-flex justify-content-center">
      <ul class="pagination">
        <?php if ($page > 1): ?>
          <li class="page-item">
            <a class="page-link" href="?page=<?= $page-1 ?><?= $category ? '&cat='.urlencode($category) : '' ?>">
              <i class="fas fa-chevron-left"></i>
            </a>
          </li>
        <?php endif ?>
        <?php for ($n = 1; $n <= $total_pages; $n++): ?>
          <li class="page-item <?= $n === $page ? 'active' : '' ?>">
            <a class="page-link" href="?page=<?= $n ?><?= $category ? '&cat='.urlencode($category) : '' ?>"><?= $n ?></a>
          </li>
        <?php endfor ?>
        <?php if ($page < $total_pages): ?>
          <li class="page-item">
            <a class="page-link" href="?page=<?= $page+1 ?><?= $category ? '&cat='.urlencode($category) : '' ?>">
              <i class="fas fa-chevron-right"></i>
            </a>
          </li>
        <?php endif ?>
      </ul>
    </nav>
    <?php endif ?>
  <?php endif ?>
</main>

<!-- FOOTER CTA -->
<section class="footer-cta py-5 text-center">
  <div class="container">
    <h3>Ready to modernise your school?</h3>
    <p class="text-muted mb-4">Join hundreds of Ghanaian schools using EduTrack to save time and reduce admin work.</p>
    <a href="<?= CTA_PRIMARY_URL ?>" class="btn btn-primary btn-lg px-5 me-2" target="_blank"><?= CTA_PRIMARY_TEXT ?></a>
    <a href="<?= CTA_WHATSAPP_URL ?>" class="btn btn-outline-success btn-lg px-4" target="_blank">
      <i class="fab fa-whatsapp me-1"></i><?= CTA_WHATSAPP_TEXT ?>
    </a>
  </div>
</section>

<!-- SITE FOOTER -->
<footer class="blog-footer text-center py-4">
  <div class="container">
    <p class="mb-1 small">&copy; <?= date('Y') ?> <a href="https://oricnetwork.com" target="_blank">ORIC Network Limited</a> &middot; All rights reserved.</p>
    <p class="small text-muted mb-0">
      <a href="<?= BLOG_BASE_URL ?>/sitemap.php">Sitemap</a> &middot;
      <a href="<?= BLOG_BASE_URL ?>/rss.php">RSS</a> &middot;
      <a href="https://edutrack.oricnetwork.com" target="_blank">EduTrack Home</a>
    </p>
  </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
