<?php
/**
 * GreenAlsoGreen Blog — Public Front Controller
 * Routes: ?post=slug | ?category=slug | ?tag=slug | (default) listing
 */
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';

// ─── Routing ──────────────────────────────────────────────────────────────────
$view  = '';
$slug  = '';
$data  = [];

if (!empty($_GET['post'])) {
    $view = 'post';
    $slug = trim($_GET['post']);
} elseif (!empty($_GET['category'])) {
    $view = 'category';
    $slug = trim($_GET['category']);
} elseif (!empty($_GET['tag'])) {
    $view = 'tag';
    $slug = trim($_GET['tag']);
} else {
    $view = 'listing';
}

$siteName    = get_setting('site.name', SITE_NAME);
$siteTagline = get_setting('site.tagline', '');
$postsPerPage = (int) get_setting('reading.posts_per_page', POSTS_PER_PAGE);
$page         = max(1, (int)($_GET['page'] ?? 1));

// ─── Single Post ──────────────────────────────────────────────────────────────
if ($view === 'post') {
    $post = db_row(
        "SELECT p.*, u.display_name AS author_name, u.username AS author_slug
         FROM posts p LEFT JOIN users u ON u.id = p.author_id
         WHERE p.slug = ? AND p.status = 'published' AND p.deleted_at IS NULL",
        [$slug]
    );
    if (!$post) {
        http_response_code(404);
        $pageTitle = '404 Not Found';
        blog_head($pageTitle, $siteName, $siteTagline);
        echo '<div class="container py-5 text-center"><h1>Post not found</h1><p><a href="<?= SITE_URL ?>">← Back to blog</a></p></div>';
        blog_foot();
        exit;
    }

    $categories = post_categories($post['id']);
    $tags       = post_tags($post['id']);
    $featImgUrl = $post['featured_image_id'] ? media_url($post['featured_image_id']) : '';
    $pageTitle  = $post['meta_title'] ?: $post['title'];
    $metaDesc   = $post['meta_description'] ?: $post['excerpt'];
    $ogImg      = $post['og_image_id'] ? media_url($post['og_image_id']) : $featImgUrl;

    // Related posts (same primary category, different post)
    $related = $post['primary_category_id'] ? db_query(
        "SELECT p.id, p.title, p.slug, p.excerpt, p.published_at, p.featured_image_id,
                p.reading_time_minutes
         FROM posts p
         WHERE p.primary_category_id = ? AND p.id != ? AND p.status = 'published' AND p.deleted_at IS NULL
         ORDER BY p.published_at DESC LIMIT 3",
        [$post['primary_category_id'], $post['id']]
    ) : [];

    blog_head($pageTitle, $siteName, $siteTagline, $metaDesc, $ogImg, $post['canonical_url'] ?: null);
    ?>
    <main class="post-single">
      <div class="container">
        <article class="post-article" itemscope itemtype="https://schema.org/Article">

          <!-- Post header -->
          <header class="post-header">
            <?php if ($categories): ?>
            <div class="post-cats">
              <?php foreach ($categories as $cat): ?>
                <a href="<?= category_url($cat['slug']) ?>" class="post-cat-tag"><?= h($cat['name']) ?></a>
              <?php endforeach ?>
            </div>
            <?php endif ?>

            <h1 class="post-title" itemprop="headline"><?= h($post['title']) ?></h1>

            <?php if ($post['excerpt']): ?>
              <p class="post-subtitle"><?= h($post['excerpt']) ?></p>
            <?php endif ?>

            <div class="post-meta">
              <span class="post-author" itemprop="author"><?= h($post['author_name']) ?></span>
              <span class="post-meta-sep">·</span>
              <time datetime="<?= h($post['published_at']) ?>" itemprop="datePublished">
                <?= format_date($post['published_at'], 'F j, Y') ?>
              </time>
              <?php if ($post['reading_time_minutes']): ?>
                <span class="post-meta-sep">·</span>
                <span><?= $post['reading_time_minutes'] ?> min read</span>
              <?php endif ?>
            </div>
          </header>

          <!-- Featured image -->
          <?php if ($featImgUrl): ?>
          <figure class="post-hero-image">
            <img src="<?= h($featImgUrl) ?>" alt="<?= h($post['title']) ?>" loading="eager">
          </figure>
          <?php endif ?>

          <!-- Body -->
          <div class="post-body" itemprop="articleBody">
            <?= $post['body'] /* Already sanitized on save */ ?>
          </div>

          <!-- Tags -->
          <?php if ($tags): ?>
          <div class="post-tags">
            <?php foreach ($tags as $tag): ?>
              <a href="<?= tag_url($tag['slug']) ?>" class="post-tag"><?= h($tag['name']) ?></a>
            <?php endforeach ?>
          </div>
          <?php endif ?>

        </article><!-- /article -->

        <!-- Related posts -->
        <?php if ($related): ?>
        <section class="related-posts">
          <h2 class="related-posts-title">Related Articles</h2>
          <div class="post-grid post-grid--3">
            <?php foreach ($related as $rp): ?>
              <?php render_post_card($rp) ?>
            <?php endforeach ?>
          </div>
        </section>
        <?php endif ?>

      </div><!-- /container -->
    </main>

    <?php
    blog_foot();
    exit;
}

// ─── Category Archive ─────────────────────────────────────────────────────────
if ($view === 'category') {
    $cat = db_row("SELECT * FROM categories WHERE slug = ?", [$slug]);
    if (!$cat) {
        http_response_code(404);
        blog_head('Not Found', $siteName, $siteTagline);
        echo '<div class="container py-5 text-center"><h1>Category not found</h1><p><a href="<?= SITE_URL ?>">← Back to blog</a></p></div>';
        blog_foot(); exit;
    }

    $total = (int) db_val(
        "SELECT COUNT(DISTINCT p.id) FROM posts p
         INNER JOIN post_categories pc ON pc.post_id=p.id
         WHERE pc.category_id=? AND p.status='published' AND p.deleted_at IS NULL",
        [$cat['id']]
    );
    $pg = paginate($total, $postsPerPage, $page);
    $posts = db_query(
        "SELECT DISTINCT p.id, p.title, p.slug, p.excerpt, p.published_at, p.featured_image_id,
                p.reading_time_minutes, p.primary_category_id,
                u.display_name AS author_name
         FROM posts p
         INNER JOIN post_categories pc ON pc.post_id=p.id
         LEFT JOIN users u ON u.id=p.author_id
         WHERE pc.category_id=? AND p.status='published' AND p.deleted_at IS NULL
         ORDER BY p.published_at DESC
         LIMIT ? OFFSET ?",
        [$cat['id'], $postsPerPage, $pg['offset']]
    );

    $pageTitle = $cat['meta_title'] ?: ($cat['name'] . ' — ' . $siteName);
    blog_head($pageTitle, $siteName, $siteTagline, $cat['meta_description'] ?: '');
    ?>
    <main class="archive-page">
      <div class="container">
        <header class="archive-header">
          <div class="archive-eyebrow">Category</div>
          <h1 class="archive-title"><?= h($cat['name']) ?></h1>
          <?php if ($cat['description']): ?>
            <p class="archive-description"><?= h($cat['description']) ?></p>
          <?php endif ?>
        </header>
        <div class="post-grid">
          <?php foreach ($posts as $p): render_post_card($p); endforeach ?>
        </div>
        <?php pagination_links($pg, ['category' => $slug]) ?>
      </div>
    </main>
    <?php
    blog_foot(); exit;
}

// ─── Tag Archive ──────────────────────────────────────────────────────────────
if ($view === 'tag') {
    $tag = db_row("SELECT * FROM tags WHERE slug = ?", [$slug]);
    if (!$tag) {
        http_response_code(404);
        blog_head('Not Found', $siteName, $siteTagline);
        echo '<div class="container py-5 text-center"><h1>Tag not found</h1><p><a href="<?= SITE_URL ?>">← Back to blog</a></p></div>';
        blog_foot(); exit;
    }

    $total = (int) db_val(
        "SELECT COUNT(*) FROM post_tags pt INNER JOIN posts p ON p.id=pt.post_id
         WHERE pt.tag_id=? AND p.status='published' AND p.deleted_at IS NULL",
        [$tag['id']]
    );
    $pg = paginate($total, $postsPerPage, $page);
    $posts = db_query(
        "SELECT p.id, p.title, p.slug, p.excerpt, p.published_at, p.featured_image_id,
                p.reading_time_minutes, u.display_name AS author_name
         FROM posts p
         INNER JOIN post_tags pt ON pt.post_id=p.id
         LEFT JOIN users u ON u.id=p.author_id
         WHERE pt.tag_id=? AND p.status='published' AND p.deleted_at IS NULL
         ORDER BY p.published_at DESC LIMIT ? OFFSET ?",
        [$tag['id'], $postsPerPage, $pg['offset']]
    );

    blog_head('Tag: ' . $tag['name'] . ' — ' . $siteName, $siteName, $siteTagline);
    ?>
    <main class="archive-page">
      <div class="container">
        <header class="archive-header">
          <div class="archive-eyebrow">Tag</div>
          <h1 class="archive-title">#<?= h($tag['name']) ?></h1>
        </header>
        <div class="post-grid">
          <?php foreach ($posts as $p): render_post_card($p); endforeach ?>
        </div>
        <?php pagination_links($pg, ['tag' => $slug]) ?>
      </div>
    </main>
    <?php
    blog_foot(); exit;
}

// ─── Blog Listing (default) ───────────────────────────────────────────────────
$featuredPost = db_row(
    "SELECT p.id, p.title, p.slug, p.excerpt, p.published_at, p.featured_image_id,
            p.reading_time_minutes, p.primary_category_id,
            u.display_name AS author_name
     FROM posts p LEFT JOIN users u ON u.id=p.author_id
     WHERE p.featured=1 AND p.status='published' AND p.deleted_at IS NULL
     ORDER BY p.published_at DESC LIMIT 1"
);

$total = (int) db_val("SELECT COUNT(*) FROM posts WHERE status='published' AND deleted_at IS NULL AND featured=0");
$pg    = paginate($total + ($featuredPost && $page === 1 ? 0 : 0), $postsPerPage, $page);

// On page 1 with a featured post, show one fewer regular post
$limit  = $postsPerPage - ($featuredPost && $page === 1 ? 1 : 0);
$offset = $pg['offset'];

$posts = db_query(
    "SELECT p.id, p.title, p.slug, p.excerpt, p.published_at, p.featured_image_id,
            p.reading_time_minutes, p.primary_category_id,
            u.display_name AS author_name
     FROM posts p LEFT JOIN users u ON u.id=p.author_id
     WHERE p.status='published' AND p.deleted_at IS NULL
       AND (? = 0 OR p.id != ?)
     ORDER BY p.published_at DESC
     LIMIT ? OFFSET ?",
    [$featuredPost ? $featuredPost['id'] : 0, $featuredPost ? $featuredPost['id'] : 0,
     max(1, $limit), $offset]
);

$categories = db_query("SELECT * FROM categories WHERE post_count > 0 ORDER BY post_count DESC LIMIT 10");

$pageTitle = $page > 1 ? "$siteName — Page $page" : $siteName;
$metaDesc  = $siteTagline ?: get_setting('seo.default_meta_description', '');

blog_head($pageTitle, $siteName, $siteTagline, $metaDesc);
?>

<main class="blog-listing">
  <div class="container">

    <!-- Hero / Featured Post -->
    <?php if ($featuredPost && $page === 1): ?>
    <section class="hero-post">
      <?php $fImg = $featuredPost['featured_image_id'] ? media_url($featuredPost['featured_image_id']) : ''; ?>
      <?php if ($fImg): ?>
      <div class="hero-post-image">
        <img src="<?= h($fImg) ?>" alt="<?= h($featuredPost['title']) ?>" loading="eager">
      </div>
      <?php endif ?>
      <div class="hero-post-content">
        <span class="hero-post-eyebrow">Featured Article</span>
        <h2 class="hero-post-title">
          <a href="<?= post_url($featuredPost['slug']) ?>"><?= h($featuredPost['title']) ?></a>
        </h2>
        <?php if ($featuredPost['excerpt']): ?>
        <p class="hero-post-excerpt"><?= h($featuredPost['excerpt']) ?></p>
        <?php endif ?>
        <div class="hero-post-meta">
          <span><?= h($featuredPost['author_name']) ?></span>
          <span class="sep">·</span>
          <time><?= format_date($featuredPost['published_at']) ?></time>
          <?php if ($featuredPost['reading_time_minutes']): ?>
          <span class="sep">·</span><span><?= $featuredPost['reading_time_minutes'] ?> min</span>
          <?php endif ?>
        </div>
        <a href="<?= post_url($featuredPost['slug']) ?>" class="btn-read-more">Read article →</a>
      </div>
    </section>
    <?php endif ?>

    <!-- Main grid + sidebar -->
    <div class="listing-layout">

      <!-- Posts grid -->
      <div class="listing-main">
        <?php if ($page > 1): ?>
          <h2 class="listing-page-header">Page <?= $page ?></h2>
        <?php endif ?>

        <?php if ($posts): ?>
        <div class="post-grid">
          <?php foreach ($posts as $p): render_post_card($p); endforeach ?>
        </div>
        <?php else: ?>
        <div class="empty-listing">
          <p>No posts published yet. Check back soon.</p>
        </div>
        <?php endif ?>

        <?php pagination_links($pg) ?>
      </div>

      <!-- Sidebar -->
      <aside class="listing-sidebar">
        <?php if ($categories): ?>
        <div class="sidebar-widget">
          <h3 class="sidebar-widget-title">Topics</h3>
          <ul class="sidebar-cat-list">
            <?php foreach ($categories as $cat): ?>
            <li>
              <a href="<?= category_url($cat['slug']) ?>"><?= h($cat['name']) ?></a>
              <span class="sidebar-cat-count"><?= $cat['post_count'] ?></span>
            </li>
            <?php endforeach ?>
          </ul>
        </div>
        <?php endif ?>

        <div class="sidebar-widget sidebar-widget--newsletter">
          <h3 class="sidebar-widget-title">Stay Updated</h3>
          <p class="sidebar-widget-desc">Get weekly sustainability insights in your inbox.</p>
          <div class="newsletter-form-wrap">
            <form class="newsletter-form">
              <input type="text" name="first_name" placeholder="First name" class="newsletter-input" required>
              <input type="email" name="email" placeholder="your@email.com" class="newsletter-input" required>
              <button type="submit" class="newsletter-btn">Subscribe</button>
            </form>
          </div>
          <script>(function(){
            var wrap = document.currentScript.parentElement;
            var form = wrap.querySelector('.newsletter-form');
            form.addEventListener('submit', function(e){
              e.preventDefault();
              fetch('newsletter-subscribe.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: new URLSearchParams(new FormData(form)).toString()
              })
              .then(function(r){ return r.json(); })
              .then(function(res){
                if (res.ok) wrap.innerHTML = '<p class="newsletter-success">Your subscription has been received.</p>';
              });
            });
          })();</script>
        </div>
      </aside>

    </div><!-- /listing-layout -->
  </div><!-- /container -->
</main>

<?php
blog_foot();

// ─── Template helpers ─────────────────────────────────────────────────────────

function blog_head(string $title, string $siteName, string $tagline, string $metaDesc = '', string $ogImg = '', ?string $canonical = null): void {
    $noindex   = (bool) get_setting('seo.disable_indexing', false);
    $parentUrl = '..';
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h($title) ?></title>
  <?php if ($metaDesc): ?><meta name="description" content="<?= h($metaDesc) ?>"><?php endif ?>
  <?php if ($noindex): ?><meta name="robots" content="noindex,nofollow"><?php endif ?>
  <?php if ($canonical): ?><link rel="canonical" href="<?= h($canonical) ?>"><?php endif ?>
  <meta property="og:title" content="<?= h($title) ?>">
  <?php if ($metaDesc): ?><meta property="og:description" content="<?= h($metaDesc) ?>"><?php endif ?>
  <?php if ($ogImg): ?><meta property="og:image" content="<?= h($ogImg) ?>"><?php endif ?>
  <meta property="og:site_name" content="<?= h($siteName) ?>">
  <!-- Shared site styles (fonts, icons, Bootstrap, base theme) -->
  <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=DM+Sans:ital,wght@0,400;0,500;0,700;1,400&family=JetBrains+Mono&display=swap" rel="stylesheet">
  <link href="<?= $parentUrl ?>/css/font-awesome.min.css" rel="stylesheet">
  <link href="<?= $parentUrl ?>/css/plugins.css" rel="stylesheet">
  <link href="<?= $parentUrl ?>/css/style.css" rel="stylesheet">
  <link href="<?= $parentUrl ?>/css/responsive.css" rel="stylesheet">
  <!-- Blog-specific layout styles (post cards, article body, listing grid) -->
  <link rel="stylesheet" href="assets/css/blog.css">
</head>
<body>

<!-- PRELOADER -->
<div class="preloader">
  <div class="spinner">
    <div class="double-bounce1"></div>
    <div class="double-bounce2"></div>
  </div>
</div>

<!-- NAVBAR -->
<nav class="navbar navbar-expand-md navbar-light sticky-top" id="mainNav">
  <div class="container">
    <a class="navbar-brand js-scroll logo" href="<?= $parentUrl ?>/home.php">
      <img src="<?= $parentUrl ?>/gfx/logo.webp" alt="GreenAlsoGreen logo" class="navbar-logo">
      <?= h($siteName) ?>
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse"
            data-bs-target="#navbarBlog" aria-controls="navbarBlog"
            aria-expanded="false" aria-label="Toggle navigation">
      <span></span><span></span><span></span>
    </button>
    <div class="collapse navbar-collapse justify-content-end" id="navbarBlog">
      <ul class="navbar-nav main_menu">
        <li class="nav-item">
          <a class="nav-link" href="<?= $parentUrl ?>/home.php#hero-area">
            <span data-hover="Home">Home</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?= $parentUrl ?>/about-me.php#about">
            <span data-hover="About Me">About Me</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="./">
            <span data-hover="Blog">Blog</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?= BASE_URL ?>/podcast">
            <span data-hover="Podcast">Podcast</span>
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="<?= $parentUrl ?>/about-me.php#contact">
            <span data-hover="Contact">Contact</span>
          </a>
        </li>
      </ul>
    </div>
  </div>
</nav>

    <?php
}

function blog_foot(): void {
    $parentUrl = '..';
    ?>

<!-- FOOTER -->
<div class="footer">
  <div class="container">
    <div class="copy-text">
      <p>Copyright &copy; GreenAlsoGreen. All rights reserved <?= date('Y') ?></p>
    </div>
  </div>
</div>

<script src="<?= $parentUrl ?>/js/jquery.min.js"></script>
<script src="<?= $parentUrl ?>/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {

  /* Preloader — matches main.js behaviour */
  $('.spinner').fadeOut();
  $('.preloader').delay(350).fadeOut('slow');

  /* Navbar scroll: toggle navbar-reduce past 50px (white bg + shadow + slideDown animation) */
  function updateNav() {
    if ($(window).scrollTop() > 50) {
      $('#mainNav').addClass('navbar-reduce').removeClass('navbar-trans');
    } else {
      $('#mainNav').removeClass('navbar-reduce').addClass('navbar-trans');
    }
  }
  $(window).on('scroll', updateNav);
  updateNav(); // set correct state on page load

  /* Mobile: ensure navbar gets solid bg when the hamburger opens */
  $('.navbar-toggler').on('click', function () {
    if (!$('#mainNav').hasClass('navbar-reduce')) {
      $('#mainNav').addClass('navbar-reduce');
    }
  });

});
</script>
</body>
</html>
    <?php
}

function render_post_card(array $p): void {
    $imgUrl = $p['featured_image_id'] ? media_url($p['featured_image_id']) : '';
    $cats   = post_categories($p['id']);
    ?>
    <article class="post-card">
      <?php if ($imgUrl): ?>
      <a href="<?= post_url($p['slug']) ?>" class="post-card-image-link" tabindex="-1" aria-hidden="true">
        <img src="<?= h($imgUrl) ?>" alt="<?= h($p['title']) ?>" class="post-card-image" loading="lazy">
      </a>
      <?php endif ?>
      <div class="post-card-body">
        <?php if ($cats): ?>
        <div class="post-card-cats">
          <a href="<?= category_url($cats[0]['slug']) ?>" class="post-card-cat"><?= h($cats[0]['name']) ?></a>
        </div>
        <?php endif ?>
        <h3 class="post-card-title">
          <a href="<?= post_url($p['slug']) ?>"><?= h($p['title']) ?></a>
        </h3>
        <?php if ($p['excerpt']): ?>
        <p class="post-card-excerpt"><?= h(make_excerpt($p['excerpt'], 130)) ?></p>
        <?php endif ?>
        <div class="post-card-meta">
          <span><?= h($p['author_name'] ?? '') ?></span>
          <span class="sep">·</span>
          <time><?= format_date($p['published_at']) ?></time>
          <?php if (!empty($p['reading_time_minutes'])): ?>
          <span class="sep">·</span>
          <span><?= $p['reading_time_minutes'] ?> min</span>
          <?php endif ?>
        </div>
      </div>
    </article>
    <?php
}

function pagination_links(array $pg, array $extra = []): void {
    if ($pg['total_pages'] <= 1) return;
    $params = array_merge($extra, []);
    ?>
    <nav class="pagination-nav" aria-label="Pagination">
      <?php if ($pg['has_prev']): ?>
        <a href="?<?= http_build_query(array_merge($params, ['page' => $pg['prev']])) ?>" class="pagination-link">← Newer</a>
      <?php endif ?>
      <span class="pagination-info">Page <?= $pg['current'] ?> of <?= $pg['total_pages'] ?></span>
      <?php if ($pg['has_next']): ?>
        <a href="?<?= http_build_query(array_merge($params, ['page' => $pg['next']])) ?>" class="pagination-link">Older →</a>
      <?php endif ?>
    </nav>
    <?php
}
