<?php
session_start();
header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$postId = $input['post_id'] ?? '';
$commentId = $input['comment_id'] ?? '';
$user = $_SESSION['user_id'] ?? '';

if (!$postId || !$commentId || !$user) {
    exit;
}

$normalFile = __DIR__ . "/../$postId/data.json";
$userFile   = __DIR__ . "/../user_posts/$postId/data.json";

if (file_exists($normalFile)) {
    $dataFile = $normalFile;
} elseif (file_exists($userFile)) {
    $dataFile = $userFile;
} else {
    exit;
}


$data = json_decode(file_get_contents($dataFile), true);
$found = false;

foreach ($data['comments'] as $index => $c) {
    if (
        $c['id'] == $commentId && $c['user'] === $user
    ) {
        array_splice($data['comments'], $index, 1);
        $found = true;
        break;
    }
}

if (!$found) {
    echo json_encode(['status' => 'error', 'message' => 'Comment not found or permission denied']);
    exit;
}

file_put_contents($dataFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
echo json_encode(['status' => 'success', 'count' => count($data['comments'])]);
