<?php
// api/news_comments.php

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/news_common.php';

try {
    rvu_ensure_news_tables($pdo);
    $user = rvu_news_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $newsId = (int)($_GET['news_id'] ?? 0);
        if ($newsId <= 0) rvu_news_json(['detail' => 'A valid news_id is required.'], 422);
        rvu_news_json(['data' => rvu_news_fetch_comments($pdo, $newsId)]);
    }

    if ($method === 'POST') {
        $input = rvu_news_input();
        $newsId = (int)($input['news_id'] ?? 0);
        $comment = trim((string)($input['comment'] ?? ''));
        $parentCommentId = isset($input['parent_comment_id']) ? (int)$input['parent_comment_id'] : null;
        $mentionUserIds = isset($input['mention_user_ids']) && is_array($input['mention_user_ids'])
            ? array_values(array_unique(array_filter(array_map('intval', $input['mention_user_ids']), fn($id) => $id > 0)))
            : [];

        if ($newsId <= 0) rvu_news_json(['detail' => 'A valid news article is required.'], 422);
        if ($comment === '') rvu_news_json(['detail' => 'Comment cannot be empty.'], 422);
        if (mb_strlen($comment) > 1000) rvu_news_json(['detail' => 'Comment cannot exceed 1,000 characters.'], 422);

        $article = rvu_news_fetch_article($pdo, $newsId, (int)$user['id']);
        if (!$article || $article['status'] !== 'published') {
            rvu_news_json(['detail' => 'Published news article not found.'], 404);
        }

        $parent = null;
        if ($parentCommentId !== null && $parentCommentId > 0) {
            $parentStmt = $pdo->prepare('SELECT id, news_id, user_id FROM campus_news_comments WHERE id = ? LIMIT 1');
            $parentStmt->execute([$parentCommentId]);
            $parent = $parentStmt->fetch(PDO::FETCH_ASSOC) ?: null;
            if (!$parent || (int)$parent['news_id'] !== $newsId) {
                rvu_news_json(['detail' => 'The reply target is invalid.'], 422);
            }
        } else {
            $parentCommentId = null;
        }

        $stmt = $pdo->prepare('INSERT INTO campus_news_comments (news_id, user_id, parent_comment_id, comment) VALUES (?, ?, ?, ?) RETURNING id');
        $stmt->execute([$newsId, (int)$user['id'], $parentCommentId, $comment]);
        $commentId = (int)$stmt->fetchColumn();

        if ($mentionUserIds) {
            $mentionStmt = $pdo->prepare('INSERT INTO campus_news_comment_mentions (comment_id, mentioned_user_id) VALUES (?, ?) ON CONFLICT DO NOTHING');
            foreach ($mentionUserIds as $mentionedUserId) {
                if ($mentionedUserId !== (int)$user['id']) {
                    $mentionStmt->execute([$commentId, $mentionedUserId]);
                }
            }
        }

        if ($parent) {
            rvu_news_create_notification($pdo, (int)$parent['user_id'], (int)$user['id'], $newsId, $commentId, 'reply');
        } else {
            rvu_news_create_notification($pdo, (int)$article['author_id'], (int)$user['id'], $newsId, $commentId, 'comment');
        }

        foreach ($mentionUserIds as $mentionedUserId) {
            rvu_news_create_notification($pdo, $mentionedUserId, (int)$user['id'], $newsId, $commentId, 'mention');
        }

        rvu_news_json(['comment' => rvu_news_fetch_comment($pdo, $commentId)], 201);
    }

    rvu_news_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'News comments server error: ' . $e->getMessage()], 500);
}
