<?php
header('Content-Type: application/json');
require_once 'auth/session.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);
$message_id = $data['message_id'] ?? 0;
$emoji = $data['emoji'] ?? '';
$action = $data['action'] ?? 'toggle'; // 'toggle', 'add', 'remove'

if (!$message_id || !$emoji) {
    echo json_encode(['success' => false, 'error' => 'Missing message_id or emoji']);
    exit;
}

try {
    if ($action === 'toggle') {
        $stmt = db()->prepare("SELECT id FROM message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?");
        $stmt->execute([$message_id, $user_id, $emoji]);
        if ($stmt->fetch()) {
            $stmt = db()->prepare("DELETE FROM message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?");
            $stmt->execute([$message_id, $user_id, $emoji]);
            $res_action = 'removed';
        } else {
            $stmt = db()->prepare("INSERT INTO message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)");
            $stmt->execute([$message_id, $user_id, $emoji]);
            $res_action = 'added';
        }
    } elseif ($action === 'add') {
        $stmt = db()->prepare("INSERT IGNORE INTO message_reactions (message_id, user_id, emoji) VALUES (?, ?, ?)");
        $stmt->execute([$message_id, $user_id, $emoji]);
        $res_action = 'added';
    } else {
        $stmt = db()->prepare("DELETE FROM message_reactions WHERE message_id = ? AND user_id = ? AND emoji = ?");
        $stmt->execute([$message_id, $user_id, $emoji]);
        $res_action = 'removed';
    }

    // Get updated reactions for this message
    $stmt = db()->prepare("SELECT emoji, COUNT(*) as count, GROUP_CONCAT(user_id) as users FROM message_reactions WHERE message_id = ? GROUP BY emoji");
    $stmt->execute([$message_id]);
    $reactions = $stmt->fetchAll();

    echo json_encode([
        'success' => true,
        'action' => $res_action,
        'message_id' => $message_id,
        'reactions' => $reactions
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
