<?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_dns_id = intval($_POST['old_dns_id']);
    $new_dns_id = intval($_POST['new_dns_id']);

    if ($old_dns_id > 0 && $new_dns_id > 0) {
        $stmt = $db->prepare("UPDATE playlist SET dns_id = :new_dns_id WHERE dns_id = :old_dns_id");
        $stmt->bindParam(':new_dns_id', $new_dns_id);
        $stmt->bindParam(':old_dns_id', $old_dns_id);
        $stmt->execute();
        $affected = $stmt->rowCount();
        $mensaje = "✅ Se actualizaron <strong>{$affected}</strong> usuarios con la nueva DNS.";
    } else {
        $mensaje = "⚠️ Debes seleccionar ambas DNS.";
    }
}

// Obtener DNS actuales usadas en playlist
$stmt_urls = $db->prepare("
    SELECT dns.id, dns.title, dns.url, COUNT(playlist.id) as cantidad 
    FROM playlist 
    LEFT JOIN dns ON dns.id = playlist.dns_id 
    GROUP BY dns.id 
    ORDER BY cantidad DESC
");
$stmt_urls->execute();
$playlist_dns = $stmt_urls->fetchAll(PDO::FETCH_ASSOC);

// Obtener todas las DNS disponibles
$stmt_all_dns = $db->prepare("SELECT * FROM dns ORDER BY title");
$stmt_all_dns->execute();
$dns_urls = $stmt_all_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 DNS: " + cantidad;
}
</script>
<div class="col-md-6 mx-auto">
<div class="card bg-dark text-white">
    <div class="mx-auto" style="max-width: 900px;">
        <h1 class="title-outside-card mb-1">Migrar DNS</h1>
        <div class="card border-left-primary shadow mb-4">
        <div class="card bg-dark text-white">
            <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="card bg-dark text-white">
                <div class="form-group">
                    <h4>🌐 Aquí podrás cambiar la 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_dns_id"><strong>DNS actual de los usuarios:</strong></label>
                        <select class="form-control" name="old_dns_id" onchange="mostrarCantidad(this)" required>
                            <option value="">-- Selecciona una DNS --</option>
                            <?php foreach ($playlist_dns as $dns): ?>
                                <option value="<?= $dns['id'] ?>">
                                    <?= htmlspecialchars($dns['title']) ?> (<?= htmlspecialchars($dns['url']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <small class="text-muted" id="usuarios_count">Usuarios con esta DNS: 0</small>
                    </div>
                    <div class="form-group">
                        <label for="new_dns_id"><strong>Nueva DNS para la migración:</strong></label>
                        <select class="form-control" name="new_dns_id" required>
                            <option value="">-- Selecciona nueva DNS --</option>
                            <?php foreach ($dns_urls as $dns): ?>
                                <option value="<?= $dns['id'] ?>">
                                    <?= 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($playlist_dns, "cantidad", "id")) ?>'>
                </form>
            </div>
        </div>
    </div>
</div>
<?php include 'includes/footer.php'; ?>
