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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(["status"=>"error","message"=>"برای رای دادن باید وارد حساب کاربری شوید"]);
    exit;
}

if (!isset($_POST['post_id'], $_POST['vote'])) {
    echo json_encode(["status"=>"error","message"=>"پارامترهای نامعتبر"]);
    exit;
}

$postId = $_POST['post_id'];
$vote = intval($_POST['vote']);
$username = $_SESSION['user_id'];
$dataFile = __DIR__ . "/$postId/data.json";

if (!file_exists($dataFile)) {
    exit;
}

$data = json_decode(file_get_contents($dataFile), true);
if (!isset($data['votes1'])) $data['votes1'] = [];
if (!isset($data['votes2'])) $data['votes2'] = [];

$data['votes1'] = array_values(array_diff($data['votes1'], [$username]));
$data['votes2'] = array_values(array_diff($data['votes2'], [$username]));

if ($vote === 1) {
    $data['votes1'][] = $username;
} elseif ($vote === 2) {
    $data['votes2'][] = $username;
}

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

echo json_encode([
    "status" => "success",
    "votes1" => count($data['votes1']),
    "votes2" => count($data['votes2'])
]);
exit;
