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

requireAdmin();

$pageTitle = 'Configurar Webhook de Telegram';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $token = $_ENV['TELEGRAM_BOT_TOKEN'] ?? getenv('TELEGRAM_BOT_TOKEN');
    $webhookUrl = $_POST['webhook_url'] ?? '';
    $webhookToken = $_ENV['TELEGRAM_WEBHOOK_TOKEN'] ?? getenv('TELEGRAM_WEBHOOK_TOKEN');
    
    if ($_POST['action'] === 'set') {
        $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['set'] = json_decode($response, true);
        
    } elseif ($_POST['action'] === 'delete') {
        $ch = curl_init('https://api.telegram.org/bot' . $token . '/deleteWebhook');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $results['delete'] = json_decode($response, true);
        
    } elseif ($_POST['action'] === 'check') {
        $ch = curl_init('https://api.telegram.org/bot' . $token . '/getWebhookInfo');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $results['info'] = json_decode($response, true);
    }
}

// Telegram requiere HTTPS obligatoriamente para webhooks
$protocol = 'https';
$host = $_ENV['APP_URL'] ?? getenv('APP_URL') ?? $_SERVER['HTTP_HOST'];
// Remover protocolo y trailing slash si existen en APP_URL
$host = preg_replace('/^https?:\/\//', '', $host);
$host = rtrim($host, '/');
$currentUrl = $protocol . '://' . $host . '/telegram/webhook/telegram_bot_webhook.php';

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-telegram"></i> Configurar Webhook de Telegram</h2>
</div>

<div class="alert alert-warning">
    <i class="bi bi-exclamation-triangle"></i> <strong>Importante:</strong> Telegram requiere obligatoriamente HTTPS con un certificado SSL válido. 
    Asegúrate de que tu dominio tenga SSL activado. La URL propuesta usa: <code><?= htmlspecialchars($currentUrl) ?></code>
</div>

<?php if (!empty($results)): ?>
    <?php if (isset($results['set'])): ?>
        <?php if ($results['set']['ok']): ?>
            <div class="alert alert-success">
                <i class="bi bi-check-circle"></i> <strong>Webhook configurado correctamente!</strong>
            </div>
        <?php else: ?>
            <div class="alert alert-danger">
                <i class="bi bi-x-circle"></i> <strong>Error:</strong> <?= htmlspecialchars($results['set']['description'] ?? 'Unknown error') ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
    
    <?php if (isset($results['delete'])): ?>
        <?php if ($results['delete']['ok']): ?>
            <div class="alert alert-success">Webhook eliminado correctamente</div>
        <?php else: ?>
            <div class="alert alert-danger">Error: <?= htmlspecialchars($results['delete']['description'] ?? 'Unknown error') ?></div>
        <?php endif; ?>
    <?php endif; ?>
    
    <?php if (isset($results['info'])): ?>
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Estado Actual del Webhook</h5>
            </div>
            <div class="card-body">
                <?php if ($results['info']['ok'] && !empty($results['info']['result']['url'])): ?>
                    <p><strong>URL:</strong> <?= htmlspecialchars($results['info']['result']['url']) ?></p>
                    <p><strong>Activo:</strong> <?= $results['info']['result']['url'] ? '✅ Sí' : '❌ No' ?></p>
                    <p><strong>Errores:</strong> <?= $results['info']['result']['last_error_message'] ?? 'Ninguno' ?></p>
                <?php else: ?>
                    <p class="text-muted">No hay webhook configurado</p>
                <?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">URL del Webhook</h5>
    </div>
    <div class="card-body">
        <p class="text-muted">URL base para el webhook (se añadirá automáticamente el token de autenticación):</p>
        <div class="input-group">
            <input type="text" class="form-control" value="<?= htmlspecialchars($currentUrl) ?>" readonly>
            <button class="btn btn-outline-secondary" onclick="navigator.clipboard.writeText('<?= htmlspecialchars($currentUrl) ?>')">
                <i class="bi bi-clipboard"></i>
            </button>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Configurar Webhook</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="set">
                    <div class="mb-3">
                        <label class="form-label">URL del webhook</label>
                        <input type="text" name="webhook_url" class="form-control" value="<?= htmlspecialchars($currentUrl) ?>" required>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-plug"></i> Establecer Webhook
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0">Opciones</h5>
            </div>
            <div class="card-body">
                <form method="POST" class="mb-2">
                    <input type="hidden" name="action" value="check">
                    <button type="submit" class="btn btn-secondary w-100 mb-2">
                        <i class="bi bi-info-circle"></i> Verificar Estado
                    </button>
                </form>
                
                <form method="POST" onsubmit="return confirm('¿Eliminar el webhook?');">
                    <input type="hidden" name="action" value="delete">
                    <button type="submit" class="btn btn-danger w-100">
                        <i class="bi bi-trash"></i> Eliminar Webhook
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

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