<?php

declare(strict_types=1);

/**
 * Community search — "/search?q=…". Uses the platform's dialect-aware full-text
 * helper over question titles + bodies. With no query it shows recent questions
 * so the page is never empty. Results are no-indexed (thin/dynamic) but followed.
 */

require __DIR__ . '/_shell.php';

$b        = forum_base();
$query    = trim((string) ($_GET['q'] ?? ''));
$results  = [];
$tagMap   = [];
$isRecent = ($query === '');
$total    = 0;
$perPage  = 20;
$pageNo   = max(1, (int) ($_GET['page'] ?? 1));

// Columns + joins shared by the search and the recent fallback.
$cols = 'q.id, q.slug, q.title, q.body_md, q.vote_score, q.answer_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';
$joins = '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';

if ($query !== '') {
    // Robust multi-term search: each term (≥2 chars, up to 6) must appear in the
    // title, body, category name, OR one of the question's tags. Dialect-agnostic
    // (LIKE), so it works on every engine PPPHP supports; ranked title-first.
    $terms = array_slice(array_values(array_filter(
        preg_split('/\s+/', $query) ?: [],
        static fn ($t) => mb_strlen((string) $t) >= 2
    )), 0, 6);

    $conds  = ['q.deleted_at IS NULL'];
    $params = [];
    foreach ($terms as $t) {
        $like = '%' . $t . '%';
        $conds[] = '(q.title LIKE ? OR q.body_md LIKE ? OR c.name LIKE ? OR EXISTS ('
                 . 'SELECT 1 FROM qa_question_tags qt JOIN qa_tags tg ON tg.id = qt.tag_id '
                 . 'WHERE qt.question_id = q.id AND tg.name LIKE ?))';
        array_push($params, $like, $like, $like, $like);
    }
    if (!$terms) {                                   // query was only 1-char tokens
        $like = '%' . $query . '%';
        $conds[] = '(q.title LIKE ? OR q.body_md LIKE ?)';
        array_push($params, $like, $like);
    }
    $where = implode(' AND ', $conds);

    $total   = (int) (dbValue("SELECT COUNT(*) FROM qa_questions q LEFT JOIN qa_categories c ON c.id = q.category_id WHERE {$where}", $params) ?? 0);
    $maxPage = max(1, (int) ceil($total / $perPage));
    if ($pageNo > $maxPage) { $pageNo = $maxPage; }
    $offset  = ($pageNo - 1) * $perPage;

    // Title matches of the whole phrase float to the top, then score, then recency.
    $titleLike = '%' . $query . '%';
    $results = dbAll(
        "SELECT {$cols} {$joins}
          WHERE {$where}
          ORDER BY CASE WHEN q.title LIKE ? THEN 0 ELSE 1 END, q.vote_score DESC, q.last_activity_at DESC
          LIMIT {$perPage} OFFSET {$offset}",
        array_merge($params, [$titleLike])
    );
} else {
    $results = dbAll(
        "SELECT {$cols} {$joins}
          WHERE q.deleted_at IS NULL
          ORDER BY q.last_activity_at DESC
          LIMIT 8"
    );
}

if ($results) {
    $ids = array_map(static fn($r) => (int) $r['id'], $results);
    $ph  = implode(',', array_fill(0, count($ids), '?'));
    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 WHERE qt.question_id IN ($ph)", $ids) as $r) {
        $tagMap[(int) $r['qid']][] = (string) $r['name'];
    }
}

forum_head(($query !== '' ? forum_e($query) . ' — ' : '') . 'Search — PPPHP Community', '<meta name="robots" content="noindex,follow">');
?>
<a class="fx-back" href="<?= $b ?>/"><i class="bi bi-arrow-left"></i> All questions</a>
<h1 class="fx-h1">Search</h1>
<p class="fx-sub"><?= $query !== '' ? number_format($total) . ' result' . ($total === 1 ? '' : 's') . ' for “' . forum_e($query) . '”' : 'Find questions across the community' ?></p>
<?php forum_searchbox($query, $b); ?>

<?php if ($query !== '' && !$results): ?>
  <div class="fx-empty"><i class="bi bi-search" style="font-size:34px;opacity:.4"></i>
    <p>No questions matched “<?= forum_e($query) ?>”.</p>
    <p><a class="fx-tag" href="<?= $b ?>/ask">Ask this question →</a></p></div>
<?php elseif ($results): ?>
  <?php if ($isRecent): ?><h2 class="fx-answers-h" style="margin:6px 0 14px;font-size:16px">Recent questions</h2><?php endif; ?>
  <div class="fx-list">
    <?php foreach ($results as $q) forum_qcard($q, $tagMap[(int) $q['id']] ?? [], $b); ?>
  </div>
  <?php if ($query !== '') forum_pagination($pageNo, $perPage, $total, $b . '/search', ['q' => $query]); ?>
<?php endif; ?>
<?php forum_foot(); ?>
