<?php
// Configuración
$botToken = '8469229183:AAEVIV5e7rjDXKNgFTX0dnCW6JWB88X4p2I';
$webhookToken = 'webhook_secure_token_12345';
$domain = 'pruebaspons.duckdns.org';
$webhookUrl = "https://{$domain}/bot/telegram_bot_webhook.php?auth_token=" . urlencode($webhookToken);

// 1. Eliminar webhook existente
$apiUrl = "https://api.telegram.org/bot{$botToken}/deleteWebhook";
$ch = curl_init($apiUrl);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true]);
$response = curl_exec($ch);
curl_close($ch);

echo "Webhook eliminado. Configurando nuevo webhook...\n";

// 2. Configurar nuevo webhook
$apiUrl = "https://api.telegram.org/bot{$botToken}/setWebhook";
$postData = [
    'url' => $webhookUrl,
    'max_connections' => 40,
    'allowed_updates' => json_encode(['message', 'callback_query'])
];

$ch = curl_init($apiUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $postData,
    CURLOPT_TIMEOUT => 10
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = json_decode($response, true);
curl_close($ch);

// Mostrar resultados
echo "Respuesta (HTTP $httpCode): ";
echo ($result['ok'] ?? false) ? "✅ Éxito" : "❌ Error: " . ($result['description'] ?? 'Desconocido');
echo "\nURL: " . ($result['result']['url'] ?? 'N/A') . "\n";

// 3. Verificar configuración actual
$apiUrl = "https://api.telegram.org/bot{$botToken}/getWebhookInfo";
$result = json_decode(file_get_contents($apiUrl), true);

if ($result['ok'] ?? false) {
    echo "\nEstado actual del webhook:\n";
    echo "URL: " . ($result['result']['url'] ?? 'No configurado') . "\n";
    echo "Errores recientes: " . ($result['result']['last_error_message'] ?? 'Ninguno') . "\n";
}
