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

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

    if ($method === 'GET') {
        $itemId = (int)($_GET['item_id'] ?? 0);
        if ($itemId <= 0) rvu_market_json(['detail'=>'item_id is required.'],422);
        $stmt = $pdo->prepare("SELECT
            c.id,c.item_id,c.user_id,c.parent_comment_id,c.comment,c.created_at,
            u.full_name AS author_name,u.role AS author_role,COALESCE(u.profile_picture,'') AS author_profile_picture
          FROM campus_market_comments c
          INNER JOIN users u ON u.id=c.user_id
          WHERE c.item_id=?
          ORDER BY COALESCE(c.parent_comment_id,c.id) ASC,c.created_at ASC,c.id ASC");
        $stmt->execute([$itemId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        foreach ($rows as &$row) {
            $row['id']=(int)$row['id'];
            $row['item_id']=(int)$row['item_id'];
            $row['user_id']=(int)$row['user_id'];
            $row['parent_comment_id']=$row['parent_comment_id']!==null?(int)$row['parent_comment_id']:null;
        }
        unset($row);
        rvu_market_json(['data'=>$rows]);
    }

    if ($method === 'POST') {
        $input = rvu_market_input();
        $itemId = (int)($input['item_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_map('intval',$input['mention_user_ids']))) : [];
        if ($itemId <= 0 || $comment === '') rvu_market_json(['detail'=>'item_id and comment are required.'],422);
        if (mb_strlen($comment) > 1000) rvu_market_json(['detail'=>'Comment cannot exceed 1,000 characters.'],422);
        $item = rvu_market_fetch_item($pdo,$itemId,(int)$user['id']);
        if (!$item) rvu_market_json(['detail'=>'Listing not found.'],404);

        $parent = null;
        if ($parentId !== null && $parentId > 0) {
            $p = $pdo->prepare('SELECT id,user_id,item_id,parent_comment_id FROM campus_market_comments WHERE id=? LIMIT 1');
            $p->execute([$parentId]);
            $parent = $p->fetch(PDO::FETCH_ASSOC) ?: null;
            if (!$parent || (int)$parent['item_id'] !== $itemId) rvu_market_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_market_comments (item_id,user_id,parent_comment_id,comment) VALUES (?,?,?,?) RETURNING id');
        $stmt->execute([$itemId,(int)$user['id'],$parentId,$comment]);
        $commentId = (int)$stmt->fetchColumn();

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

        $actor = (string)($user['full_name'] ?? 'A member');
        if ($parent) {
            rvu_market_create_notification($pdo,(int)$parent['user_id'],(int)$user['id'],$itemId,$commentId,'reply',$actor.' replied to your marketplace comment','On "'.mb_substr((string)$item['title'],0,100).'"');
        } elseif ($item['seller_user_id'] !== null) {
            rvu_market_create_notification($pdo,(int)$item['seller_user_id'],(int)$user['id'],$itemId,$commentId,'comment',$actor.' commented on your marketplace listing','On "'.mb_substr((string)$item['title'],0,100).'"');
        }
        foreach ($mentionIds as $mentionId) {
            rvu_market_create_notification($pdo,$mentionId,(int)$user['id'],$itemId,$commentId,'mention',$actor.' mentioned you in a marketplace comment',mb_substr($comment,0,180));
        }
        rvu_market_json(['data'=>rvu_market_fetch_comment($pdo,$commentId)],201);
    }

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