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

if(isset($_GET['edit'])){
    $st=$db->prepare('SELECT * FROM client_macs WHERE id=:id');
    $st->bindValue(':id',(int)$_GET['edit'],SQLITE3_INTEGER);
    $edit=$st->execute()->fetchArray(SQLITE3_ASSOC) ?: null;
}
if(isset($_GET['toggle'])){
    $id=(int)$_GET['toggle'];
    $db->exec("UPDATE client_macs SET is_active=CASE WHEN is_active=1 THEN 0 ELSE 1 END, status=CASE WHEN is_active=1 THEN 'bloqueado' ELSE 'ativo' END, updated_at=CURRENT_TIMESTAMP WHERE id=".$id);
    header('Location: clientes_macs.php'); exit;
}
if(isset($_GET['delete'])){
    $id=(int)$_GET['delete'];
    $db->exec('DELETE FROM client_macs WHERE id='.$id);
    header('Location: clientes_macs.php'); exit;
}
if($_SERVER['REQUEST_METHOD']==='POST'){
    $id=(int)($_POST['id'] ?? 0);
    $mac=normalize_mac_value($_POST['mac'] ?? '');
    $cliente_nome=trim($_POST['cliente_nome'] ?? '');
    $usuario=trim($_POST['usuario'] ?? '');
    $senha=trim($_POST['senha'] ?? '');
    $owner=$_POST['owner'] ?? 'admin:0';
    $notes=trim($_POST['notes'] ?? '');
    $expires_at=trim($_POST['expires_at'] ?? '');
    $discount_note=trim($_POST['discount_note'] ?? '');
    $ativo=isset($_POST['is_active'])?1:0;
    $status=$ativo ? 'ativo' : 'bloqueado';

    [$owner_type,$owner_id]=array_pad(explode(':',$owner,2),2,0);
    $owner_id=(int)$owner_id;
    if(!in_array($owner_type,['admin','revenda','subrevenda'],true)){ $owner_type='admin'; $owner_id=0; }

    if($mac===''){ $err='Informe o MAC/ID do cliente.'; }
    else{
        if($id>0){
            $st=$db->prepare('UPDATE client_macs SET mac=:mac,cliente_nome=:cn,usuario=:u,senha=:s,owner_type=:ot,owner_id=:oi,notes=:no,expires_at=:ex,discount_note=:dn,is_active=:a,status=:status,updated_at=CURRENT_TIMESTAMP WHERE id=:id');
            $st->bindValue(':id',$id,SQLITE3_INTEGER);
        } else {
            $st=$db->prepare("INSERT INTO client_macs(mac,cliente_nome,usuario,senha,owner_type,owner_id,notes,expires_at,discount_note,is_active,status,first_seen,last_seen) VALUES(:mac,:cn,:u,:s,:ot,:oi,:no,:ex,:dn,:a,:status,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
        }
        $st->bindValue(':mac',$mac,SQLITE3_TEXT);
        $st->bindValue(':cn',$cliente_nome,SQLITE3_TEXT);
        $st->bindValue(':u',$usuario,SQLITE3_TEXT);
        $st->bindValue(':s',$senha,SQLITE3_TEXT);
        $st->bindValue(':ot',$owner_type,SQLITE3_TEXT);
        $st->bindValue(':oi',$owner_id,SQLITE3_INTEGER);
        $st->bindValue(':no',$notes,SQLITE3_TEXT);
        $st->bindValue(':ex',$expires_at,SQLITE3_TEXT);
        $st->bindValue(':dn',$discount_note,SQLITE3_TEXT);
        $st->bindValue(':a',$ativo,SQLITE3_INTEGER);
        $st->bindValue(':status',$status,SQLITE3_TEXT);
        $st->execute();
        header('Location: clientes_macs.php?ok=1'); exit;
    }
}

$revendas=[]; $res=$db->query('SELECT id,nome,usuario FROM revendas WHERE is_active=1 ORDER BY nome'); while($r=$res->fetchArray(SQLITE3_ASSOC)) $revendas[]=$r;
$subs=[]; $res=$db->query('SELECT id,nome,usuario FROM sub_revendas WHERE is_active=1 ORDER BY nome'); while($r=$res->fetchArray(SQLITE3_ASSOC)) $subs[]=$r;

$rows=[]; $q=trim($_GET['q'] ?? ''); $f=trim($_GET['f'] ?? '');
$where=[]; $params=[];
if($q!==''){ $where[]='(mac LIKE :q OR usuario LIKE :q OR cliente_nome LIKE :q OR modelo LIKE :q OR ip LIKE :q)'; $params[':q']='%'.$q.'%'; }
if($f==='pendente'){ $where[]="status='pendente'"; }
if($f==='ativo'){ $where[]="is_active=1 AND status='ativo'"; }
if($f==='bloqueado'){ $where[]="(is_active=0 OR status='bloqueado')"; }
$sql='SELECT * FROM client_macs'.($where?' WHERE '.implode(' AND ',$where):'').' ORDER BY id DESC';
$st=$db->prepare($sql);
foreach($params as $k=>$v) $st->bindValue($k,$v,SQLITE3_TEXT);
$res=$st->execute();
while($r=$res->fetchArray(SQLITE3_ASSOC)) $rows[]=$r;

include __DIR__.'/includes/header.php';
?>
<div class="card">
<h3>🔐 Dispositivos APK / MACs</h3>
<p class="muted">O cliente vê o MAC/ID no APK e envia para a revenda. A revenda adiciona aqui. Sem MAC cadastrado/liberado, o APK não fica vinculado à revenda.</p>
<?php if(isset($_GET['ok'])): ?><p class="ok">MAC salvo.</p><?php endif; ?>
<?php if($err): ?><p class="bad"><?=h($err)?></p><?php endif; ?>

<form method="post">
<input type="hidden" name="id" value="<?=h($edit['id'] ?? 0)?>">
<div class="grid" style="grid-template-columns:repeat(2,minmax(0,1fr));gap:12px">
<div><label>MAC/ID do APK</label><input name="mac" value="<?=h($edit['mac'] ?? '')?>" placeholder="Ex: 6e0b65aa502af6b7"></div>
<div><label>Cliente/Nome</label><input name="cliente_nome" value="<?=h($edit['cliente_nome'] ?? '')?>"></div>
<div><label>Usuário IPTV</label><input name="usuario" value="<?=h($edit['usuario'] ?? '')?>"></div>
<div><label>Senha IPTV</label><input name="senha" value="<?=h($edit['senha'] ?? '')?>"></div>
<div><label>Dono do APK</label><select name="owner"><option value="admin:0" <?=($edit && $edit['owner_type']==='admin')?'selected':''?>>Admin / Pendente</option><optgroup label="Revendas"><?php foreach($revendas as $rv): ?><option value="revenda:<?=h($rv['id'])?>" <?=($edit && $edit['owner_type']==='revenda' && (int)$edit['owner_id']===(int)$rv['id'])?'selected':''?>><?=h($rv['nome'] ?: $rv['usuario'])?></option><?php endforeach; ?></optgroup><optgroup label="Sub Revendas"><?php foreach($subs as $sr): ?><option value="subrevenda:<?=h($sr['id'])?>" <?=($edit && $edit['owner_type']==='subrevenda' && (int)$edit['owner_id']===(int)$sr['id'])?'selected':''?>><?=h($sr['nome'] ?: $sr['usuario'])?></option><?php endforeach; ?></optgroup></select></div>
<div><label>Observação</label><input name="notes" value="<?=h($edit['notes'] ?? '')?>"></div>
<div><label>Vencimento do Cliente</label><input type="date" name="expires_at" value="<?=h(substr((string)($edit['expires_at'] ?? ''),0,10))?>"></div>
<div><label>Mensagem de desconto individual</label><input name="discount_note" value="<?=h($edit['discount_note'] ?? '')?>" placeholder="Opcional: desconto especial para este cliente"></div>
</div>
<label style="display:flex;gap:8px;align-items:center;margin-top:12px"><input type="checkbox" name="is_active" <?=(!isset($edit['is_active']) || (int)$edit['is_active']===1)?'checked':''?>> Liberar/Ativar APK</label>
<p><button class="btn">Salvar MAC</button> <?php if($edit): ?><a class="btn dark" href="clientes_macs.php">Cancelar</a><?php endif; ?></p>
</form>
</div>

<div class="card">
<h3>Lista de dispositivos</h3>
<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, usuário, cliente, modelo ou IP"></div>
<div><label>Status</label><select name="f"><option value="">Todos</option><option value="pendente" <?=$f==='pendente'?'selected':''?>>Pendentes</option><option value="ativo" <?=$f==='ativo'?'selected':''?>>Ativos</option><option value="bloqueado" <?=$f==='bloqueado'?'selected':''?>>Bloqueados</option></select></div>
<button class="btn dark">Buscar</button>
</form>
<table>
<tr><th>ID</th><th>MAC/ID</th><th>Cliente</th><th>Dono</th><th>Vencimento</th><th>Status</th><th>Modelo</th><th>Último acesso</th><th>Ações</th></tr>
<?php foreach($rows as $r): ?>
<tr>
<td><?=h($r['id'])?></td>
<td><b><?=h($r['mac'])?></b><br><span class="muted"><?=h($r['ip'] ?? '')?></span></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><?php $stt=$r['status'] ?? ((int)$r['is_active']===1?'ativo':'bloqueado'); echo $stt==='pendente'?'<span class="warn">Pendente</span>':((int)$r['is_active']===1?'<span class="pill">Ativo</span>':'<span class="bad">Bloqueado</span>'); ?></td>
<td><?=h($r['modelo'] ?? '')?><br><span class="muted"><?=h($r['app_version'] ?? '')?></span></td>
<td><?=h($r['last_seen'] ?? $r['updated_at'] ?? '')?></td>
<td><a class="btn dark" href="clientes_macs.php?edit=<?=h($r['id'])?>">Editar</a> <a class="btn dark" href="clientes_macs.php?toggle=<?=h($r['id'])?>"><?=(int)$r['is_active']===1?'Bloquear':'Desbloquear'?></a> <a class="btn" onclick="return confirm('Excluir este MAC?')" href="clientes_macs.php?delete=<?=h($r['id'])?>">Excluir</a></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
