<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$db = new SQLite3('./a/.eggziedb.db');

$message = $msgType = '';

$dns_list = [];
$res = $db->query("SELECT DISTINCT url, COUNT(id) as total FROM ibo WHERE url IS NOT NULL AND url != '' GROUP BY url ORDER BY url ASC");
while ($row = $res->fetchArray(SQLITE3_ASSOC)) $dns_list[] = $row;

if (isset($_POST['action'])) {
    $new_dns = trim($_POST['new_dns']);
    $action  = $_POST['action'];
    if (empty($new_dns)) {
        $message = 'Informe o novo DNS antes de continuar.';
        $msgType = 'danger';
    } else {
        $safe = SQLite3::escapeString($new_dns);
        if ($action === 'all') {
            $db->exec("UPDATE ibo SET url='$safe'");
            $message = 'DNS atualizado em <strong>'.$db->changes().'</strong> cliente(s).';
            $msgType = 'success';
        } elseif ($action === 'by_dns' && !empty($_POST['old_dns'])) {
            $old = SQLite3::escapeString(trim($_POST['old_dns']));
            $db->exec("UPDATE ibo SET url='$safe' WHERE url='$old'");
            $message = 'DNS atualizado em <strong>'.$db->changes().'</strong> cliente(s) que usavam <code>'.htmlspecialchars($_POST['old_dns']).'</code>.';
            $msgType = 'success';
        }
        // reload list
        $dns_list = [];
        $r2 = $db->query("SELECT DISTINCT url, COUNT(id) as total FROM ibo WHERE url IS NOT NULL AND url != '' GROUP BY url ORDER BY url ASC");
        while ($row = $r2->fetchArray(SQLITE3_ASSOC)) $dns_list[] = $row;
    }
}

$total_clients = $db->querySingle("SELECT COUNT(id) FROM ibo") ?: 0;

include 'includes/header.php';
?>

<div class="page-header">
  <h1><i class="fas fa-globe" style="color:var(--accent);font-size:18px"></i> DNS em Massa</h1>
  <p>Substitua o servidor DNS de múltiplos clientes de uma só vez.</p>
</div>

<?php if ($message): ?>
  <div class="u-alert u-alert-<?php echo $msgType; ?>">
    <i class="fas fa-<?php echo $msgType==='success'?'check-circle':'exclamation-circle'; ?>"></i>
    <span><?php echo $message; ?></span>
  </div>
<?php endif; ?>

<div class="grid-2 mb-4">

  <!-- ── Card: Por DNS específico ──────────────────────────── -->
  <div class="u-card accent-left glow">
    <div class="u-card-header">
      <span class="u-card-title"><i class="fas fa-exchange-alt"></i> Substituir DNS Específico</span>
    </div>
    <div class="u-card-body">
      <p style="font-size:12.5px;color:var(--text-muted);margin-bottom:16px">
        Escolha um DNS cadastrado e substitua-o por um novo.
        Apenas os clientes com o DNS selecionado serão alterados.
      </p>
      <form method="post" id="form-by-dns">
        <input type="hidden" name="action" value="by_dns">
        <div class="form-group">
          <label class="form-label">DNS Atual <span class="req">*</span></label>
          <?php if (empty($dns_list)): ?>
            <p style="color:var(--warning);font-size:13px"><i class="fas fa-exclamation-triangle"></i> Nenhum DNS cadastrado.</p>
          <?php else: ?>
            <select name="old_dns" id="old-dns-select" class="u-select" required>
              <option value="">— Selecione o DNS antigo —</option>
              <?php foreach ($dns_list as $d): ?>
                <option value="<?php echo htmlspecialchars($d['url']); ?>">
                  <?php echo htmlspecialchars($d['url']); ?> (<?php echo $d['total']; ?> cliente<?php echo $d['total']>1?'s':''; ?>)
                </option>
              <?php endforeach; ?>
            </select>
          <?php endif; ?>
        </div>
        <div class="form-group">
          <label class="form-label">Novo DNS <span class="req">*</span></label>
          <input type="text" name="new_dns" class="u-input" placeholder="http://novo-servidor.com" required>
        </div>
        <button type="submit" class="u-btn u-btn-primary">
          <i class="fas fa-sync-alt"></i> Aplicar Substituição
        </button>
      </form>
    </div>
  </div>

  <!-- ── Card: Todos os clientes ───────────────────────────── -->
  <div class="u-card danger-left glow">
    <div class="u-card-header">
      <span class="u-card-title danger"><i class="fas fa-exclamation-triangle"></i> Substituir em Todos</span>
    </div>
    <div class="u-card-body">
      <div class="u-alert u-alert-warning mb-3">
        <i class="fas fa-bolt"></i>
        <span>Esta ação atualiza o DNS de <strong>todos os <?php echo $total_clients; ?> cliente(s)</strong> cadastrados. Use com cuidado.</span>
      </div>
      <form method="post" onsubmit="return confirm('Confirma? Esta ação altera o DNS de TODOS os clientes.')">
        <input type="hidden" name="action" value="all">
        <div class="form-group">
          <label class="form-label">Novo DNS para todos <span class="req">*</span></label>
          <input type="text" name="new_dns" class="u-input" placeholder="http://novo-servidor.com" required>
        </div>
        <button type="submit" class="u-btn u-btn-danger">
          <i class="fas fa-bolt"></i> Aplicar em Todos
        </button>
      </form>
    </div>
  </div>

</div><!-- /grid-2 -->

<!-- DNS cadastrados -->
<div class="u-card violet-left">
  <div class="u-card-header">
    <span class="u-card-title violet"><i class="fas fa-list"></i> DNS Cadastrados</span>
    <span class="u-badge u-badge-violet"><?php echo count($dns_list); ?> servidor(es)</span>
  </div>
  <div class="u-card-body">
    <?php if (empty($dns_list)): ?>
      <p style="color:var(--text-muted);font-size:13px">Nenhum DNS cadastrado.</p>
    <?php else: ?>
      <?php foreach ($dns_list as $i => $d): ?>
      <div class="dns-list-item">
        <div>
          <div class="dns-list-url"><?php echo htmlspecialchars($d['url']); ?></div>
          <div style="font-size:11px;color:var(--text-muted);margin-top:3px">
            <?php echo $d['total']; ?> cliente<?php echo $d['total']>1?'s':''; ?>
          </div>
        </div>
        <button type="button" class="u-btn u-btn-ghost u-btn-sm"
                onclick="prefill(<?php echo htmlspecialchars(json_encode($d['url'])); ?>)">
          <i class="fas fa-edit" style="color:var(--accent)"></i> Substituir este
        </button>
      </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</div>

<div class="mt-3">
  <a href="users.php" class="u-btn u-btn-ghost">
    <i class="fas fa-arrow-left"></i> Voltar para Usuários
  </a>
</div>

<script>
function prefill(dns) {
    var sel = document.getElementById('old-dns-select');
    if (sel) {
        for (var i = 0; i < sel.options.length; i++) {
            if (sel.options[i].value === dns) { sel.selectedIndex = i; break; }
        }
        sel.closest('.u-card').scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}
</script>

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