<?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;
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="card">
  <div class="card-header d-flex align-items-center gap-3">
    <span class="topbar-page-icon"><i class="bx bx-transfer-alt"></i></span>
    <div><h4 class="mb-1">Migrar clientes para outro DNS</h4><p class="text-muted mb-0">Todos os clientes que usam o DNS atual serão atualizados para o novo servidor.</p></div>
  </div>
  <div class="card-body">
    <div class="alert alert-warning"><i class="bx bx-error-circle me-1"></i> Esta ação altera todos os registros encontrados. Confira os servidores antes de confirmar.</div>
    <form method="post" class="row g-3">
      <div class="col-12 col-lg-5"><label class="form-label" for="dns_atual">DNS atual</label><select name="dns_atual" id="dns_atual" class="form-select" required><?= getDnsOptions($db) ?></select></div>
      <div class="col-12 col-lg-2 d-flex align-items-end justify-content-center"><span class="topbar-page-icon"><i class="bx bx-right-arrow-alt"></i></span></div>
      <div class="col-12 col-lg-5"><label class="form-label" for="dns_nova">Novo DNS</label><select name="dns_nova" id="dns_nova" class="form-select" required><?= getDnsOptions($db) ?></select></div>
      <div class="col-12 d-flex justify-content-end"><button class="btn btn-primary" name="migrar" type="submit"><i class="bx bx-transfer"></i> Migrar clientes</button></div>
    </form>
  </div>
</div>
<?php if ($migracaoEfetuada): ?><div id="migrationSuccess" hidden data-redirect="dashboard.php"></div><?php endif; ?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
