<?php
/**
 * ============================================================================
 * posts/add-comment.php - Add Comment to Post API
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$userId = getUserId();
$postId = isset($_POST['post_id']) ? (int)$_POST['post_id'] : 0;
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
$parentCommentId = isset($_POST['parent_comment_id']) ? (int)$_POST['parent_comment_id'] : null;

if (!$postId || empty($content)) {
    echo json_encode(['success' => false, 'error' => 'Invalid input']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $postClass = new \App\Post($db);
    
    // Add comment
    $commentId = $postClass->addComment($postId, $userId, $content, $parentCommentId);
    
    if ($commentId) {
        // Get the added comment
        $query = "SELECT 
                    pc.*,
                    u.full_name,
                    u.profile_picture
                FROM post_comments pc
                INNER JOIN users u ON pc.user_id = u.id
                WHERE pc.id = :comment_id";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':comment_id', $commentId);
        $stmt->execute();
        
        $comment = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'comment' => $comment
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to add comment']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>