<?php

declare(strict_types=1);

/**
 * Public community home — the question list, styled as a forum.
 * Reached at the app root ("/") via public-routes.php. Read-only + anonymous;
 * writing (Ask / answer) links to the login-gated generated pages.
 */

require __DIR__ . '/_shell.php';

$b = forum_base();

// Optional category filter (?cat=slug).
$catSlug   = preg_replace('/[^a-z0-9-]/', '', strtolower((string) ($_GET['cat'] ?? '')));
$activeCat = ($catSlug !== '') ? dbRow('SELECT id, name FROM qa_categories WHERE slug = ?', [$catSlug]) : null;
$where  = 'q.deleted_at IS NULL';
$params = [];
if ($activeCat) { $where .= ' AND q.category_id = ?'; $params[] = (int) $activeCat['id']; }

// Sort / filter tabs (?sort=newest|top|unanswered).
$sort = (string) ($_GET['sort'] ?? 'newest');
if (!in_array($sort, ['newest', 'top', 'unanswered'], true)) { $sort = 'newest'; }
if ($sort === 'unanswered') { $where .= ' AND q.answer_count = 0 AND q.accepted_answer_id IS NULL'; }
$orderBy = $sort === 'top' ? 'q.vote_score DESC, q.last_activity_at DESC' : 'q.last_activity_at DESC';

$total = (int) (dbValue("SELECT COUNT(*) FROM qa_questions q WHERE {$where}", $params) ?? 0);

// Pagination — 20 per page, windowed pager preserves ?cat= and ?sort=.
$perPage = 20;
$pageNo  = max(1, (int) ($_GET['page'] ?? 1));
$maxPage = max(1, (int) ceil($total / $perPage));
if ($pageNo > $maxPage) { $pageNo = $maxPage; }
$offset  = ($pageNo - 1) * $perPage;

$questions = dbAll(
    "SELECT q.id, q.slug, q.title, q.body_md, q.vote_score, q.answer_count,
            q.view_count, q.accepted_answer_id, q.last_activity_at,
            c.name AS cat_name, u.display_name AS author,
            u.username AS author_username, u.reputation AS author_rep, u.email AS author_email
       FROM qa_questions q
       LEFT JOIN qa_categories c ON c.id = q.category_id
       LEFT JOIN qa_users u      ON u.id = q.author_id
      WHERE {$where}
      ORDER BY {$orderBy}
      LIMIT {$perPage} OFFSET {$offset}", $params
);
$categories = dbAll('SELECT slug, name FROM qa_categories ORDER BY sort_order, name');

// Tags grouped by question (one query).
$tagMap = [];
foreach (dbAll('SELECT qt.question_id AS qid, t.name AS name
                  FROM qa_question_tags qt JOIN qa_tags t ON t.id = qt.tag_id') as $r) {
    $tagMap[(int) $r['qid']][] = (string) $r['name'];
}

// Self-canonical (root) + description so the home page indexes cleanly. Filtered
// views (?cat=) point their canonical at the root and are no-indexed to avoid
// thin/duplicate category pages competing with the main list.
$sch  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$canon = isset($_SERVER['HTTP_HOST']) ? $sch . '://' . $_SERVER['HTTP_HOST'] . $b . '/' : $b . '/';
$homeMeta = '<link rel="canonical" href="' . forum_e($canon) . '">'
    . '<meta name="description" content="Questions and answers from the PPPHP community — building database-driven apps, connecting databases, deployment and customisation.">'
    . '<meta property="og:title" content="PPPHP Community — Questions &amp; Answers"><meta property="og:type" content="website">'
    . (($activeCat || $sort !== 'newest') ? '<meta name="robots" content="noindex,follow">' : '');

forum_head(($activeCat ? forum_e($activeCat['name']) . ' — ' : '') . 'Community Questions — PPPHP', $homeMeta);
?>
<?php
// Preserve ?cat= when switching sort, and vice-versa.
$catQ  = $activeCat ? '&cat=' . rawurlencode($catSlug) : '';
$sortQ = $sort !== 'newest' ? '&sort=' . $sort : '';
$sortUrl = static function (string $s) use ($b, $catQ): string {
    $q = ($s !== 'newest' ? 'sort=' . $s : '') . $catQ;
    return $b . '/' . ($q !== '' ? '?' . ltrim($q, '&') : '');
};
?>
<?php if (forum_is_suspended()): ?>
  <div class="fx-suspended"><i class="bi bi-slash-circle"></i> Your account is suspended — you can read the community but can't post, answer or vote. Contact an administrator if you think this is a mistake.</div>
<?php endif; ?>
<div class="fx-headrow">
  <div>
    <h1 class="fx-h1"><?= $activeCat ? forum_e($activeCat['name']) : 'All Questions' ?></h1>
    <p class="fx-sub"><?= number_format($total) ?> question<?= $total === 1 ? '' : 's' ?><?= $activeCat ? ' in this category' : ' from the PPPHP community' ?></p>
  </div>
  <nav class="fx-sorts" aria-label="Sort questions">
    <a class="fx-sort<?= $sort === 'newest' ? ' on' : '' ?>" href="<?= $sortUrl('newest') ?>"><i class="bi bi-clock-history"></i> Newest</a>
    <a class="fx-sort<?= $sort === 'top' ? ' on' : '' ?>" href="<?= $sortUrl('top') ?>"><i class="bi bi-fire"></i> Top</a>
    <a class="fx-sort<?= $sort === 'unanswered' ? ' on' : '' ?>" href="<?= $sortUrl('unanswered') ?>"><i class="bi bi-patch-question"></i> Unanswered</a>
  </nav>
</div>
<div class="fx-cats">
  <a class="fx-catchip<?= $activeCat ? '' : ' on' ?>" href="<?= $b ?>/<?= $sortQ ? '?' . ltrim($sortQ, '&') : '' ?>">All</a>
  <?php foreach ($categories as $c): ?>
    <a class="fx-catchip<?= ($activeCat && $catSlug === $c['slug']) ? ' on' : '' ?>" href="<?= $b ?>/?cat=<?= forum_e($c['slug']) . $sortQ ?>"><?= forum_e($c['name']) ?></a>
  <?php endforeach; ?>
</div>
<?php if (!$questions): ?>
  <div class="fx-empty"><i class="bi bi-chat-square-text" style="font-size:34px;opacity:.4"></i>
    <p><?= $sort === 'unanswered' ? 'No unanswered questions right now — every question has an answer. 🎉' : ($activeCat ? 'No questions in this category yet.' : 'No questions yet. Be the first to ask!') ?></p>
    <?php if ($sort === 'unanswered' || $activeCat): ?><p><a class="fx-tag" href="<?= $b ?>/">← Back to all questions</a></p><?php endif; ?></div>
<?php else: ?>
<div class="fx-list">
  <?php foreach ($questions as $q) forum_qcard($q, $tagMap[(int) $q['id']] ?? [], $b); ?>
</div>
<?php
// Windowed pager, carrying the active category + sort across pages.
$pgExtra = [];
if ($activeCat) { $pgExtra['cat'] = $catSlug; }
if ($sort !== 'newest') { $pgExtra['sort'] = $sort; }
forum_pagination($pageNo, $perPage, $total, $b . '/', $pgExtra);
?>
<?php endif; ?>
<?php forum_foot(); ?>
