<?php
require_once '../config/database.php';

$db = new Database();
$conn = $db->connect();

$method = $_SERVER['REQUEST_METHOD'];
$requestUri = $_SERVER['REQUEST_URI'];

$parts = explode('/', parse_url($requestUri, PHP_URL_PATH));
$isLikeAction = false;
$commentId = null;

// Handle like endpoint: /comments.php/{id}/like
if (count($parts) >= 4 && $parts[count($parts) - 1] === 'like') {
    $isLikeAction = true;
    $commentId = $parts[count($parts) - 2];
}

// ✅ Handle GET: /comments.php/{postId}?username={username}
if ($method === 'GET' && count($parts) >= 3) {
    $postId = $parts[count($parts) - 1];
    $username = $_GET['username'] ?? '';

    $stmt = $conn->prepare("
        SELECT c.*, 
               (SELECT COUNT(*) FROM comment_likes WHERE comment_id = c.id) AS likes,
               EXISTS (
                   SELECT 1 FROM comment_likes WHERE comment_id = c.id AND username = ?
               ) AS hasLiked
        FROM comments c
        WHERE c.post_id = ?
        ORDER BY c.time DESC
    ");
    $stmt->execute([$username, $postId]);
    $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Convert hasLiked to true/false
    foreach ($comments as &$comment) {
        $comment['hasLiked'] = (bool) $comment['hasLiked'];
    }

    echo json_encode($comments);
    exit;
}

// ✅ Handle like/unlike
if ($isLikeAction && $method === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['username'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing username']);
        exit;
    }

    $username = $data['username'];

    // Like toggle logic...
    $check = $conn->prepare('SELECT * FROM comment_likes WHERE comment_id = ? AND username = ?');
    $check->execute([$commentId, $username]);

    if ($check->rowCount() > 0) {
        $conn->prepare('DELETE FROM comment_likes WHERE comment_id = ? AND username = ?')->execute([$commentId, $username]);
        $conn->prepare('UPDATE comments SET likes = likes - 1 WHERE id = ?')->execute([$commentId]);
        $hasLiked = false;
    } else {
        $conn->prepare('INSERT INTO comment_likes (comment_id, username) VALUES (?, ?)')->execute([$commentId, $username]);
        $conn->prepare('UPDATE comments SET likes = likes + 1 WHERE id = ?')->execute([$commentId]);
        $hasLiked = true;
    }

    $stmt = $conn->prepare('SELECT likes FROM comments WHERE id = ?');
    $stmt->execute([$commentId]);
    $likes = $stmt->fetch(PDO::FETCH_ASSOC)['likes'];

    echo json_encode([
        'success' => true,
        'likes' => (int)$likes,
        'hasLiked' => $hasLiked
    ]);
    exit;
}

// ✅ Handle comment POST
if ($method === 'POST' && count($parts) >= 3 && !$isLikeAction) {
    $postId = $parts[count($parts) - 1];
    $data = json_decode(file_get_contents('php://input'), true);

    if (!isset($data['username'], $data['content'], $data['user_image'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing username, content or user_image']);
        exit;
    }

    $username = $data['username'];
    $userImage = $data['user_image'];
    $content = $data['content'];

    // 🔑 Generate unique comment ID
    $id = uniqid('cmt_', true);

    // Insert the comment
    $stmt = $conn->prepare('
        INSERT INTO comments (id, post_id, username, user_image, content, likes, time)
        VALUES (?, ?, ?, ?, ?, 0, NOW())
    ');
    $stmt->execute([$id, $postId, $username, $userImage, $content]);

    // 🧮 Increment the comment count in the `posts` table
    $update = $conn->prepare('
        UPDATE posts SET comments = comments + 1 WHERE id = ?
    ');
    $update->execute([$postId]);

    http_response_code(201);
    echo json_encode(['success' => true, 'message' => 'Comment added', 'id' => $id]);
    exit;
}



// Invalid endpoint fallback
http_response_code(404);
echo json_encode(['error' => 'Invalid endpoint']);
