false, 'error' => 'No autenticado'], 401); } // Verificar permiso if (!hasPermission('manage_welcome', 'telegram')) { jsonResponse(['success' => false, 'error' => 'No tienes permiso para gestionar el mensaje de bienvenida de Telegram.'], 403); } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonResponse(['success' => false, 'error' => 'Método no permitido'], 405); } try { $db = getDB(); $botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN'); if (!$botToken) { throw new Exception("Token de bot de Telegram no configurado."); } // 1. Obtener la configuración de bienvenida $stmt = $db->query(" SELECT b.*, g.ruta as imagen_ruta FROM bienvenida_telegram b LEFT JOIN gallery g ON b.imagen_id = g.id LIMIT 1 "); $config = $stmt->fetch(PDO::FETCH_ASSOC); if (!$config || empty($config['activo'])) { throw new Exception("El mensaje de bienvenida no está activo o configurado."); } if (empty($config['chat_id'])) { throw new Exception("No hay un canal de bienvenida configurado."); } $chat_id = $config['chat_id']; $texto = $config['texto'] ?? "¡Bienvenido {usuario}!"; $imagen_url = !empty($config['imagen_id']) && !empty($config['imagen_ruta']) ? ($_ENV['APP_URL'] ?? 'http://localhost') . '/gallery/uploads/' . basename($config['imagen_ruta']) : null; // Simular un nuevo usuario para el mensaje de prueba $testUser = $userData->username ?? 'Tester'; // Usar el username del usuario logueado como test $messageText = str_replace('{usuario}', $testUser, $texto); // Preparar opciones de teclado (botones de idioma y botón "Únete al grupo") $keyboard = []; $inline_keyboard = []; // Botones de Idioma $idiomasHabilitados = json_decode($config['idiomas_habilitados'], true) ?? []; if (!empty($idiomasHabilitados)) { $row = []; foreach ($idiomasHabilitados as $langCode) { // Suponemos que tienes una forma de obtener el nombre del idioma por su código $langName = strtoupper($langCode); // Simplificado: usa el código como nombre $row[] = ['text' => $langName, 'callback_data' => "lang_select_{$langCode}"]; if (count($row) == 2) { // 2 botones por fila $inline_keyboard[] = $row; $row = []; } } if (!empty($row)) { $inline_keyboard[] = $row; } } // Botón "Únete al grupo" if (!empty($config['boton_unirse_texto']) && !empty($config['boton_unirse_url'])) { $inline_keyboard[] = [['text' => $config['boton_unirse_texto'], 'url' => $config['boton_unirse_url']]]; } if (!empty($inline_keyboard)) { $keyboard = ['inline_keyboard' => $inline_keyboard]; } $telegramApiUrl = "https://api.telegram.org/bot{$botToken}/"; $method = 'sendMessage'; $postFields = [ 'chat_id' => $chat_id, 'parse_mode' => 'HTML', // o 'MarkdownV2', dependiendo del formato de Summernote ]; if ($imagen_url) { $method = 'sendPhoto'; $postFields['photo'] = $imagen_url; $postFields['caption'] = $messageText; unset($postFields['text']); // sendPhoto usa 'caption' en lugar de 'text' } else { $postFields['text'] = $messageText; } if (!empty($keyboard)) { $postFields['reply_markup'] = json_encode($keyboard); } $ch = curl_init($telegramApiUrl . $method); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($curlError) { throw new Exception("Error cURL: " . $curlError); } $responseJson = json_decode($response, true); if ($httpCode !== 200 || !($responseJson['ok'] ?? false)) { $errorMsg = $responseJson['description'] ?? 'Error desconocido de Telegram API'; throw new Exception("Telegram API Error ({$httpCode}): {$errorMsg}"); } logToFile('telegram/messages.log', "Mensaje de bienvenida de prueba enviado a {$chat_id} por {$userData->username}"); jsonResponse(['success' => true, 'message' => 'Mensaje de prueba enviado con éxito a Telegram!', 'telegram_response' => $responseJson]); } catch (Exception $e) { logToFile('telegram/errors.log', "Error enviando mensaje de bienvenida de prueba: " . $e->getMessage(), 'ERROR'); jsonResponse(['success' => false, 'error' => $e->getMessage()], 500); }