<?php
session_start();

$blockedWords = [];
$rateLimitSeconds = 10;

if (!isset($_SESSION['user_id'])) exit;

$input = json_decode(file_get_contents('php://input'), true);
$postId = $input['post_id'] ?? null;
$text = trim($input['text'] ?? '');
if (!$postId || !$text) exit;

$postId = basename($postId);
$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 = __DIR__ . '/../comment_rate_log.json';
$rateData = [];

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

$key = hash('sha256', $_SESSION['user_id'] . '|' . $ip . '|' . $postId);
$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);
if (!isset($data['comments'])) $data['comments'] = [];

$text = htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);

foreach ($blockedWords as $word) {
    $pattern = '/' . preg_quote($word, '/') . '/iu';
    $text = preg_replace_callback($pattern, function ($matches) {
        return str_repeat('*', mb_strlen($matches[0]));
    }, $text);
}

$text = preg_replace_callback('/\[(.*?)\]/s', function ($matches) {
    return '<span class="spoiler" data-spoiler="' . htmlspecialchars($matches[1]) . '">' . htmlspecialchars($matches[1]) . '</span>';
}, $text);

$newComment = [
    'id' => $now,
    'user' => $_SESSION['user_id'],
    'text' => $text,
    'date' => date('Y-m-d H:i:s'),
    'likes' => 0,
    'dislikes' => 0
];
$data['comments'][] = $newComment;

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