<?php
require __DIR__ . '/auth.php';
exigirAdmin();

$usuarioId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$stmt = $pdo->prepare("SELECT id,nome,usuario,ativo FROM usuarios_localizacao WHERE id=? AND perfil='USUARIO' LIMIT 1");
$stmt->execute([$usuarioId]);
$alvo = $stmt->fetch();
if (!$alvo) { http_response_code(404); exit('Usuário não encontrado.'); }

$stmt = $pdo->prepare("SELECT * FROM dispositivos WHERE usuario_id=? ORDER BY nome");
$stmt->execute([$usuarioId]);
$dispositivos = $stmt->fetchAll();
$deviceId = isset($_GET['d']) ? (int)$_GET['d'] : (isset($dispositivos[0]['id'])?(int)$dispositivos[0]['id']:0);
$device=null;$historico=[];$ultima=null;

if ($deviceId>0) {
    $stmt=$pdo->prepare("SELECT * FROM dispositivos WHERE id=? AND usuario_id=? LIMIT 1");
    $stmt->execute([$deviceId,$usuarioId]); $device=$stmt->fetch();
    if($device){
        $stmt=$pdo->prepare("SELECT * FROM localizacoes WHERE dispositivo_id=? ORDER BY registrado_em DESC LIMIT 100");
        $stmt->execute([$deviceId]);$historico=$stmt->fetchAll();$ultima=isset($historico[0])?$historico[0]:null;
    }
}
function eh($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}
function enderecoAdm($r){return !empty($r['endereco'])?$r['endereco']:'Lat. '.$r['latitude'].' / Long. '.$r['longitude'];}
?>
<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Localização do usuário</title>
<style>*{box-sizing:border-box}body{margin:0;font-family:Arial;background:#f3f6f9;color:#1f2937}.wrap{max-width:1100px;margin:24px auto;padding:0 16px}.top,.card{background:#fff;border-radius:14px;padding:18px;margin-bottom:18px;box-shadow:0 3px 16px #0001}.top{background:#0f2742;color:#fff}.btn{display:inline-block;padding:9px 12px;border-radius:9px;background:#e8eef5;color:#0f2742;text-decoration:none}.devices{display:flex;gap:8px;flex-wrap:wrap}.dev{padding:8px 10px;border-radius:8px;background:#eef4fa;text-decoration:none;color:#1f2937}.map{height:380px;background:#eef2f7;border-radius:12px;display:flex;align-items:center;justify-content:center}.map iframe{width:100%;height:100%;border:0;border-radius:12px}table{width:100%;border-collapse:collapse}th,td{padding:9px;border-bottom:1px solid #e5e7eb;text-align:left}</style></head>
<body><div class="wrap"><div class="top"><a class="btn" href="admin.php">← Administrador</a><h1 style="margin-bottom:4px"><?php echo eh($alvo['nome']);?></h1><div>Usuário: <?php echo eh($alvo['usuario']);?></div></div>
<div class="card"><h3>Aparelhos</h3><div class="devices"><?php foreach($dispositivos as $d):?><a class="dev" href="?id=<?php echo $usuarioId;?>&d=<?php echo (int)$d['id'];?>"><?php echo eh($d['nome']);?></a><?php endforeach;?><?php if(!$dispositivos):?>Nenhum aparelho vinculado.<?php endif;?></div></div>
<?php if($device):?><div class="card"><h2><?php echo eh($device['nome']);?></h2>
<?php if($ultima):$lat=(float)$ultima['latitude'];$lon=(float)$ultima['longitude'];$map='https://www.openstreetmap.org/export/embed.html?bbox='.($lon-.01).'%2C'.($lat-.01).'%2C'.($lon+.01).'%2C'.($lat+.01).'&layer=mapnik&marker='.$lat.'%2C'.$lon;?>
<div class="map"><iframe src="<?php echo eh($map);?>"></iframe></div><p><strong>Endereço:</strong> <?php echo eh(enderecoAdm($ultima));?></p>
<?php else:?><div class="map">Nenhuma localização recebida.</div><?php endif;?></div>
<div class="card"><h3>Histórico recente</h3><table><tr><th>Data</th><th>Endereço</th><th>Precisão</th><th>Bateria</th></tr>
<?php foreach($historico as $l):?><tr><td><?php echo eh($l['registrado_em']);?></td><td><?php echo eh(enderecoAdm($l));?></td><td><?php echo eh($l['precisao']);?> m</td><td><?php echo eh($l['bateria']);?>%</td></tr><?php endforeach;?>
<?php if(!$historico):?><tr><td colspan="4">Sem histórico.</td></tr><?php endif;?></table></div><?php endif;?>
</div></body></html>
