<?php
include 'includes/header.php';

$db = new PDO("sqlite:api/.db.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$mensaje = "";

// Procesar migración
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['migrate_dns'])) {
    $old_url = trim($_POST['old_url']);
    $new_url = trim($_POST['new_url']);

    if (!empty($old_url) && !empty($new_url)) {
        $query = "UPDATE ibo SET url = :new_url WHERE url = :old_url";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':new_url', $new_url);
        $stmt->bindParam(':old_url', $old_url);
        $stmt->execute();
        $affected = $stmt->rowCount();
        $mensaje = "✅ Se actualizaron <strong>{$affected}</strong> usuarios con la nueva URL.";
    } else {
        $mensaje = "⚠️ Debes seleccionar ambas URLs.";
    }
}

// Obtener URLs de IBO
$stmt_urls = $db->prepare("SELECT url, COUNT(*) as cantidad FROM ibo GROUP BY url ORDER BY cantidad DESC");
$stmt_urls->execute();
$ibo_urls = $stmt_urls->fetchAll(PDO::FETCH_ASSOC);

// Obtener URLs de DNS
$stmt_dns = $db->prepare("SELECT * FROM dns ORDER BY title");
$stmt_dns->execute();
$dns_urls = $stmt_dns->fetchAll(PDO::FETCH_ASSOC);
?>

<script>
function mostrarCantidad(select) {
    const cantidades = JSON.parse(document.getElementById('cantidades_data').value);
    const seleccionada = select.value;
    const cantidad = cantidades[seleccionada] || 0;
    document.getElementById('usuarios_count').innerText = "Usuarios con esta URL: " + cantidad;
}
</script>

<div class="container-fluid">
    <div class="mx-auto" style="max-width: 900px;">
        <h1 class="title-outside-card mb-1">Migrar URL DNS</h1>

        <div class="card border-left-primary shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-color">
                    <i class="fas fa-network-wired"></i> Detalles de Migración
                </h6>
            </div>

            <div class="card-body">
                <div class="form-group">
                    <h4>🌐 Aquí podrás cambiar la URL DNS de manera masiva a los clientes 🚀</h4>
                </div>

                <?php if (!empty($mensaje)): ?>
                    <div class="alert alert-info"><?= $mensaje ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div class="form-group">
                        <label for="old_url"><strong>URL actual de los Usuarios:</strong></label>
                        <select class="form-control" name="old_url" onchange="mostrarCantidad(this)" required>
                            <option value="">-- Selecciona una URL --</option>
                            <?php foreach ($ibo_urls as $url): ?>
                                <option value="<?= htmlspecialchars($url['url']) ?>">
                                    <?= htmlspecialchars($url['url']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted" id="usuarios_count">Usuarios con esta URL: 0</small>
                    </div>

                    <div class="form-group">
                        <label for="new_url"><strong>Nueva URL para la migración:</strong></label>
                        <select class="form-control" name="new_url" required>
                            <option value="">-- Selecciona nueva URL --</option>
                            <?php foreach ($dns_urls as $dns): ?>
                                <option value="<?= htmlspecialchars($dns['url']) ?>">
                                    <?= htmlspecialchars($dns['title']) ?> (<?= htmlspecialchars($dns['url']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <button type="submit" name="migrate_dns" class="btn btn-success btn-icon-split">
                        <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                        <span class="text">Migrar DNS</span>
                    </button>

                    <input type="hidden" id="cantidades_data" value='<?= json_encode(array_column($ibo_urls, "cantidad", "url")) ?>'>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
