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

requireAdmin();

$pageTitle = 'Configurar Webhooks';

$results = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'set_telegram') {
        $token = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
        $webhookUrl = $_POST['webhook_url'];
        $webhookToken = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');
        
        $fullUrl = $webhookUrl . '?auth_token=' . $webhookToken;
        
        $ch = curl_init('https://api.telegram.org/bot' . $token . '/setWebhook');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['url' => $fullUrl]);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $results['telegram_set'] = json_decode($response, true);
    }
}

$currentUrl = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-gear"></i> Configurar Webhooks</h2>
</div>

<?php if (isset($results['telegram_set'])): ?>
    <?php if ($results['telegram_set']['ok']): ?>
        <div class="alert alert-success">Webhook de Telegram configurado correctamente</div>
    <?php else: ?>
        <div class="alert alert-danger">Error: <?= htmlspecialchars($results['telegram_set']['description'] ?? 'Unknown error') ?></div>
    <?php endif; ?>
<?php endif; ?>

<div class="row">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-telegram"></i> Webhook de Telegram</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="set_telegram">
                    
                    <div class="mb-3">
                        <label class="form-label">URL del webhook</label>
                        <input type="text" name="webhook_url" class="form-control" value="<?= $currentUrl ?>/telegram_bot_webhook.php" required>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save"></i> Guardar
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-info-circle"></i> Información</h5>
            </div>
            <div class="card-body">
                <p class="text-muted">
                    Los webhooks permiten que Telegram y Discord envíen eventos a tu aplicación en tiempo real.
                </p>
                <ul>
                    <li><strong>Telegram:</strong> Procesa mensajes y comandos</li>
                </ul>
            </div>
        </div>
    </div>
</div>

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