<?php

declare(strict_types=1);

/**
 * Community forum public routes.
 *
 * Included by the generated front controller with $uri (the base-stripped
 * request path) and APP_BASE in scope, BEFORE the default dashboard/alias/SEO
 * routing. It serves the forum home at "/" and question threads at
 * "/q/{id}/{slug}"; every other path returns so normal routing continues
 * (login, admin pages, generated CRUD, assets, …).
 */

if (!isset($uri)) {
    return;
}

// Community-branded auth pages (override the generic generated ones).
if ($uri === '/login')    { require __DIR__ . '/forum/login.php';    exit; }
if ($uri === '/register') { require __DIR__ . '/forum/register.php'; exit; }
if ($uri === '/verify')   { require __DIR__ . '/forum/verify.php';   exit; }
if ($uri === '/forgot-password') { require __DIR__ . '/forum/forgot-password.php'; exit; }
if ($uri === '/reset-password')  { require __DIR__ . '/forum/reset-password.php';  exit; }
if ($uri === '/two-factor')      { require __DIR__ . '/forum/two-factor.php';      exit; }

// Forum home — the public question list at the site root.
if ($uri === '/' || $uri === '') {
    require __DIR__ . '/forum/home.php';
    exit;
}

// Search results.
if ($uri === '/search') {
    require __DIR__ . '/forum/search.php';
    exit;
}

// Ask a question — GET shows the form, POST creates it (login-gated inside).
if ($uri === '/ask') {
    require __DIR__ . '/forum/ask.php';
    exit;
}

// Moderation dashboard — GET renders, POST acts (admin-gated + CSRF inside).
if ($uri === '/admin') {
    require __DIR__ . '/forum/admin.php';
    exit;
}

// Forum write actions (vote / accept) — POST only, CSRF + login gated inside.
if ($uri === '/forum/act' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    require __DIR__ . '/forum/action.php';
    exit;
}

// Post an answer — POST only, CSRF + login gated inside.
if ($uri === '/forum/answer' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    require __DIR__ . '/forum/answer.php';
    exit;
}

// Member profile — /u/{username} (usernames: letters, numbers, dot, dash, underscore).
if (preg_match('#^/u/([A-Za-z0-9_.-]{1,64})/?$#', (string) $uri, $mu)) {
    $GLOBALS['__forum_user'] = $mu[1];
    require __DIR__ . '/forum/profile.php';
    exit;
}

// Question thread — /q/{id}/{optional-slug}. The page 301s a wrong slug to
// the canonical one and renders the question with its answers + SEO meta.
if (preg_match('#^/q/(\d+)(?:/([A-Za-z0-9\-]*))?/?$#', (string) $uri, $m)) {
    $GLOBALS['__forum_qid']  = (int) $m[1];
    $GLOBALS['__forum_slug'] = $m[2] ?? '';
    require __DIR__ . '/forum/question.php';
    exit;
}

// Not a forum route → fall through to the app's default routing.
