<?php
require_once __DIR__ . '/../../vendor/autoload.php';

use App\Controllers\TelegramController;
use App\Middleware\RoleMiddleware;
use App\Services\AuthService;

RoleMiddleware::admin();
$auth = new AuthService();

$controller = new TelegramController();

// Manejar acciones
if (isPost()) {
    $action = post('action');
    if ($action === 'setup') {
        $controller->setup();
    } elseif ($action === 'delete') {
        $controller->delete();
    }
}

// Obtener datos para la vista
$data = $controller->index();
$info = $data['info'];
$defaultUrl = $data['defaultUrl'];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Telegram - Contenedor Ibiza</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .status-box {
            padding: 1.5rem;
            border-radius: 8px;
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        .status-item {
            margin-bottom: 0.5rem;
        }
        .status-label {
            font-weight: 600;
            color: #64748b;
        }
        .status-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.85rem;
            font-weight: 600;
        }
        .status-active { background-color: #dcfce7; color: #166534; }
        .status-inactive { background-color: #fee2e2; color: #991b1b; }
    </style>
</head>
<body>
    <?php include '../partials/navbar.php'; ?>

    <div class="container">
        <h1 class="card-title mb-4">🤖 Gestión de Bot Telegram</h1>

        <?php if ($msg = flash('success')): ?>
            <div class="alert alert-success"><?= e($msg) ?></div>
        <?php endif; ?>
        
        <?php if ($msg = flash('error')): ?>
            <div class="alert alert-danger"><?= e($msg) ?></div>
        <?php endif; ?>

        <div class="card">
            <h3 class="mb-4">Estado del Webhook</h3>
            
            <div class="status-box">
                <?php if ($info && !empty($info['url'])): ?>
                    <div class="status-item">
                        <span class="status-label">Estado:</span>
                        <span class="status-badge status-active">Activo</span>
                    </div>
                    <div class="status-item">
                        <span class="status-label">URL:</span>
                        <code><?= e($info['url']) ?></code>
                    </div>
                    <div class="status-item">
                        <span class="status-label">Mensajes pendientes:</span>
                        <?= e($info['pending_update_count'] ?? 0) ?>
                    </div>
                    <?php if (!empty($info['last_error_message'])): ?>
                        <div class="status-item text-danger" style="margin-top: 1rem;">
                            <span class="status-label">Último error:</span>
                            <?= e($info['last_error_message']) ?> 
                            (<?= date('d/m/Y H:i', $info['last_error_date'] ?? time()) ?>)
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="status-item">
                        <span class="status-label">Estado:</span>
                        <span class="status-badge status-inactive">Inactivo / No configurado</span>
                    </div>
                <?php endif; ?>
            </div>

            <h3 class="mb-4">Configuración</h3>
            
            <form method="POST" class="mb-4">
                <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                <input type="hidden" name="action" value="setup">
                
                <div class="form-group">
                    <label>URL del Webhook (HTTPS requerido)</label>
                    <input type="url" name="webhook_url" class="form-control" 
                           value="<?= e($defaultUrl) ?>" required>
                    <small style="display: block; margin-top: 0.5rem; color: #64748b;">
                        Esta es la URL a la que Telegram enviará los mensajes. Debe ser pública y segura (HTTPS).
                        Por defecto, se sugiere la URL interna de tu sitio.
                    </small>
                </div>
                
                <button type="submit" class="btn btn-primary">
                    💾 Guardar Configuración
                </button>
            </form>

            <?php if ($info && !empty($info['url'])): ?>
                <hr style="margin: 2rem 0; border: 0; border-top: 1px solid #e2e8f0;">
                
                <h3 class="mb-4 text-danger">Zona de Peligro</h3>
                
                <form method="POST" onsubmit="return confirm('¿Estás seguro de desactivar el bot? Dejará de responder mensajes.');">
                    <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
                    <input type="hidden" name="action" value="delete">
                    
                    <button type="submit" class="btn btn-danger">
                        🚫 Borrar Webhook
                    </button>
                    <small style="display: block; margin-top: 0.5rem; color: #64748b;">
                        Esto desconectará el bot de tu servidor.
                    </small>
                </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
