<?php
session_start();

// Função para obter as DNS do banco de dados e criar as opções do seletor
function getDnsOptions() {
    $dbDns = new SQLite3("./api/db/studiolivecode_dns.db");
    $results = $dbDns->query("SELECT url FROM dns");
    $options = "";
    while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
        $options .= "<option value='" . $row['url'] . "'>" . $row['url'] . "</option>";
    }
    $dbDns->close();
    return $options;
}

$migracaoEfetuada = false;

if (isset($_POST["migrar"])) {
    $dns_atual = $_POST["dns_atual"];
    $dns_nova = $_POST["dns_nova"];
    
    $dbClientes = new SQLite3('./api/db/studiolivecode_clientes.db');
    
    // Atualizar a coluna dns
    $updateDnsQuery = "UPDATE ibo SET dns = '$dns_nova' WHERE dns = '$dns_atual'";
    $dbClientes->exec($updateDnsQuery);

    // Atualizar a coluna url
    $updateUrlQuery = "UPDATE ibo SET url = REPLACE(url, '$dns_atual', '$dns_nova') WHERE url LIKE '%$dns_atual%'";
    $dbClientes->exec($updateUrlQuery);

    $dbClientes->close();
    
    $migracaoEfetuada = true;
}
?>

<?php include './includes/header.php'; ?>
<div class="card radius-10">
    <div class="card-body">
        <h4 class="card-title">Troca De DNS</h4>
        <form method="post">
            <div class="form-group mb-4">
                <label class="control-label" for="dns_atual"><strong>DNS Antiga</strong></label>
                <div class="input-group">
                    <select class="form-control" id="dns_atual" name="dns_atual" required>
                        <?php echo getDnsOptions(); ?>
                    </select>
                </div>
            </div>
            <div class="form-group mb-4">
                <label class="control-label" for="dns_nova"><strong>DNS Nova</strong></label>
                <div class="input-group">
                    <select class="form-control" id="dns_nova" name="dns_nova" required>
                        <?php echo getDnsOptions(); ?>
                    </select>
                </div>
            </div>
            <div class="form-group mb-4">
                <button type="submit" name="migrar" class="btn btn-primary"><i class='bx bx-check mr-1'></i>Trocar</button>
            </div>
        </form>
    </div>
</div>

<?php
if ($migracaoEfetuada) {
    ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Migração efetuada com sucesso!',
            html: '<p>Agora todas as DNS e listas M3U8 têm a nova DNS escolhida.</p>',
            confirmButtonText: 'Fechar',
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'dashboard.php';
            }
        });
    </script>
    <?php
}
?>

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