<?php
require_once __DIR__.'/includes/config.php';
require_login();
$db=db();

$rows=[];
$q=trim($_GET['q'] ?? '');
if($q!==''){
    $st=$db->prepare("SELECT * FROM client_macs WHERE mac LIKE :q OR cliente_nome LIKE :q OR usuario LIKE :q ORDER BY id DESC");
    $st->bindValue(':q','%'.$q.'%',SQLITE3_TEXT);
    $res=$st->execute();
}else{
    $res=$db->query("SELECT * FROM client_macs ORDER BY id DESC");
}
while($r=$res->fetchArray(SQLITE3_ASSOC)) $rows[]=$r;

include __DIR__.'/includes/header.php';
?>
<div class="card">
<h3>🌐 DNS/VPN por Cliente</h3>
<p class="muted">Escolha o cliente/MAC e configure DNS individual: Google DNS, Cloudflare DNS, OpenDNS ou Desativado.</p>
<form method="get" style="display:flex;gap:10px;align-items:end;flex-wrap:wrap">
<div style="flex:1;min-width:260px"><label>Pesquisar</label><input name="q" value="<?=h($q)?>" placeholder="MAC, cliente ou usuário"></div>
<button class="btn dark">Buscar</button>
<a class="btn" href="clientes_macs.php">Dispositivos APK</a>
</form>
<table>
<tr><th>ID</th><th>MAC/ID</th><th>Cliente</th><th>Dono</th><th>DNS Atual</th><th>Ação</th></tr>
<?php foreach($rows as $r): $ds=$r['dns_service'] ?? 'off'; ?>
<tr>
<td><?=h($r['id'])?></td>
<td><b><?=h($r['mac'])?></b></td>
<td><?=h($r['cliente_nome'])?><br><span class="muted"><?=h($r['usuario'])?></span></td>
<td><?=h(get_owner_label($r['owner_type'],$r['owner_id']))?></td>
<td><?=$ds==='off'?'<span class="bad">DESATIVADO</span>':'<span class="pill">'.h(strtoupper($ds)).'</span>'?><br><span class="muted"><?=h(($r['dns_primary'] ?? '').(($r['dns_secondary'] ?? '') ? ' / '.$r['dns_secondary'] : ''))?></span></td>
<td><a class="btn" href="dns_cliente.php?id=<?=h($r['id'])?>">Configurar DNS/VPN</a></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
