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

$u = usuarioAtual();
$usuarioId = (int)$u['id'];

function enderecoOuCoordenadas($r) {
    if (!empty($r['endereco'])) return $r['endereco'];
    return 'Lat. '.$r['latitude'].' / Long. '.$r['longitude'];
}

function voltarPainel($id=0) {
    header('Location: painel.php' . ($id > 0 ? '?d='.(int)$id : ''));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validarCsrf();
    $acao = isset($_POST['acao']) ? trim($_POST['acao']) : '';
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($id > 0) {
        $stmt = $pdo->prepare('SELECT id FROM dispositivos WHERE id=? AND usuario_id=? LIMIT 1');
        $stmt->execute([$id, $usuarioId]);
        if (!$stmt->fetch()) {
            http_response_code(403);
            exit('Este aparelho não pertence ao seu usuário.');
        }
    }

    if ($acao === 'toggle' && $id > 0) {
        $stmt = $pdo->prepare(
            'UPDATE dispositivos SET compartilhamento_ativo=IF(compartilhamento_ativo=1,0,1)
             WHERE id=? AND usuario_id=?'
        );
        $stmt->execute([$id, $usuarioId]);
        voltarPainel($id);
    }

    if ($acao === 'renomear' && $id > 0) {
        $nome = isset($_POST['nome']) ? trim($_POST['nome']) : '';
        if ($nome !== '') {
            $nome = substr($nome, 0, 100);
            $stmt = $pdo->prepare('UPDATE dispositivos SET nome=? WHERE id=? AND usuario_id=?');
            $stmt->execute([$nome, $id, $usuarioId]);
        }
        voltarPainel($id);
    }

    if ($acao === 'excluir' && $id > 0) {
        $stmt = $pdo->prepare('DELETE FROM dispositivos WHERE id=? AND usuario_id=?');
        $stmt->execute([$id, $usuarioId]);
        voltarPainel();
    }
}

$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;
    }
}
?>
<!doctype html>
<html lang="pt-BR"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Meu painel de localização</title>
<style>
*{box-sizing:border-box}body{font-family:Arial,sans-serif;background:#f3f6f9;margin:0;color:#1f2937}.wrap{max-width:1180px;margin:28px auto;padding:0 16px}
.top{background:#0f2742;color:#fff;padding:20px;border-radius:14px}.toprow{display:flex;justify-content:space-between;gap:12px;align-items:center;flex-wrap:wrap}
.grid{display:grid;grid-template-columns:300px 1fr;gap:18px;margin-top:18px}.card{background:#fff;border-radius:14px;padding:18px;box-shadow:0 3px 16px rgba(0,0,0,.07)}
.dev{display:block;padding:11px;border-radius:10px;text-decoration:none;color:#1f2937;margin-bottom:6px}.dev:hover,.dev.on{background:#eef4fa}.dev small{display:block;color:#64748b;margin-top:3px}
.status{display:inline-block;padding:6px 10px;border-radius:999px;font-size:13px;background:#e8f5e9;color:#166534}.off{background:#fee2e2;color:#991b1b}
.btn{border:0;border-radius:10px;padding:10px 14px;background:#0f2742;color:#fff;cursor:pointer;font-size:14px;text-decoration:none;display:inline-block}.btn-light{background:#e8eef5;color:#0f2742}.btn-danger{background:#b42318}.btn-download{background:#009c3b;color:#fff}
.actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.device-head{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:center}
.map{height:350px;border-radius:12px;background:#eef2f7;display:flex;align-items:center;justify-content:center;text-align:center;padding:20px}.map iframe{width:100%;height:100%;border:0;border-radius:12px}
.endereco-atual{background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:12px;margin-top:14px;line-height:1.45}
table{width:100%;border-collapse:collapse;font-size:14px}th,td{padding:10px;border-bottom:1px solid #e5e7eb;text-align:left;vertical-align:top}.empty{color:#6b7280}
.modal{display:none;position:fixed;inset:0;background:#0f172a88;padding:20px;align-items:center;justify-content:center;z-index:999}.modal.open{display:flex}.modal-card{background:#fff;width:100%;max-width:480px;border-radius:14px;padding:20px}
input[type=text]{width:100%;padding:10px;border:1px solid #ccd5df;border-radius:9px}.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap}
@media(max-width:760px){.grid{grid-template-columns:1fr}.wrap{margin:16px auto}.map{height:280px}}
</style></head><body>
<div class="wrap">
<div class="top"><div class="toprow"><div><h1 style="margin:0 0 6px">Localização autorizada</h1><div>Olá, <?php echo h($u['nome']); ?>. Aqui aparecem somente os seus aparelhos.</div></div>
<div><a class="btn btn-light" href="logout.php">Sair</a><?php if($u['perfil']==='ADMIN'):?> <a class="btn btn-light" href="admin.php">Administrador</a><?php endif;?></div></div></div>

<div class="grid">
<div class="card"><h3 style="margin-top:0">Meus dispositivos</h3>
<?php if($dispositivos): foreach($dispositivos as $d):?>
<a class="dev <?php echo (int)$d['id']===$deviceId?'on':'';?>" href="?d=<?php echo (int)$d['id'];?>">
<strong><?php echo h($d['nome']);?></strong><small>ID <?php echo (int)$d['id'];?> · <?php echo !empty($d['compartilhamento_ativo'])?'Ativo':'Pausado';?></small>
</a>
<?php endforeach; else:?><div class="empty">Nenhum aparelho vinculado à sua conta ainda.</div><?php endif;?>
</div>

<div>
<?php if($device):?>
<div class="card"><div class="device-head"><div><h2 style="margin:0 0 8px"><?php echo h($device['nome']);?></h2>
<span class="status <?php echo !empty($device['compartilhamento_ativo'])?'':'off';?>"><?php echo !empty($device['compartilhamento_ativo'])?'Compartilhamento autorizado':'Compartilhamento pausado';?></span></div>
<div class="actions">
<form method="post"><input type="hidden" name="csrf" value="<?php echo h(csrfToken());?>"><input type="hidden" name="acao" value="toggle"><input type="hidden" name="id" value="<?php echo (int)$device['id'];?>">
<button class="btn"><?php echo !empty($device['compartilhamento_ativo'])?'Pausar':'Ativar';?></button></form>
<a href="/app-debug.apk" class="btn btn-download" download>⬇ Baixar</a>
<button class="btn btn-light" type="button" onclick="document.getElementById('renomear').classList.add('open')">Renomear</button>
<button class="btn btn-danger" type="button" onclick="document.getElementById('excluir').classList.add('open')">Excluir</button>
</div></div></div>

<div class="card" style="margin-top:18px"><h3>Última posição</h3>
<?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 loading="lazy" src="<?php echo h($map);?>"></iframe></div>
<div class="endereco-atual"><strong>Endereço:</strong> <?php echo h(enderecoOuCoordenadas($ultima));?><br>
<strong>Precisão:</strong> <?php echo $ultima['precisao']!==null?h($ultima['precisao']).' m':'-';?> &nbsp;|&nbsp;
<strong>Bateria:</strong> <?php echo $ultima['bateria']!==null?h($ultima['bateria']).'%':'-';?><br>
<strong>Registrado:</strong> <?php echo h($ultima['registrado_em']);?> &nbsp;|&nbsp;
<a target="_blank" rel="noopener" href="https://www.google.com/maps?q=<?php echo h($ultima['latitude']);?>,<?php echo h($ultima['longitude']);?>">Abrir no mapa</a></div>
<?php else:?><div class="map">Nenhuma localização recebida ainda.</div><?php endif;?>
</div>

<div class="card" style="margin-top:18px;overflow:auto"><h3>Histórico recente</h3><table><thead><tr><th>Data</th><th>Endereço</th><th>Precisão</th><th>Bateria</th><th>Mapa</th></tr></thead><tbody>
<?php if($historico): foreach($historico as $l):?>
<tr><td><?php echo h($l['registrado_em']);?></td><td><?php echo h(enderecoOuCoordenadas($l));?></td>
<td><?php echo $l['precisao']!==null?h($l['precisao']).' m':'-';?></td><td><?php echo $l['bateria']!==null?h($l['bateria']).'%':'-';?></td>
<td><a target="_blank" rel="noopener" href="https://www.google.com/maps?q=<?php echo h($l['latitude']);?>,<?php echo h($l['longitude']);?>">Abrir</a></td></tr>
<?php endforeach; else:?><tr><td colspan="5" class="empty">Nenhum histórico recebido.</td></tr><?php endif;?>
</tbody></table></div>

<div class="modal" id="renomear"><div class="modal-card"><h3>Renomear aparelho</h3><form method="post">
<input type="hidden" name="csrf" value="<?php echo h(csrfToken());?>"><input type="hidden" name="acao" value="renomear"><input type="hidden" name="id" value="<?php echo (int)$device['id'];?>">
<input type="text" name="nome" value="<?php echo h($device['nome']);?>" required><div class="modal-actions"><button type="button" class="btn btn-light" onclick="document.getElementById('renomear').classList.remove('open')">Cancelar</button><button class="btn">Salvar</button></div></form></div></div>
<div class="modal" id="excluir"><div class="modal-card"><h3>Excluir aparelho</h3><p>O histórico deste aparelho também será apagado.</p><form method="post">
<input type="hidden" name="csrf" value="<?php echo h(csrfToken());?>"><input type="hidden" name="acao" value="excluir"><input type="hidden" name="id" value="<?php echo (int)$device['id'];?>">
<div class="modal-actions"><button type="button" class="btn btn-light" onclick="document.getElementById('excluir').classList.remove('open')">Cancelar</button><button class="btn btn-danger">Excluir definitivamente</button></div></form></div></div>
<?php else:?><div class="card"><h2 style="margin-top:0">Nenhum celular vinculado</h2><p>O administrador poderá vincular o aparelho cadastrado automaticamente à sua conta.</p></div><?php endif;?>
</div></div></div>
</body></html>
