<?php
/**
 * POST — envía una reacción emoji a un mensaje desde el número turnero.
 * Body JSON: { message_id, user_id, emoji }
 */
require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../services/WhatsAppService.php';
requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'error'=>'Método no permitido']); exit; }

$input     = json_decode(file_get_contents('php://input'), true) ?? [];
$messageId = trim($input['message_id'] ?? '');
$userId    = intval($input['user_id'] ?? 0);
$emoji     = trim($input['emoji'] ?? '');

if (!$messageId || !$userId || !$emoji) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'message_id, user_id y emoji son requeridos']);
    exit;
}

try {
    $db   = Database::getInstance();
    $user = $db->fetch("SELECT phone_number FROM users WHERE id = ?", [$userId]);
    if (!$user) { http_response_code(404); echo json_encode(['success'=>false,'error'=>'Usuario no encontrado']); exit; }

    $phoneId = getConfigFromDB('whatsapp_phone_number_id_turnero', '');
    if (!$phoneId) { http_response_code(503); echo json_encode(['success'=>false,'error'=>'Número turnero no configurado']); exit; }

    $wa   = new WhatsAppService('turnero');
    $resp = $wa->sendReaction($user['phone_number'], $messageId, $emoji, false);

    // Guardar reacción en el mensaje
    $db->query(
        "UPDATE conversations SET reaction_emoji = ?, reaction_to_message_id = ? WHERE message_id = ?",
        [$emoji, $messageId, $messageId]
    );

    echo json_encode(['success' => true, 'response' => $resp]);

} catch (Exception $e) {
    error_log('chat_react: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
