<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../includes/env_loader.php';

requireAdmin();

$pageTitle = 'Test de Conexión Discord';

$results = [];
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'test') {
    $token = $_ENV['DISCORD_BOT_TOKEN'] ?? getenv('DISCORD_BOT_TOKEN');
    
    if (empty($token)) {
        $error = 'Token de bot no configurado';
    } else {
        $ch = curl_init('https://discord.com/api/v10/users/@me');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bot ' . $token]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $userData = json_decode($response, true);
        
        $results['user'] = $userData;
        $results['http_code'] = $httpCode;
        
        if ($httpCode === 200) {
            $guildId = $_ENV['DISCORD_GUILD_ID'] ?? getenv('DISCORD_GUILD_ID');
            
            if ($guildId) {
                $ch = curl_init("https://discord.com/api/v10/guilds/{$guildId}");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bot ' . $token]);
                $guildResponse = curl_exec($ch);
                $guildCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                $results['guild'] = json_decode($guildResponse, true);
                $results['guild_code'] = $guildCode;
            }
            
            $ch = curl_init('https://discord.com/api/v10/channels');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bot ' . $token]);
            $channelsResponse = curl_exec($ch);
            curl_close($ch);
            
            $results['channels'] = json_decode($channelsResponse, true);
        }
        
        if ($_POST['test_message'] ?? false) {
            $channelId = $_POST['test_channel_id'] ?? '';
            
            if ($channelId) {
                $testMessage = $_POST['test_message_text'] ?? '✅ Prueba de conexión desde el sistema de mensajería';
                
                $ch = curl_init("https://discord.com/api/v10/channels/{$channelId}/messages");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Authorization: Bot ' . $token,
                    'Content-Type: application/json'
                ]);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['content' => $testMessage]));
                $msgResponse = curl_exec($ch);
                $msgCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                $results['test_message'] = json_decode($msgResponse, true);
                $results['test_message_code'] = $msgCode;
            }
        }
    }
}

require_once __DIR__ . '/../templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-discord"></i> Test de Conexión Discord</h2>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if (!empty($results)): ?>
    <?php if ($results['http_code'] === 200): ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle"></i> <strong>Conexión exitosa!</strong> El bot está conectado como <strong><?= htmlspecialchars($results['user']['username']) ?></strong>
        </div>
    <?php else: ?>
        <div class="alert alert-danger">
            <i class="bi bi-x-circle"></i> <strong>Error de conexión:</strong> Código HTTP <?= $results['http_code'] ?>
            <?php if (isset($results['user']['message'])): ?>
                <br><?= htmlspecialchars($results['user']['message']) ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($results['guild'])): ?>
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Servidor</h5>
            </div>
            <div class="card-body">
                <?php if ($results['guild_code'] === 200): ?>
                    <p><strong>Nombre:</strong> <?= htmlspecialchars($results['guild']['name']) ?></p>
                    <p><strong>ID:</strong> <?= htmlspecialchars($results['guild']['id']) ?></p>
                    <p><strong>Miembros:</strong> <?= $results['guild']['approximate_member_count'] ?? 'N/A' ?></p>
                <?php else: ?>
                    <div class="alert alert-warning">Error al obtener servidor: Código <?= $results['guild_code'] ?></div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
    
    <?php if (isset($results['test_message'])): ?>
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Prueba de Envío</h5>
            </div>
            <div class="card-body">
                <?php if ($results['test_message_code'] === 200): ?>
                    <div class="alert alert-success"><i class="bi bi-check-circle"></i> Mensaje enviado correctamente</div>
                <?php else: ?>
                    <div class="alert alert-danger">Error al enviar mensaje: Código <?= $results['test_message_code'] ?></div>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
<?php endif; ?>

<div class="card border-0 shadow-sm mb-4">
    <div class="card-header bg-white border-0">
        <h5 class="mb-0">Probar Conexión</h5>
    </div>
    <div class="card-body">
        <form method="POST">
            <input type="hidden" name="action" value="test">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-plug"></i> Verificar Conexión
            </button>
        </form>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white border-0">
        <h5 class="mb-0">Enviar Mensaje de Prueba</h5>
    </div>
    <div class="card-body">
        <form method="POST">
            <input type="hidden" name="action" value="test">
            <input type="hidden" name="test_message" value="1">
            
            <div class="mb-3">
                <label class="form-label">ID del Canal</label>
                <input type="text" name="test_channel_id" class="form-control" placeholder="123456789012345678">
            </div>
            
            <div class="mb-3">
                <label class="form-label">Mensaje</label>
                <textarea name="test_message_text" class="form-control" rows="3">✅ Prueba de conexión desde el sistema de mensajería</textarea>
            </div>
            
            <button type="submit" class="btn btn-success">
                <i class="bi bi-send"></i> Enviar Mensaje
            </button>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
