<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/events_common.php';

try {
    rvu_ensure_event_social_tables($pdo);
    $user = rvu_event_require_user($pdo);
    $userId = (int)$user['id'];
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $eventId = (int)($_GET['event_id'] ?? 0);
        if ($eventId <= 0) rvu_event_json(['detail' => 'event_id is required.'], 422);
        rvu_event_json(['data' => rvu_event_fetch_comments($pdo, $eventId)]);
    }

    if ($method === 'POST') {
        $input = rvu_event_input();
        $eventId = (int)($input['event_id'] ?? 0);
        $comment = trim((string)($input['comment'] ?? ''));
        $parentId = isset($input['parent_comment_id']) ? (int)$input['parent_comment_id'] : null;
        $mentionIds = isset($input['mention_user_ids']) && is_array($input['mention_user_ids'])
            ? array_values(array_unique(array_filter(array_map('intval', $input['mention_user_ids']))))
            : [];

        if ($eventId <= 0 || $comment === '') rvu_event_json(['detail' => 'Event and comment are required.'], 422);
        if (mb_strlen($comment) > 1000) rvu_event_json(['detail' => 'Comment cannot exceed 1,000 characters.'], 422);
        $event = rvu_event_fetch($pdo, $eventId, $userId);
        if (!$event) rvu_event_json(['detail' => 'Event not found.'], 404);

        $parent = null;
        if ($parentId !== null && $parentId > 0) {
            $stmt = $pdo->prepare('SELECT id, event_id, user_id, parent_comment_id FROM campus_event_comments WHERE id = ? LIMIT 1');
            $stmt->execute([$parentId]);
            $parent = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
            if (!$parent || (int)$parent['event_id'] !== $eventId) rvu_event_json(['detail' => 'Invalid reply target.'], 422);
            if ($parent['parent_comment_id'] !== null) $parentId = (int)$parent['parent_comment_id'];
        } else {
            $parentId = null;
        }

        $stmt = $pdo->prepare('INSERT INTO campus_event_comments(event_id, user_id, parent_comment_id, comment) VALUES (?, ?, ?, ?) RETURNING id');
        $stmt->execute([$eventId, $userId, $parentId, $comment]);
        $commentId = (int)$stmt->fetchColumn();

        if ($mentionIds) {
            $mentionStmt = $pdo->prepare('INSERT INTO campus_event_comment_mentions(comment_id, mentioned_user_id) VALUES (?, ?) ON CONFLICT DO NOTHING');
            foreach ($mentionIds as $mentionedId) {
                if ($mentionedId > 0 && $mentionedId !== $userId) $mentionStmt->execute([$commentId, $mentionedId]);
            }
        }

        $actorName = trim((string)($user['full_name'] ?? 'Rockview User'));
        if ($parent) {
            rvu_event_notify($pdo, (int)$parent['user_id'], $userId, $eventId, $commentId, 'reply', $actorName . ' replied to your event comment', 'On "' . mb_substr((string)$event['title'], 0, 100) . '"');
        } elseif ((int)$event['author_id'] > 0) {
            rvu_event_notify($pdo, (int)$event['author_id'], $userId, $eventId, $commentId, 'comment', $actorName . ' commented on your event', 'On "' . mb_substr((string)$event['title'], 0, 100) . '"');
        }

        foreach ($mentionIds as $mentionedId) {
            rvu_event_notify($pdo, $mentionedId, $userId, $eventId, $commentId, 'mention', $actorName . ' mentioned you in an event discussion', mb_substr($comment, 0, 160));
        }

        rvu_event_json(['data' => rvu_event_fetch_comment($pdo, $commentId)], 201);
    }

    rvu_event_json(['detail' => 'Method not allowed.'], 405);
} catch (Throwable $e) {
    rvu_event_json(['detail' => 'Event comments server error: ' . $e->getMessage()], 500);
}
