<?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'] ?? '';
$type = $input['type'] ?? '';
$user = $_SESSION['user_id'] ?? '';

if (!$user || !$postId || !$commentId || !$type) 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;
}


$ip = $_SERVER['REMOTE_ADDR'];
$logFile = '../comment_vote_rate_log.json';
$rateData = [];

if (file_exists($logFile)) {
    $rateData = json_decode(file_get_contents($logFile), true);
}

$key = hash('sha256', "$user|$ip|$postId|$commentId");
$rateLimitSeconds = 5;
$now = time();

if (isset($rateData[$key]) && $now - $rateData[$key] < $rateLimitSeconds) {
    exit;
}

$rateData[$key] = $now;
file_put_contents($logFile, json_encode($rateData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

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

foreach ($data['comments'] as &$c) {
    if ($c['id'] == $commentId) {

        if (!isset($c['liked_users'])) $c['liked_users'] = [];
        if (!isset($c['disliked_users'])) $c['disliked_users'] = [];

        if ($type === 'like') {
            if (in_array($user, $c['liked_users'])) {
                $c['liked_users'] = array_values(array_diff($c['liked_users'], [$user]));
            } else {
                $c['liked_users'][] = $user;
                $c['disliked_users'] = array_values(array_diff($c['disliked_users'], [$user]));
            }
        } elseif ($type === 'dislike') {
            if (in_array($user, $c['disliked_users'])) {
                $c['disliked_users'] = array_values(array_diff($c['disliked_users'], [$user]));
            } else {
                $c['disliked_users'][] = $user;
                $c['liked_users'] = array_values(array_diff($c['liked_users'], [$user]));
            }
        }


        $c['likes'] = count($c['liked_users']);
        $c['dislikes'] = count($c['disliked_users']);

        $found = true;
        $likes = $c['likes'];
        $dislikes = $c['dislikes'];
        break;
    }
}

if (!$found) exit;

file_put_contents($dataFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

echo json_encode([
    'status' => 'success',
    'likes' => $likes,
    'dislikes' => $dislikes
]);
