<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php';

$post_id = $_POST['post_id'] ?? '';
$user_id = $_POST['user_id'] ?? '';
$reaction = $_POST['reaction'] ?? '';
$key = $_POST['key'] ?? '';

$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid encryption data']);
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();
    if (!$con) {
        echo json_encode(['status' => 'error', 'message' => 'DB connection failed']);
        exit;
    }

    // Check existing reaction
    $sql = "SELECT reaction_type FROM post_reactions WHERE post_id='$post_id' AND user_id='$user_id'";
    $result = mysqli_query($con, $sql);

    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $oldReaction = $row['reaction_type'];

        if ($oldReaction == $reaction) {
            // Same reaction → delete
            $sqlDelete = "DELETE FROM post_reactions WHERE post_id='$post_id' AND user_id='$user_id'";
            mysqli_query($con, $sqlDelete);
            $userReaction = "";
        } else {
            // Different reaction → update
            $sqlUpdate = "UPDATE post_reactions SET reaction_type='$reaction' 
                          WHERE post_id='$post_id' AND user_id='$user_id'";
            mysqli_query($con, $sqlUpdate);
            $userReaction = $reaction;
        }
    } else {
        // No reaction before → insert
        $sqlInsert = "INSERT INTO post_reactions (post_id, user_id, reaction_type) 
                      VALUES ('$post_id','$user_id','$reaction')";
        mysqli_query($con, $sqlInsert);
        $userReaction = $reaction;
    }

    // Get all reaction counts
    $counts = [];
    $totalReacts = 0;

    $sqlCount = "SELECT reaction_type, COUNT(*) AS total FROM post_reactions WHERE post_id='$post_id' GROUP BY reaction_type";
    $resCount = mysqli_query($con, $sqlCount);
    while ($row = mysqli_fetch_assoc($resCount)) {
        $counts[$row['reaction_type']] = $row['total'];
        $totalReacts += $row['total'];
    }

    // Sort descending by count
    arsort($counts);

    // Take top 3
    $top3Reactions = array_slice($counts, 0, 3, true);

    echo json_encode([
        "status" => "ok",
        "userReaction" => $userReaction,
        "counts" => $counts,
        "totalReacts" => $totalReacts,
        "top3" => $top3Reactions
    ]);
}

?>
