<?php
/**
 * Test de Conexión con Telegram Bot API
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Cargar variables de entorno
if (file_exists(__DIR__ . '/../.env')) {
    $lines = file(__DIR__ . '/../.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
    }
}

require_once __DIR__ . '/../shared/auth/jwt.php';
$userData = JWTAuth::requireAuth();

$botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');

if (!$botToken) {
    die("Error: TELEGRAM_BOT_TOKEN no está configurado en .env");
}

// Test 1: getMe - Obtener información del bot
function testGetMe($token) {
    $ch = curl_init("https://api.telegram.org/bot{$token}/getMe");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'response' => json_decode($response, true)
    ];
}

// Test 2: getUpdates - Obtener actualizaciones recientes
function testGetUpdates($token) {
    $ch = curl_init("https://api.telegram.org/bot{$token}/getUpdates?limit=5");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'response' => json_decode($response, true)
    ];
}

$testGetMe = testGetMe($botToken);
$testUpdates = testGetUpdates($botToken);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Conexión Telegram</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --telegram-color: #0088cc;
            --success: #28a745;
            --danger: #dc3545;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--telegram-color) 0%, #006699 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container { max-width: 900px; margin: 0 auto; }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .header {
            background: white;
            border-radius: 15px;
            padding: 20px 30px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        h1 { color: var(--telegram-color); margin-bottom: 10px; }
        h2 { color: #333; margin-bottom: 15px; font-size: 20px; }
        
        .status {
            display: inline-block;
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: 600;
            margin-bottom: 15px;
        }
        
        .status.success { background: var(--success); color: white; }
        .status.error { background: var(--danger); color: white; }
        
        pre {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            font-size: 13px;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            background: #6c757d;
            color: white;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fab fa-telegram"></i> Test de Conexión Telegram</h1>
        <a href="/telegram/dashboard_telegram.php" class="btn">← Volver</a>
    </div>
    
    <div class="container">
        <div class="card">
            <h2>1. Información del Bot (getMe)</h2>
            <div class="status <?php echo $testGetMe['http_code'] === 200 ? 'success' : 'error'; ?>">
                <?php echo $testGetMe['http_code'] === 200 ? '✓ Conexión exitosa' : '✗ Error de conexión'; ?>
            </div>
            
            <?php if ($testGetMe['response']['ok']): ?>
                <p><strong>Nombre:</strong> <?php echo htmlspecialchars($testGetMe['response']['result']['first_name']); ?></p>
                <p><strong>Username:</strong> @<?php echo htmlspecialchars($testGetMe['response']['result']['username']); ?></p>
                <p><strong>ID:</strong> <?php echo $testGetMe['response']['result']['id']; ?></p>
                <p><strong>Permite inline:</strong> <?php echo $testGetMe['response']['result']['supports_inline_queries'] ? 'Sí' : 'No'; ?></p>
            <?php endif; ?>
            
            <details>
                <summary style="cursor: pointer; margin-top: 15px;">Ver respuesta completa</summary>
                <pre><?php echo json_encode($testGetMe['response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?></pre>
            </details>
        </div>
        
        <div class="card">
            <h2>2. Actualizaciones Recientes (getUpdates)</h2>
            <div class="status <?php echo $testUpdates['http_code'] === 200 ? 'success' : 'error'; ?>">
                <?php echo $testUpdates['http_code'] === 200 ? '✓ API accesible' : '✗ Error'; ?>
            </div>
            
            <?php if ($testUpdates['response']['ok']): ?>
                <p><strong>Mensajes recientes:</strong> <?php echo count($testUpdates['response']['result']); ?></p>
            <?php endif; ?>
            
            <details>
                <summary style="cursor: pointer; margin-top: 15px;">Ver actualizaciones</summary>
                <pre><?php echo json_encode($testUpdates['response'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); ?></pre>
            </details>
        </div>
        
        <div class="card">
            <h2>3. Configuración Actual</h2>
            <p><strong>Token:</strong> <?php echo substr($botToken, 0, 10) . '...' . substr($botToken, -10); ?></p>
            <p style="color: #666; font-size: 14px; margin-top: 10px;">
                <i class="fas fa-info-circle"></i> Si todos los tests pasan, tu bot está correctamente configurado y listo para usarse.
            </p>
        </div>
        
        <div class="card">
            <h2>4. Gestión de Webhook</h2>
            <p style="margin-bottom: 15px; color: #666;">
                El bot puede funcionar con webhook (HTTP) o polling (daemon). Actualmente usamos <strong>polling con Supervisor</strong>.
                Si prefieres usar webhook, configúralo aquí:
            </p>
            
            <div style="margin-bottom: 15px;">
                <strong>URL del Webhook:</strong>
                <input type="text" id="webhookUrl" value="<?php echo $_ENV['APP_URL'] ?? ''; ?>/bot/telegram/webhook/index.php" 
                       style="width: 100%; padding: 8px; border: 2px solid #eee; border-radius: 5px; margin-top: 5px;">
            </div>
            
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <button onclick="setWebhook()" class="btn" style="background: var(--telegram-color);">
                    <i class="fas fa-upload"></i> Configurar Webhook
                </button>
                <button onclick="deleteWebhook()" class="btn" style="background: var(--danger);">
                    <i class="fas fa-trash"></i> Eliminar Webhook
                </button>
                <button onclick="getWebhookInfo()" class="btn" style="background: #6c757d;">
                    <i class="fas fa-info-circle"></i> Ver Estado
                </button>
            </div>
            
            <div id="webhookResult" style="display: none; margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                <pre id="webhookResultText" style="margin: 0; white-space: pre-wrap;"></pre>
            </div>
        </div>
    </div>
    
    <script>
        async function setWebhook() {
            const url = document.getElementById('webhookUrl').value;
            if (!url) {
                alert('Por favor ingresa una URL válida');
                return;
            }
            
            const resultDiv = document.getElementById('webhookResult');
            const resultText = document.getElementById('webhookResultText');
            resultDiv.style.display = 'block';
            resultText.textContent = 'Configurando webhook...';
            
            try {
                const response = await fetch('/telegram/api/webhook/manage.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'set',
                        url: url
                    })
                });
                const data = await response.json();
                resultText.textContent = JSON.stringify(data.data, null, 2);
                
                if (data.success) {
                    resultDiv.style.background = '#d4edda';
                } else {
                    resultDiv.style.background = '#f8d7da';
                }
            } catch (error) {
                resultText.textContent = 'Error: ' + error.message;
                resultDiv.style.background = '#f8d7da';
            }
        }
        
        async function deleteWebhook() {
            if (!confirm('¿Eliminar el webhook actual? Esto es necesario si quieres usar el bot con polling (Supervisor).')) return;
            
            const resultDiv = document.getElementById('webhookResult');
            const resultText = document.getElementById('webhookResultText');
            resultDiv.style.display = 'block';
            resultText.textContent = 'Eliminando webhook...';
            
            try {
                const response = await fetch('/telegram/api/webhook/manage.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'delete'
                    })
                });
                const data = await response.json();
                resultText.textContent = JSON.stringify(data.data, null, 2);
                
                if (data.success) {
                    resultDiv.style.background = '#d4edda';
                } else {
                    resultDiv.style.background = '#f8d7da';
                }
            } catch (error) {
                resultText.textContent = 'Error: ' + error.message;
                resultDiv.style.background = '#f8d7da';
            }
        }
        
        async function getWebhookInfo() {
            const resultDiv = document.getElementById('webhookResult');
            const resultText = document.getElementById('webhookResultText');
            resultDiv.style.display = 'block';
            resultText.textContent = 'Consultando estado...';
            
            try {
                const response = await fetch('/telegram/api/webhook/manage.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'info'
                    })
                });
                const data = await response.json();
                resultText.textContent = JSON.stringify(data.data, null, 2);
                resultDiv.style.background = '#f8f9fa';
            } catch (error) {
                resultText.textContent = 'Error: ' + error.message;
                resultDiv.style.background = '#f8d7da';
            }
        }
    </script>
</body>
</html>
