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

$id=(int)($_GET['id'] ?? $_POST['id'] ?? 0);
$st=$db->prepare('SELECT * FROM client_macs WHERE id=:id');
$st->bindValue(':id',$id,SQLITE3_INTEGER);
$client=$st->execute()->fetchArray(SQLITE3_ASSOC);
if(!$client){ include __DIR__.'/includes/header.php'; echo '<div class="card"><h3>Cliente não encontrado.</h3><p><a class="btn" href="clientes_macs.php">Voltar</a></p></div>'; include __DIR__.'/includes/footer.php'; exit; }

$services=[
 'google'=>['Google DNS','8.8.8.8','8.8.4.4','🔵'],
 'cloudflare'=>['Cloudflare DNS','1.1.1.1','1.0.0.1','🟠'],
 'opendns'=>['OpenDNS','208.67.222.222','208.67.220.220','🌐'],
 'off'=>['Desativar DNS','','','OFF']
];

if($_SERVER['REQUEST_METHOD']==='POST'){
    $service=$_POST['dns_service'] ?? 'off';
    if(!isset($services[$service])) $service='off';
    $active=$service==='off'?0:1;
    $primary=$services[$service][1];
    $secondary=$services[$service][2];
    $st=$db->prepare('UPDATE client_macs SET dns_service=:s,dns_active=:a,dns_primary=:p,dns_secondary=:sec,updated_at=CURRENT_TIMESTAMP WHERE id=:id');
    $st->bindValue(':s',$service,SQLITE3_TEXT);
    $st->bindValue(':a',$active,SQLITE3_INTEGER);
    $st->bindValue(':p',$primary,SQLITE3_TEXT);
    $st->bindValue(':sec',$secondary,SQLITE3_TEXT);
    $st->bindValue(':id',$id,SQLITE3_INTEGER);
    $st->execute();
    header('Location: dns_cliente.php?id='.$id.'&ok=1'); exit;
}

$current=$client['dns_service'] ?? 'off';
if(!isset($services[$current])) $current='off';
include __DIR__.'/includes/header.php';
?>
<style>
.dns-shell{border:1px solid rgba(255,138,0,.20);border-radius:18px;overflow:hidden;background:linear-gradient(145deg,rgba(17,24,35,.98),rgba(8,12,18,.98));box-shadow:0 18px 50px rgba(0,0,0,.45)}
.dns-top{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px;padding:14px;background:rgba(255,255,255,.035);border-bottom:1px solid #263244}
.dns-info{padding:13px;border:1px solid #303b4d;border-radius:13px;background:#111923}.dns-info b{display:block;margin-top:5px}
.dns-tabs{display:flex;gap:8px;padding:16px;border-bottom:1px solid #263244}.dns-tab{padding:12px 20px;border-radius:10px;background:#141c28;color:#cfd6e4;font-weight:800}.dns-tab.active{background:linear-gradient(90deg,#b20e17,#e21b23);color:#fff}
.dns-body{padding:18px}.dns-option{display:flex;align-items:center;gap:18px;padding:16px 18px;margin:12px 0;border:1px solid #303b4d;border-radius:13px;background:linear-gradient(90deg,rgba(255,255,255,.045),rgba(255,255,255,.025));cursor:pointer}
.dns-option.active{background:linear-gradient(90deg,#bd121b,#9d1219);border-color:#ef3038;box-shadow:0 0 28px rgba(255,0,0,.12)}
.dns-radio{width:24px;height:24px;border:3px solid #b9c2d0;border-radius:50%;display:inline-block;position:relative;flex:0 0 auto}.dns-option.active .dns-radio{border-color:#fff}.dns-option.active .dns-radio:after{content:'';position:absolute;left:5px;top:5px;width:8px;height:8px;background:#fff;border-radius:50%}
.dns-icon{font-size:31px;width:46px;text-align:center}.dns-title{font-size:18px;font-weight:900}.dns-sub{color:#b8c0cd;margin-top:4px}.dns-alert{margin-top:18px;border:1px solid rgba(49,132,253,.45);background:rgba(13,110,253,.10);padding:16px;border-radius:12px;color:#67b1ff}
.dns-actions{display:flex;justify-content:flex-end;gap:12px;margin-top:20px}.pill-ok{display:inline-block;background:#1ecb67;color:#fff;padding:6px 13px;border-radius:18px;font-weight:900}.pill-off{display:inline-block;background:#d71920;color:#fff;padding:6px 13px;border-radius:18px;font-weight:900}
</style>
<div class="card">
    <h2>Editar Cliente / MAC</h2>
    <?php if(isset($_GET['ok'])): ?><p class="ok">DNS salvo com sucesso.</p><?php endif; ?>
    <div class="dns-shell">
        <div class="dns-top">
            <div class="dns-info">Nome<b><?=h($client['cliente_nome'] ?: 'Cliente')?></b></div>
            <div class="dns-info">Usuário<b><?=h($client['usuario'])?></b></div>
            <div class="dns-info">MAC / ID<b><?=h($client['mac'])?></b></div>
            <div class="dns-info">Dono<b><?=h(get_owner_label($client['owner_type'],$client['owner_id']))?></b></div>
            <div class="dns-info">Status<b><?=(int)$client['is_active']===1?'<span class="pill-ok">Ativo</span>':'<span class="pill-off">Bloqueado</span>'?></b></div>
        </div>
        <div class="dns-tabs">
            <a class="dns-tab" href="clientes_macs.php?edit=<?=h($id)?>">👤 Dados do Cliente</a>
            <span class="dns-tab active">🌐 DNS / VPN</span>
            <a class="dns-tab" href="clientes_macs.php">📋 Voltar</a>
        </div>
        <form method="post" class="dns-body">
            <input type="hidden" name="id" value="<?=h($id)?>">
            <h3>Serviço DNS do Cliente</h3>
            <p class="muted">Escolha o serviço DNS que será aplicado neste cliente. Isso pode ajudar em problemas de conexão.</p>
            <?php foreach($services as $key=>$s): ?>
            <label class="dns-option <?=$current===$key?'active':''?>">
                <input type="radio" name="dns_service" value="<?=h($key)?>" <?=$current===$key?'checked':''?> style="display:none">
                <span class="dns-radio"></span>
                <span class="dns-icon"><?=h($s[3])?></span>
                <span>
                    <span class="dns-title"><?=h($s[0])?></span>
                    <span class="dns-sub"><?= $key==='off' ? 'Não usar DNS personalizado' : h($s[1].' / '.$s[2]) ?></span>
                </span>
            </label>
            <?php endforeach; ?>
            <div class="dns-alert">ⓘ O DNS selecionado será enviado para o aplicativo pela API <b>api/apk_config.php</b>.</div>
            <div class="dns-actions">
                <a class="btn dark" href="clientes_macs.php">Cancelar</a>
                <button class="btn">💾 Salvar Alterações</button>
            </div>
        </form>
    </div>
</div>
<script>
document.querySelectorAll('.dns-option').forEach(function(el){
  el.addEventListener('click',function(){
    document.querySelectorAll('.dns-option').forEach(function(x){x.classList.remove('active')});
    el.classList.add('active');
    el.querySelector('input').checked=true;
  });
});
</script>
<?php include __DIR__.'/includes/footer.php'; ?>
