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

requireAdmin();

$pageTitle = 'Verificar Webhook';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'check_telegram') {
        $token = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
        
        $ch = curl_init('https://api.telegram.org/bot' . $token . '/getWebhookInfo');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $results['telegram'] = json_decode($response, true);
    }
}

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-webcam"></i> Verificar Webhook</h2>
</div>

<form method="POST" class="mb-4">
    <input type="hidden" name="action" value="check_telegram">
    <button type="submit" class="btn btn-primary">
        <i class="bi bi-search"></i> Verificar Webhook de Telegram
    </button>
</form>

<?php if (isset($results['telegram'])): ?>
    <?php if ($results['telegram']['ok']): ?>
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Estado del Webhook de Telegram</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($results['telegram']['result']['url'])): ?>
                    <p><strong>URL:</strong> <?= htmlspecialchars($results['telegram']['result']['url']) ?></p>
                    <p><strong>Tiene webhook:</strong> ✅ Sí</p>
                    <p><strong>Último error:</strong> <?= $results['telegram']['result']['last_error_message'] ?? 'Ninguno' ?></p>
                    <p><strong>Última sincronización:</strong> <?= date('d/m/Y H:i:s', $results['telegram']['result']['last_synchronize_ok_date'] ?? 0) ?></p>
                <?php else: ?>
                    <p class="text-muted">No hay webhook configurado</p>
                <?php endif; ?>
            </div>
        </div>
    <?php else: ?>
        <div class="alert alert-danger">
            Error: <?= htmlspecialchars($results['telegram']['description'] ?? 'Unknown error') ?>
        </div>
    <?php endif; ?>
<?php endif; ?>

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