<?php

declare(strict_types=1);

/**
 * Post an answer — POST /forum/answer from the thread's answer form. Login +
 * CSRF gated; creates a qa_answers row (author via the forum identity bridge),
 * refreshes the question's answer_count + last_activity_at, then redirects back
 * to the thread anchored on the new answer.
 */

require __DIR__ . '/_shell.php';

use PpPhp\Core\Security;
use PpPhp\Core\DB;

$b    = forum_base();
$uid  = forum_author_id();
$qid  = (int) ($_POST['question_id'] ?? 0);
$body = trim((string) ($_POST['body'] ?? ''));

if (!$uid) {
    header('Location: ' . $b . '/login');
    exit;
}
$q = $qid > 0 ? dbRow('SELECT id, slug FROM qa_questions WHERE id = ? AND deleted_at IS NULL', [$qid]) : null;
if (!$q) {
    header('Location: ' . $b . '/');
    exit;
}
$dest = $b . '/q/' . $qid . '/' . (string) ($q['slug'] ?? '');

// Suspended members can browse but not answer.
if (forum_is_suspended()) {
    header('Location: ' . $dest . '?e=suspended#answer-form');
    exit;
}

if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
    header('Location: ' . $dest . '?e=session#answer-form');
    exit;
}
if (mb_strlen($body) < 15) {
    header('Location: ' . $dest . '?e=short#answer-form');
    exit;
}

DB::Insert('qa_answers', ['question_id' => $qid, 'author_id' => $uid, 'body_md' => $body]);
$aid = (int) dbValue('SELECT id FROM qa_answers WHERE question_id = ? AND author_id = ? ORDER BY id DESC LIMIT 1', [$qid, $uid]);
DB::Query(
    'UPDATE qa_questions
        SET answer_count = (SELECT COUNT(*) FROM qa_answers WHERE question_id = ? AND deleted_at IS NULL),
            last_activity_at = NOW()
      WHERE id = ?',
    [$qid, $qid]
);

header('Location: ' . $dest . '#a' . $aid);
exit;
