<?php

require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/env_loader.php';
require_once __DIR__ . '/../TelegramSender.php';
require_once __DIR__ . '/../actions/TelegramActions.php';
require_once __DIR__ . '/../converters/HtmlToTelegramHtmlConverter.php';
require_once __DIR__ . '/../../src/Translate.php';

$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
$webhookSecret = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');
$receivedToken = $_GET['auth_token'] ?? '';

if ($webhookSecret !== $receivedToken) {
    http_response_code(403);
    exit('Unauthorized');
}

$update = json_decode(file_get_contents('php://input'), true);

if (!$update) {
    exit('No update');
}

file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " -收到更新\n", FILE_APPEND);

if (isset($update['callback_query'])) {
    $callbackData = $update['callback_query']['data'] ?? 'no data';
    file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - Callback: $callbackData\n", FILE_APPEND);
}

try {
    $pdo = getDbConnection();
    $sender = new Telegram\TelegramSender();
    $actions = new Telegram\Actions\TelegramActions();
    $translator = new src\Translate();
    
    if (isset($update['message'])) {
        $message = $update['message'];
        $chatId = $message['chat']['id'];
        $userId = $message['from']['id'] ?? null;
        $text = $message['text'] ?? '';
        $username = $message['from']['first_name'] ?? 'Usuario';
        
        registerTelegramUser($pdo, $message['from']);
        
        if (!isExistingTelegramUser($pdo, $userId)) {
            sendWelcomeMessage($pdo, $sender, $chatId, $username);
        }
        
        if (str_starts_with($text, '/')) {
            handleTelegramCommand($sender, $pdo, $chatId, $userId, $text, $username);
        } elseif (str_starts_with($text, '#')) {
            $command = ltrim($text, '#');
            sendTemplateByCommand($pdo, $sender, $chatId, $command);
        } else {
            handleTelegramMessage($pdo, $sender, $chatId, $userId, $text);
        }
        
    } elseif (isset($update['callback_query'])) {
        $callbackQuery = $update['callback_query'];
        $callbackData = $callbackQuery['data'];
        $chatId = $callbackQuery['message']['chat']['id'];
        $messageId = $callbackQuery['message']['message_id'];
        $userId = $callbackQuery['from']['id'] ?? '';
        
        error_log("Telegram callback - chatId: $chatId, messageId: $messageId, userId: $userId, callbackData: $callbackData");
        
        handleTelegramCallback($pdo, $sender, $translator, $chatId, $messageId, $callbackQuery['id'], $callbackData);
    }
    
} catch (Exception $e) {
    error_log("Telegram Webhook Error: " . $e->getMessage());
}

function registerTelegramUser(PDO $pdo, array $user): void
{
    $stmt = $pdo->prepare("
        INSERT INTO recipients (platform_id, name, type, platform, language_code, chat_mode)
        VALUES (?, ?, 'user', 'telegram', ?, 'bot')
        ON DUPLICATE KEY UPDATE name = VALUES(name)
    ");
    
    $name = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
    $languageCode = $user['language_code'] ?? 'es';
    
    $stmt->execute([$user['id'], $name, $languageCode]);
}

function handleAutoTranslation(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, string $text): void
{
    $keyboard = getTelegramTranslationButtons($pdo, $text);
    
    if (!empty($keyboard)) {
        $message = "🌐 <b>Traducciones disponibles:</b>\nHaz clic en una bandera para ver la traducción";
        $sender->sendMessage($chatId, $message, $keyboard);
    }
}

function getTelegramTranslationButtons(PDO $pdo, string $text, ?string $excludeLang = null): ?array
{
    try {
        $stmt = $pdo->query("SELECT language_code, flag_emoji FROM supported_languages WHERE is_active = 1");
        $activeLanguages = $stmt->fetchAll();
        
        if (count($activeLanguages) <= 1) {
            return null;
        }
        
        $textHash = md5($text);
        $stmt = $pdo->prepare("INSERT INTO translation_cache (text_hash, original_text) VALUES (?, ?) ON DUPLICATE KEY UPDATE original_text = VALUES(original_text)");
        $stmt->execute([$textHash, $text]);
        
        $buttons = [];
        foreach ($activeLanguages as $lang) {
            if ($excludeLang && $lang['language_code'] === $excludeLang) {
                continue;
            }
            
            $callbackData = "translate:" . $lang['language_code'] . ":" . $textHash;
            
            $buttons[] = [
                'text' => $lang['flag_emoji'] . ' ' . strtoupper($lang['language_code']),
                'callback_data' => $callbackData
            ];
        }
        
        if (empty($buttons)) {
            return null;
        }
        
        return ['inline_keyboard' => array_chunk($buttons, 3)];
    } catch (Exception $e) {
        error_log("getTelegramTranslationButtons error: " . $e->getMessage());
        return null;
    }
}

function handleTelegramCommand(Telegram\TelegramSender $sender, PDO $pdo, int $chatId, int $userId, string $command, string $username): void
{
    $command = str_replace(['/', '@botname'], '', $command);
    $parts = explode(' ', $command);
    $cmd = strtolower($parts[0]);
    $args = array_slice($parts, 1);
    
    switch ($cmd) {
        case 'start':
            $stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
            $config = $stmt->fetch();
            
            if ($config && $config['is_active']) {
                $text = str_replace('{user_name}', $username, $config['message_text']);
                $buttons = [];
                
                if ($config['button_text'] && $config['group_invite_link']) {
                    $buttons[] = [
                        'text' => $config['button_text'],
                        'url' => $config['group_invite_link']
                    ];
                }
                
                $keyboard = !empty($buttons) ? $sender->createInlineKeyboard($buttons) : null;
                $sender->sendMessage($chatId, $text, $keyboard);
            } else {
                $sender->sendMessage($chatId, "¡Hola {$username}! 👋\n\nUsa /comandos para ver los comandos disponibles.");
            }
            break;
            
        case 'comandos':
            $message = "📋 <b>Comandos disponibles:</b>\n\n";
            $message .= "/start - Iniciar bot\n";
            $message .= "/comandos - Ver comandos\n";
            $message .= "/setlang [código] - Establecer idioma\n";
            $message .= "/bienvenida - Mensaje de bienvenida\n";
            $message .= "/agente - Cambiar modo de chat\n";
            
            $stmt = $pdo->query("SELECT name, telegram_command FROM recurrent_messages WHERE telegram_command IS NOT NULL AND telegram_command != '' ORDER BY name");
            $customCommands = $stmt->fetchAll();
            
            if (!empty($customCommands)) {
                $message .= "\n📦 <b>Plantillas:</b>\n";
                foreach ($customCommands as $cmd) {
                    $message .= "#" . htmlspecialchars($cmd['telegram_command']) . " - " . htmlspecialchars($cmd['name']) . "\n";
                }
            }
            
            $message .= "\n✍️ Escribe cualquier texto para traducir automáticamente";
            
            $translationButtons = getTelegramTranslationButtons($pdo, $message);
            
            if ($translationButtons) {
                $sender->sendMessage($chatId, $message, $translationButtons);
            } else {
                $sender->sendMessage($chatId, $message);
            }
            break;
            
        case 'setlang':
            $langCode = $args[0] ?? 'es';
            $stmt = $pdo->prepare("UPDATE recipients SET language_code = ? WHERE platform_id = ? AND platform = 'telegram'");
            $stmt->execute([$langCode, $chatId]);
            
            $sender->sendMessage($chatId, "✅ Idioma actualizado a: " . strtoupper($langCode));
            break;
            
        case 'bienvenida':
            $stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
            $config = $stmt->fetch();
            
            if ($config && $config['is_active']) {
                $text = str_replace('{user_name}', $username, $config['message_text']);
                
                // Agregar botones de traducción (convertir HTML a texto plano)
                $plainText = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $plainText = preg_replace('/\s+/', ' ', $plainText);
                $translationButtons = getTelegramTranslationButtons($pdo, $plainText);
                
                if (!empty($translationButtons)) {
                    $keyboard = $sender->createInlineKeyboard(array_map(function($btn) {
                        return ['text' => $btn['flag'], 'callback_data' => $btn['callback_data']];
                    }, $translationButtons));
                    $sender->sendMessage($chatId, $text, $keyboard);
                } else {
                    $sender->sendMessage($chatId, $text);
                }
            }
            break;
            
        case 'agente':
            $buttons = [
                [
                    'text' => '🤖 Seguir con Bot',
                    'callback_data' => 'chat_mode:bot:' . $userId
                ],
                [
                    'text' => '💬 Platicar con IA',
                    'callback_data' => 'chat_mode:ia:' . $userId
                ]
            ];
            
            $keyboard = $sender->createInlineKeyboard($buttons);
            $sender->sendMessage($chatId, "🤖 <b>Selecciona un modo de chat:</b>", $keyboard);
            break;
    }
}

function handleTelegramMessage(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, int $userId, string $text): void
{
    $stmt = $pdo->prepare("SELECT chat_mode FROM recipients WHERE platform_id = ? AND platform = 'telegram'");
    $stmt->execute([$userId]);
    $recipient = $stmt->fetch();
    
    if ($recipient && $recipient['chat_mode'] === 'ia') {
        sendToN8NIA($sender, $chatId, $userId, $text);
    } else {
        require_once __DIR__ . '/../../src/Translate.php';
        $translator = new src\Translate();
        handleAutoTranslation($pdo, $sender, $translator, $chatId, $text);
    }
}

function sendToN8NIA(Telegram\TelegramSender $sender, int $chatId, int $userId, string $userMessage): void
{
    $useN8n = $_ENV['N8N_IA_WEBHOOK_URL'] ?? getenv('N8N_IA_WEBHOOK_URL') ?? '';
    $useN8n = trim($useN8n, '"');
    
    if (!empty($useN8n)) {
        $data = [
            'user_id' => (string)$userId,
            'message' => $userMessage
        ];
        
        $ch = curl_init($useN8n);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($httpCode < 200 || $httpCode >= 300) {
            $sender->sendMessage($chatId, "❌ Error HTTP: $httpCode");
            error_log("N8N IA Telegram Error: HTTP $httpCode - $error");
        }
        return;
    }
    
    require_once __DIR__ . '/../../src/IA/Agent.php';
    $agent = new \IA\Agent();
    
    try {
        $response = $agent->generateResponse($userMessage);
        $sender->sendMessage($chatId, $response);
    } catch (\Exception $e) {
        $sender->sendMessage($chatId, "❌ Error: " . $e->getMessage());
        error_log("IA Agent Error: " . $e->getMessage());
    }
}

function sendTemplateByCommand(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, string $command): void
{
    $stmt = $pdo->prepare("SELECT * FROM recurrent_messages WHERE telegram_command = ?");
    $stmt->execute([$command]);
    $template = $stmt->fetch();
    
    if ($template) {
        $converter = new Telegram\Converters\HtmlToTelegramHtmlConverter();
        $content = $converter->convert($template['message_content']);
        
        $plainText = $template['message_content'];
        $plainText = preg_replace('/<br\s*\/?>/i', "\n", $plainText);
        $plainText = preg_replace('/<\/p>/i', "\n", $plainText);
        $plainText = preg_replace('/<p[^>]*>/i', '', $plainText);
        $plainText = strip_tags($plainText);
        $plainText = html_entity_decode($plainText, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        // Limpiar espacios múltiples pero preservar saltos de línea
        $plainText = preg_replace('/[ \t]+/', ' ', $plainText);
        $plainText = preg_replace('/\n\s*\n/', "\n", $plainText);
        $plainText = trim($plainText);
        
        $translationButtons = getTelegramTranslationButtons($pdo, $plainText);
        
        if ($translationButtons) {
            $sender->sendMessage($chatId, $content, $translationButtons);
        } else {
            $sender->sendMessage($chatId, $content);
        }
    } else {
        $sender->sendMessage($chatId, "❌ Plantilla no encontrada: #{$command}");
    }
}

function handleTelegramCallback(PDO $pdo, Telegram\TelegramSender $sender, src\Translate $translator, int $chatId, int $messageId, string $callbackQueryId, string $callbackData): void
{
    $parts = explode(':', $callbackData, 3);
    $action = $parts[0] ?? '';
    
    if ($action === 'translate') {
        $targetLang = $parts[1] ?? 'es';
        $textHash = $parts[2] ?? '';
        
        file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - targetLang: $targetLang, textHash: $textHash\n", FILE_APPEND);
        
        // Recuperar texto de la base de datos
        $stmt = $pdo->prepare("SELECT original_text FROM translation_cache WHERE text_hash = ?");
        $stmt->execute([$textHash]);
        $row = $stmt->fetch();
        
        if (!$row) {
            file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: No text found\n", FILE_APPEND);
            $sender->answerCallbackQuery($callbackQueryId, "❌ Error: Texto no encontrado");
            return;
        }
        
        $originalText = $row['original_text'];
        
        if (empty($originalText)) {
            file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: Empty text\n", FILE_APPEND);
            $sender->answerCallbackQuery($callbackQueryId, "❌ Error: No se pudo recuperar el texto");
            return;
        }
        
        try {
            // Obtener el idioma original
            $sourceLang = $translator->detectLanguage($originalText) ?? 'es';
            file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - sourceLang: $sourceLang, targetLang: $targetLang, originalText: " . substr($originalText, 0, 50) . "\n", FILE_APPEND);
            
            // Traducir
            $translated = $translator->translate($originalText, $sourceLang, $targetLang);
            file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - translated: $translated\n", FILE_APPEND);
            
            if ($translated) {
                // Limpiar TODAS las etiquetas HTML problemáticas (con espacios como < b > o </ b >)
                $translated = preg_replace('/<\s*(\/?)\s*([a-z]+)\s*>?/i', '<$1$2>', $translated);
                
                // Eliminar espacios extra en comandos de Telegram
                $translated = preg_replace('/\/(\s+)(\w+)/', '/$2', $translated);
                $translated = preg_replace('/#(\s+)(\w+)/', '#$2', $translated);
                
                // Verificar si hay etiquetas HTML inválidas después de la limpieza
                if (preg_match('/<[a-z][^>]*\s+[^>]*>/i', $translated)) {
                    // Si hay más problemas, convertir a texto plano pero mantener estructura
                    $translated = strip_tags($translated);
                    // Agregar emoji para mejor visualización
                    $translated = str_replace('/start', '✅ /start', $translated);
                    $translated = str_replace('/comandos', '📋 /comandos', $translated);
                    $translated = str_replace('/setlang', '🌐 /setlang', $translated);
                    $translated = str_replace('/bienvenida', '👋 /bienvenida', $translated);
                    $translated = str_replace('/agente', '🤖 /agente', $translated);
                }
                
                $sender->answerCallbackQuery($callbackQueryId, "", false);
                
                $keyboard = getTelegramTranslationButtons($pdo, $originalText, $targetLang);
                
                $result = $sender->editMessageText($chatId, $messageId, "🌐 <b>Traducción (" . strtoupper($targetLang) . "):</b>\n\n" . $translated, $keyboard);
                file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - editMessageText result: " . json_encode($result) . "\n", FILE_APPEND);
            } else {
                file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - ERROR: Translation failed\n", FILE_APPEND);
                $sender->answerCallbackQuery($callbackQueryId, "❌ Error al traducir el mensaje", false);
            }
        } catch (Exception $e) {
            file_put_contents('/var/www/html/lastwar/logs/telegram_debug.log', date('Y-m-d H:i:s') . " - EXCEPTION: " . $e->getMessage() . "\n", FILE_APPEND);
            $sender->answerCallbackQuery($callbackQueryId, "❌ Error en la traducción", false);
        }
    } elseif ($action === 'chat_mode') {
        $mode = $parts[1] ?? 'bot';
        $userId = $parts[2] ?? '';
        
        if (empty($userId)) {
            $sender->answerCallbackQuery($callbackQueryId, "❌ Error: Usuario no identificado");
            return;
        }
        
        $chatMode = ($mode === 'ia') ? 'ia' : 'bot';
        $stmt = $pdo->prepare("UPDATE recipients SET chat_mode = ? WHERE platform_id = ? AND platform = 'telegram'");
        $stmt->execute([$chatMode, $userId]);
        
        if ($chatMode === 'ia') {
            $sender->answerCallbackQuery($callbackQueryId, "✅ Modo IA activado. Ahora puedes platicar con la IA.", false);
            $sender->sendMessage($chatId, "✅ <b>Modo IA activado.</b>\n\nAhora puedes platicar conmigo. Escribe cualquier cosa y la enviaré a la IA.");
        } else {
            $sender->answerCallbackQuery($callbackQueryId, "✅ Modo Bot activado.", false);
            $sender->sendMessage($chatId, "✅ <b>Modo Bot activado.</b>\n\nAhora puedes usar comandos como #comando y traducción.");
        }
    }
}

function isExistingTelegramUser(PDO $pdo, int $userId): bool
{
    $stmt = $pdo->prepare("SELECT id FROM recipients WHERE platform_id = ? AND platform = 'telegram'");
    $stmt->execute([$userId]);
    return $stmt->fetch() !== false;
}

function sendWelcomeMessage(PDO $pdo, Telegram\TelegramSender $sender, int $chatId, string $username): void
{
    $stmt = $pdo->query("SELECT * FROM telegram_bot_messages WHERE id = 1");
    $config = $stmt->fetch();
    
    if ($config && $config['is_active']) {
        $text = str_replace('{user_name}', $username, $config['message_text']);
        $buttons = [];
        
        if ($config['button_text'] && $config['group_invite_link']) {
            $buttons[] = [
                'text' => $config['button_text'],
                'url' => $config['group_invite_link']
            ];
        }
        
        $keyboard = !empty($buttons) ? $sender->createInlineKeyboard($buttons) : null;
        $sender->sendMessage($chatId, $text, $keyboard);
    } else {
        $sender->sendMessage($chatId, "¡Hola {$username}! 👋\n\nUsa /comandos para ver los comandos disponibles.");
    }
}
