<?php
include 'db_connect.php'; // ডাটাবেজ কানেকশন ফাইল

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $post_id = $_POST['post_id'];
    $user_id = $_POST['user_id'];
    $action = $_POST['action']; // like, love, care, wow

    // বৈধ action গুলো
    $validActions = ['like', 'love', 'care', 'wow'];

    if (!in_array($action, $validActions)) {
        echo json_encode(["status" => "error", "message" => "Invalid action"]);
        exit;
    }

    $con = dbConnect();

    // আগের রিঅ্যাকশন চেক করো
    $checkQuery = "SELECT * FROM post_likes WHERE post_id='$post_id' AND user_id='$user_id'";
    $result = mysqli_query($con, $checkQuery);
    $row = mysqli_fetch_assoc($result);

    if ($row) {
        $previousAction = $row['action'];

        if ($previousAction == $action) {
            // আগের মতো একই রিঅ্যাকশন, তাহলে রিমুভ (toggle off)
            $deleteQuery = "DELETE FROM post_likes WHERE post_id='$post_id' AND user_id='$user_id'";
            mysqli_query($con, $deleteQuery);

            // count কমাও
            mysqli_query($con, "UPDATE post_table SET `${action}s` = `${action}s` - 1 WHERE id='$post_id'");

            echo json_encode(["status" => "removed"]);
        } else {
            // আগের রিঅ্যাকশন পরিবর্তন করো
            $updateQuery = "UPDATE post_likes SET action='$action' WHERE post_id='$post_id' AND user_id='$user_id'";
            mysqli_query($con, $updateQuery);

            // আগেরটা -1, নতুনটা +1
            mysqli_query($con, "UPDATE post_table SET `${previousAction}s` = `${previousAction}s` - 1, `${action}s` = `${action}s` + 1 WHERE id='$post_id'");

            echo json_encode(["status" => "updated"]);
        }
    } else {
        // নতুন রিঅ্যাকশন ইনসার্ট
        $insertQuery = "INSERT INTO post_likes (post_id, user_id, action) VALUES ('$post_id', '$user_id', '$action')";
        mysqli_query($con, $insertQuery);

        // count বাড়াও
        mysqli_query($con, "UPDATE post_table SET `${action}s` = `${action}s` + 1 WHERE id='$post_id'");

        echo json_encode(["status" => "success"]);
    }
}
?>
