<?php
/**
 * Study Comments API
 * OBGYN Research Platform
 */

require_once '../config/config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

$userId = getCurrentUserId(); // May be null for public access
$method = $_SERVER['REQUEST_METHOD'];
$db = getDB();

try {
    switch ($method) {
        case 'GET':
            // Get comments for a study
            $studyId = isset($_GET['study_id']) ? (int)$_GET['study_id'] : 0;
            $parentId = isset($_GET['parent_id']) ? (int)$_GET['parent_id'] : null;
            $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
            $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
            $offset = ($page - 1) * $limit;

            if (!$studyId) {
                throw new Exception('Study ID required');
            }

            // Check if study exists and is public
            $stmt = $db->prepare("SELECT id, is_public FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();

            if (!$study) {
                throw new Exception('Study not found');
            }

            // Only show comments if study is public or user is collaborator/creator
            $canView = $study['is_public'];
            if (!$canView && $userId) {
                $stmt = $db->prepare("
                    SELECT 1 FROM studies s
                    LEFT JOIN study_collaborators sc ON s.id = sc.study_id AND sc.user_id = ?
                    WHERE s.id = ? AND (s.creator_id = ? OR sc.id IS NOT NULL)
                ");
                $stmt->execute([$userId, $studyId, $userId]);
                $canView = $stmt->fetch() !== false;
            }

            if (!$canView) {
                throw new Exception('Access denied');
            }

            // Get comments
            $whereClause = "WHERE sc.study_id = ?";
            $params = [$studyId];

            if ($parentId !== null) {
                $whereClause .= " AND sc.parent_id = ?";
                $params[] = $parentId;
            } else {
                $whereClause .= " AND sc.parent_id IS NULL";
            }

            $stmt = $db->prepare("
                SELECT sc.*, u.first_name, u.last_name, u.profile_picture,
                       (SELECT COUNT(*) FROM study_comments WHERE parent_id = sc.id) as reply_count
                FROM study_comments sc
                JOIN users u ON sc.user_id = u.id
                $whereClause AND sc.status = 'approved'
                ORDER BY sc.created_at DESC
                LIMIT ? OFFSET ?
            ");
            $params[] = $limit;
            $params[] = $offset;
            $stmt->execute($params);

            $comments = $stmt->fetchAll();

            // Get total count
            $stmt = $db->prepare("
                SELECT COUNT(*) FROM study_comments sc
                $whereClause AND sc.status = 'approved'
            ");
            array_pop($params); // Remove limit
            array_pop($params); // Remove offset
            $stmt->execute($params);
            $totalCount = $stmt->fetchColumn();

            echo json_encode([
                'success' => true,
                'data' => $comments,
                'pagination' => [
                    'page' => $page,
                    'limit' => $limit,
                    'total' => $totalCount,
                    'pages' => ceil($totalCount / $limit)
                ]
            ]);
            break;

        case 'POST':
            // Add comment
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['error' => 'Authentication required']);
                exit;
            }

            $studyId = isset($_POST['study_id']) ? (int)$_POST['study_id'] : 0;
            $content = sanitize($_POST['content'] ?? '');
            $parentId = isset($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
            $rating = isset($_POST['rating']) ? (int)$_POST['rating'] : null;
            $isReview = isset($_POST['is_review']) ? (bool)$_POST['is_review'] : false;

            if (!$studyId || empty($content)) {
                throw new Exception('Study ID and content required');
            }

            // Validate rating
            if ($rating !== null && ($rating < 1 || $rating > 5)) {
                throw new Exception('Rating must be between 1 and 5');
            }

            // Check if study exists and user can comment
            $stmt = $db->prepare("SELECT id, is_public, creator_id FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();

            if (!$study) {
                throw new Exception('Study not found');
            }

            // Check permissions
            $isCollaborator = false;
            if ($study['creator_id'] !== $userId) {
                $stmt = $db->prepare("SELECT id FROM study_collaborators WHERE study_id = ? AND user_id = ?");
                $stmt->execute([$studyId, $userId]);
                $isCollaborator = $stmt->fetch() !== false;
            }

            // Only collaborators can leave reviews, anyone can comment if study is public
            if ($isReview && !$isCollaborator && $study['creator_id'] !== $userId) {
                throw new Exception('Only collaborators can leave reviews');
            }

            if (!$isReview && !$study['is_public'] && !$isCollaborator && $study['creator_id'] !== $userId) {
                throw new Exception('Access denied');
            }

            // Check if parent comment exists and belongs to same study
            if ($parentId) {
                $stmt = $db->prepare("SELECT id FROM study_comments WHERE id = ? AND study_id = ?");
                $stmt->execute([$parentId, $studyId]);
                if (!$stmt->fetch()) {
                    throw new Exception('Parent comment not found');
                }
            }

            // Insert comment
            $stmt = $db->prepare("
                INSERT INTO study_comments (study_id, user_id, parent_id, content, is_review, rating)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$studyId, $userId, $parentId, $content, $isReview, $rating]);

            $commentId = $db->lastInsertId();

            // Log activity
            logActivity('comment_added', 'studies', $studyId);

            echo json_encode([
                'success' => true,
                'message' => 'Comment added successfully',
                'comment_id' => $commentId
            ]);
            break;

        case 'PUT':
            // Update comment (only by author)
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['error' => 'Authentication required']);
                exit;
            }

            $commentId = isset($_POST['comment_id']) ? (int)$_POST['comment_id'] : 0;
            $content = sanitize($_POST['content'] ?? '');
            $rating = isset($_POST['rating']) ? (int)$_POST['rating'] : null;

            if (!$commentId || empty($content)) {
                throw new Exception('Comment ID and content required');
            }

            // Get comment and verify ownership
            $stmt = $db->prepare("SELECT * FROM study_comments WHERE id = ? AND user_id = ?");
            $stmt->execute([$commentId, $userId]);
            $comment = $stmt->fetch();

            if (!$comment) {
                throw new Exception('Comment not found or access denied');
            }

            // Update comment
            $stmt = $db->prepare("
                UPDATE study_comments
                SET content = ?, rating = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$content, $rating, $commentId]);

            echo json_encode(['success' => true, 'message' => 'Comment updated successfully']);
            break;

        case 'DELETE':
            // Delete comment (by author or admin)
            if (!$userId) {
                http_response_code(401);
                echo json_encode(['error' => 'Authentication required']);
                exit;
            }

            $commentId = isset($_GET['comment_id']) ? (int)$_GET['comment_id'] : 0;

            if (!$commentId) {
                throw new Exception('Comment ID required');
            }

            // Delete comment (only if user owns it or is admin)
            $stmt = $db->prepare("
                DELETE FROM study_comments
                WHERE id = ? AND (user_id = ? OR ? IN (SELECT user_id FROM user_roles WHERE role_id IN (1,2)))
            ");
            $stmt->execute([$commentId, $userId, $userId]);

            if ($stmt->rowCount() === 0) {
                throw new Exception('Comment not found or access denied');
            }

            echo json_encode(['success' => true, 'message' => 'Comment deleted successfully']);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
