<?php
/**
 * Test de Conexión con Discord
 */

// 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';

// Verificar autenticación
$userData = JWTAuth::requireAuth();

$bot_token = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
$guild_id = $_ENV['DISCORD_GUILD_ID'] ?? getenv('DISCORD_GUILD_ID');

$testResults = [];
$allSuccess = true;

// Test 1: Verificar token
$testResults[] = [
    'test' => 'Verificar token configurado',
    'success' => !empty($bot_token),
    'message' => !empty($bot_token) ? 'Token configurado correctamente' : 'Token no configurado'
];

// Test 2: Obtener información del bot
if (!empty($bot_token)) {
    $ch = curl_init('https://discord.com/api/v10/users/@me');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bot ' . $bot_token,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $success = $httpCode === 200;
    $allSuccess = $allSuccess && $success;
    
    if ($success) {
        $botInfo = json_decode($response, true);
        $testResults[] = [
            'test' => 'Conectar con Discord API',
            'success' => true,
            'message' => 'Conectado como: ' . $botInfo['username'] . '#' . $botInfo['discriminator'],
            'data' => $botInfo
        ];
    } else {
        $testResults[] = [
            'test' => 'Conectar con Discord API',
            'success' => false,
            'message' => 'Error HTTP ' . $httpCode . ': ' . $response
        ];
    }
}

// Test 3: Obtener información del servidor/guild
if (!empty($bot_token) && !empty($guild_id)) {
    $ch = curl_init("https://discord.com/api/v10/guilds/{$guild_id}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bot ' . $bot_token,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $success = $httpCode === 200;
    $allSuccess = $allSuccess && $success;
    
    if ($success) {
        $guildInfo = json_decode($response, true);
        $testResults[] = [
            'test' => 'Acceder al servidor Discord',
            'success' => true,
            'message' => 'Servidor: ' . $guildInfo['name'] . ' (Miembros: ' . ($guildInfo['approximate_member_count'] ?? 'N/A') . ')',
            'data' => $guildInfo
        ];
    } else {
        $testResults[] = [
            'test' => 'Acceder al servidor Discord',
            'success' => false,
            'message' => 'Error HTTP ' . $httpCode . ': ' . $response
        ];
    }
}

// Test 4: Listar canales
if (!empty($bot_token) && !empty($guild_id)) {
    $ch = curl_init("https://discord.com/api/v10/guilds/{$guild_id}/channels");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bot ' . $bot_token,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $success = $httpCode === 200;
    $allSuccess = $allSuccess && $success;
    
    if ($success) {
        $channels = json_decode($response, true);
        $textChannels = array_filter($channels, fn($c) => $c['type'] === 0);
        $testResults[] = [
            'test' => 'Listar canales',
            'success' => true,
            'message' => 'Se encontraron ' . count($textChannels) . ' canales de texto',
            'data' => array_slice($textChannels, 0, 5)
        ];
    } else {
        $testResults[] = [
            'test' => 'Listar canales',
            'success' => false,
            'message' => 'Error HTTP ' . $httpCode
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Discord - Sistema de Bots</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #5865F2 0%, #4752C4 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }
        h1 {
            color: #5865F2;
            margin-bottom: 30px;
            text-align: center;
        }
        .test-result {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 5px solid #ddd;
        }
        .test-result.success {
            border-left-color: #28a745;
        }
        .test-result.error {
            border-left-color: #dc3545;
        }
        .test-name {
            font-weight: 700;
            font-size: 16px;
            margin-bottom: 8px;
        }
        .test-message {
            color: #666;
            font-size: 14px;
        }
        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }
        .badge-success { background: #d4edda; color: #155724; }
        .badge-error { background: #f8d7da; color: #721c24; }
        .btn-back {
            display: inline-block;
            background: #6c757d;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            margin-top: 20px;
        }
        .summary {
            background: <?php echo $allSuccess ? '#d4edda' : '#f8d7da'; ?>;
            color: <?php echo $allSuccess ? '#155724' : '#721c24'; ?>;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            text-align: center;
            font-weight: 600;
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 Test de Conexión con Discord</h1>
        
        <div class="summary">
            <?php if ($allSuccess): ?>
                ✅ Todos los tests pasaron correctamente
            <?php else: ?>
                ❌ Algunos tests fallaron
            <?php endif; ?>
        </div>
        
        <?php foreach ($testResults as $result): ?>
            <div class="test-result <?php echo $result['success'] ? 'success' : 'error'; ?>">
                <div class="test-name">
                    <?php echo htmlspecialchars($result['test']); ?>
                    <span class="badge <?php echo $result['success'] ? 'badge-success' : 'badge-error'; ?>">
                        <?php echo $result['success'] ? 'OK' : 'ERROR'; ?>
                    </span>
                </div>
                <div class="test-message"><?php echo htmlspecialchars($result['message']); ?></div>
            </div>
        <?php endforeach; ?>
        
        <a href="/discord/dashboard_discord.php" class="btn-back">← Volver al Dashboard</a>
    </div>
</body>
</html>
