<?php
session_start();

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

$db->exec("
CREATE TABLE IF NOT EXISTS dns (
    nome TEXT PRIMARY KEY,
    url TEXT NOT NULL
)
");

$db->exec("
CREATE TABLE IF NOT EXISTS usuarios (
    mac TEXT PRIMARY KEY,
    dns TEXT,
    username TEXT,
    password TEXT,
    status TEXT
)
");

function getDnsOptions($db){
    $opt = "";
    $res = $db->query("SELECT url FROM dns ORDER BY nome ASC");
    while($r = $res->fetch(PDO::FETCH_ASSOC)){
        $opt .= "<option value='".htmlspecialchars($r["url"])."'>".htmlspecialchars($r["url"])."</option>";
    }
    return $opt;
}

$migracaoEfetuada = false;

if(isset($_POST["migrar"])){

    $dns_atual = $_POST["dns_atual"];
    $dns_nova  = $_POST["dns_nova"];

    if($dns_atual !== $dns_nova){

        $stmt = $db->prepare("UPDATE usuarios SET dns = ? WHERE dns = ?");
        $stmt->execute([$dns_nova, $dns_atual]);

        $migracaoEfetuada = true;
    }
}

include "./includes/header.php";
?>

<div class="card radius-10">
<div class="card-body">
<h4>Migrar DNS</h4>

<form method="post">

<div class="form-group mb-4">
<label>DNS Atual</label>
<select name="dns_atual" class="form-control" required>
<?= getDnsOptions($db) ?>
</select>
</div>

<div class="form-group mb-4">
<label>DNS Nova</label>
<select name="dns_nova" class="form-control" required>
<?= getDnsOptions($db) ?>
</select>
</div>

<button class="btn btn-primary" name="migrar">Migrar</button>

</form>
</div>
</div>

<?php
if($migracaoEfetuada){
    echo "<script>
    Swal.fire({
        icon:'success',
        title:'DNS migrada',
        text:'Todos os usuários agora usam a nova DNS'
    }).then(()=>{ window.location.href='dashboard.php'; });
    </script>";
}
include "./includes/footer.php";
?>
