<?php
// mapa.php — Mapa Operacional (VERSÃO FINAL COMPLETA - SEM API GOOGLE)
$pageActive = 'mapa';
$pageTitle  = 'Mapa Operacional';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$olts     = getOLTs();
$clientes = getClientes();

$stmtOS = pdo()->query(
    "SELECT cliente_id, COUNT(*) FROM ordens_servico
     WHERE status IN ('ABERTA','AGENDADA','EM_ANDAMENTO') GROUP BY cliente_id"
);
$osAbertas = $stmtOS->fetchAll(PDO::FETCH_KEY_PAIR);

$totalClientes  = count($clientes);
$comGPS         = count(array_filter($clientes, fn($c)=>$c['latitude']&&$c['longitude']));

$cidadesUnicas = array_unique(array_filter(array_column($clientes, 'endereco_cidade')));
sort($cidadesUnicas);

$coordsCidades = [
    'Jales'           => [-20.2681, -50.5494],
    'Paranapuã'       => [-20.1039, -50.5889],
    'Santa Albertina' => [-20.0319, -50.7281],
    'Mesópolis'       => [-19.9667, -50.6375],
    'Populina'        => [-19.9453, -50.5383],
    'Dirce Reis'      => [-20.4658, -50.6067],
];

$dadosCli = array_map(fn($c) => [
    'id'        => (int)$c['id'],
    'nome'      => $c['nome'],
    'lat'       => $c['latitude']  ? (float)$c['latitude']  : null,
    'lng'       => $c['longitude'] ? (float)$c['longitude'] : null,
    'plano'     => $c['plano']           ?? '',
    'cidade'    => $c['endereco_cidade'] ?? '',
    'telefone'  => $c['telefone']        ?? '',
    'cep'       => $c['cep']             ?? '',
    'endereco'  => trim(($c['endereco_logradouro']??'') . ', ' . ($c['endereco_numero']??'') . ' - ' . ($c['endereco_bairro']??'')),
    'bloqueado' => (int)$c['bloqueado'],
    'osA'       => (int)($osAbertas[$c['id']] ?? 0),
], $clientes);

$jsCli        = json_encode($dadosCli,  JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$jsCidades    = json_encode(array_values($cidadesUnicas), JSON_UNESCAPED_UNICODE);
$jsCoordsCid  = json_encode($coordsCidades, JSON_UNESCAPED_UNICODE);

require_once __DIR__ . '/includes/header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<style>
*{box-sizing:border-box}
.main{overflow:hidden!important}

.mapa-wrapper{
  display:flex;flex-direction:column;
  height:calc(100dvh - 56px);
  overflow:hidden;
}

/* ══════ 1. FILTRO CIDADES ══════ */
.cidade-bar{
  background:var(--surface);border-bottom:1px solid var(--border);
  padding:8px 12px;flex-shrink:0;
}
.painel-select{
  width:260px;background:var(--card);border:1px solid var(--border);
  border-radius:8px;padding:8px 12px;font-family:var(--ui);font-size:12px;
  color:var(--text);outline:none;appearance:none;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath fill='%235a7a9a' d='M5 7L1 3h8z'/%3E%3C/svg%3E");
  background-repeat:no-repeat;background-position:right 12px center;
  padding-right:32px;cursor:pointer;
}

/* ══════ 2. BARRA FILTROS REDE ══════ */
.filtros-bar{
  background:var(--surface);border-bottom:1px solid var(--border);
  padding:6px 10px;flex-shrink:0;
  display:flex;align-items:center;gap:6px;
  overflow-x:auto;-webkit-overflow-scrolling:touch;
}
.filtros-bar::-webkit-scrollbar{height:5px}
.filtros-bar::-webkit-scrollbar-thumb{background:var(--cyan);border-radius:3px}
.chip-btn-h{
  padding:6px 14px;border-radius:16px;font-size:10px;font-weight:700;
  font-family:var(--mono);cursor:pointer;
  border:1px solid var(--border);background:var(--card);color:var(--muted);
  white-space:nowrap;transition:all .15s;user-select:none;
}
.chip-btn-h:hover{background:var(--cyan);color:#000;border-color:var(--cyan)}
.chip-btn-h.on{background:var(--cyan);color:#000;border-color:var(--cyan)}

/* ══════ 3. MAPA ══════ */
.mapa-container{
  flex:1;position:relative;overflow:hidden;min-height:0;
}
#main-map{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%}

.leaflet-container{background:var(--bg)!important;font-family:var(--ui)!important}
.leaflet-popup-content-wrapper{background:var(--card)!important;border:1px solid var(--border)!important;border-radius:10px!important;box-shadow:0 8px 24px rgba(0,0,0,.5)!important}
.leaflet-popup-content{color:var(--text)!important;margin:8px 10px!important;font-size:11px!important;line-height:1.5!important}
.leaflet-popup-tip{background:var(--card)!important}
.leaflet-tooltip{background:var(--surface)!important;color:var(--cyan)!important;border:1px solid var(--pink)!important;border-radius:6px!important;font-size:10px!important;font-weight:700!important;padding:4px 8px!important}
.leaflet-control-zoom a{background:var(--surface)!important;color:var(--text)!important;border:2px solid var(--cyan)!important;font-weight:900!important;font-size:18px!important;width:40px!important;height:40px!important;line-height:36px!important;border-radius:8px!important;margin-bottom:6px!important}
.leaflet-control-zoom a:hover{background:var(--cyan)!important;color:#000!important}

.leaflet-control-centralizar{
  background:var(--surface)!important;border:2px solid var(--green)!important;
  color:var(--green)!important;font-weight:900!important;font-size:16px!important;
  width:40px!important;height:40px!important;line-height:36px!important;
  border-radius:8px!important;cursor:pointer!important;text-align:center!important;
  margin-bottom:6px!important;box-shadow:0 4px 15px rgba(0,0,0,.4)!important;
}
.leaflet-control-centralizar:hover{background:var(--green)!important;color:#000!important}
.leaflet-control-centralizar.ativo{background:var(--green)!important;color:#000!important}

/* ══════ 4. BARRA CLIENTES ══════ */
.clientes-bar{
  background:var(--surface);border-top:1px solid var(--border);
  height:150px;flex-shrink:0;
  display:flex;overflow-x:auto;overflow-y:hidden;
  padding:10px;gap:10px;
  -webkit-overflow-scrolling:touch;
}
.clientes-bar::-webkit-scrollbar{height:6px}
.clientes-bar::-webkit-scrollbar-thumb{background:var(--cyan);border-radius:3px}

.cli-card-h{
  flex:0 0 auto;width:165px;
  background:var(--card);border:1px solid var(--border);
  border-radius:12px;padding:12px;cursor:pointer;
  display:flex;flex-direction:column;gap:6px;
  transition:all .15s;
}
.cli-card-h:hover{border-color:var(--cyan);transform:translateY(-2px)}
.cli-card-h.sel{border-color:var(--pink);background:rgba(236,72,153,.06);box-shadow:0 0 16px rgba(236,72,153,.15)}
.cli-card-h-top{display:flex;align-items:center;gap:6px}
.cli-card-h-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
.cli-card-h-nome{font-size:11px;font-weight:700;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1}
.cli-card-h-end{font-size:9px;color:var(--muted);font-family:var(--mono);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;line-height:1.4;min-height:25px}
.cli-card-h-status{font-size:8px;font-family:var(--mono)}
.cli-card-h-acts{display:flex;gap:4px;margin-top:auto}
.cli-act-mini{
  width:26px;height:26px;border-radius:6px;display:flex;align-items:center;
  justify-content:center;text-decoration:none;font-size:12px;transition:all .12s;
  flex-shrink:0;
}
.cli-act-mini.wpp{background:rgba(37,211,102,.15);color:#25D366}
.cli-act-mini.tel{background:rgba(255,255,255,.06);color:var(--text);border:1px solid var(--border)}
.cli-act-mini.ficha{background:rgba(0,212,255,.12);color:var(--cyan);font-size:9px;font-weight:700;width:auto;padding:0 6px}
.cli-act-mini:hover{opacity:.7;transform:scale(1.05)}

/* MODAL */
.modal-overlay{
  position:fixed!important;top:0!important;left:0!important;
  width:100vw!important;height:100vh!important;
  background:rgba(0,0,0,.88)!important;z-index:999999!important;
  display:none!important;align-items:center!important;justify-content:center!important;
  padding:16px!important;
}
.modal-overlay.show{display:flex!important}
.modal-content{
  background:var(--surface)!important;border:2px solid var(--cyan)!important;
  border-radius:16px!important;width:100%!important;max-width:620px!important;
  max-height:90vh!important;overflow:hidden!important;position:relative!important;
  display:flex;flex-direction:column;
}
.modal-close{
  position:absolute!important;top:10px!important;right:10px!important;
  background:rgba(0,0,0,.8)!important;color:#fff!important;border:2px solid var(--red)!important;
  border-radius:50%!important;width:34px!important;height:34px!important;
  font-size:20px!important;cursor:pointer!important;z-index:10!important;
  display:flex!important;align-items:center!important;justify-content:center!important;
}
.modal-close:hover{background:var(--red)!important}
.modal-header{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;flex-shrink:0}
.modal-header-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
.modal-header-info{flex:1;min-width:0}
.modal-header-nome{font-size:14px;font-weight:700;color:var(--pink)}
.modal-header-end{font-size:10px;color:var(--muted);font-family:var(--mono);margin-top:2px}
.modal-body{position:relative;height:350px;flex-shrink:0}
.modal-body iframe,.modal-body .mini-mapa-modal{width:100%!important;height:100%!important;border:none!important}
.modal-footer{padding:12px 16px;border-top:1px solid var(--border);display:flex;gap:8px;flex-wrap:wrap;flex-shrink:0}
.modal-btn{
  padding:8px 14px;border-radius:8px;font-size:11px;font-weight:700;
  text-decoration:none;border:none;cursor:pointer;transition:all .15s;
}
.modal-btn.maps{background:#4285F4;color:#fff}
.modal-btn.waze{background:#33ccff;color:#000}
.modal-btn.street{background:#ea4335;color:#fff}
.modal-btn.wpp{background:#25D366;color:#fff}
.modal-btn.tel{background:var(--card);color:var(--text);border:1px solid var(--border)}
.modal-btn.ficha{background:rgba(0,212,255,.12);color:var(--cyan);border:1px solid var(--cyan)}
.modal-btn:hover{opacity:.85}

@media(max-width:768px){
  .mapa-wrapper{height:calc(100dvh - 116px)}
  .clientes-bar{height:130px}
  .modal-content{max-width:100vw!important;border-radius:12px 12px 0 0!important}
  .modal-body{height:250px}
}
</style>

<div class="topbar">
    <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">&#9776;</button>
    <div>
        <div class="page-title">◉ Mapa Operacional</div>
        <div class="page-sub"><?= $comGPS ?>/<?= $totalClientes ?> clientes com GPS</div>
    </div>
    <div class="topbar-actions">
        <?php if(usuarioLogado()['perfil']==='ADMIN'): ?>
        <a href="config_projeto.php" class="btn btn-ghost btn-sm">▲ KML</a>
        <?php endif; ?>
    </div>
</div>

<div class="mapa-wrapper">
    <!-- 1. FILTRO CIDADES -->
    <div class="cidade-bar">
        <select class="painel-select" id="filtro-cidade" onchange="filtrarTudo()">
            <option value="">🏙 Todas as cidades</option>
        </select>
    </div>

    <!-- 2. BARRA FILTROS REDE -->
    <div class="filtros-bar">
        <button class="chip-btn-h on" data-filtro="clientes" onclick="toggleFiltroRede('clientes',this)">👤 Clientes</button>
        <button class="chip-btn-h" data-filtro="cx"      onclick="toggleFiltroRede('cx',this)">CX</button>
        <button class="chip-btn-h" data-filtro="cto"     onclick="toggleFiltroRede('cto',this)">CTO</button>
        <button class="chip-btn-h" data-filtro="ceo"     onclick="toggleFiltroRede('ceo',this)">CEO</button>
        <button class="chip-btn-h" data-filtro="cr"      onclick="toggleFiltroRede('cr',this)">CR</button>
        <button class="chip-btn-h" data-filtro="cep"     onclick="toggleFiltroRede('cep',this)">CEP</button>
        <button class="chip-btn-h" data-filtro="cel"     onclick="toggleFiltroRede('cel',this)">CEL</button>
        <button class="chip-btn-h" data-filtro="emenda"  onclick="toggleFiltroRede('emenda',this)">Emenda</button>
        <button class="chip-btn-h" data-filtro="cabo"    onclick="toggleFiltroRede('cabo',this)">Cabo</button>
        <button class="chip-btn-h" data-filtro="fo"      onclick="toggleFiltroRede('fo',this)">FO</button>
        <button class="chip-btn-h" data-filtro="feeder"  onclick="toggleFiltroRede('feeder',this)">Feeder</button>
        <button class="chip-btn-h" data-filtro="ramal"   onclick="toggleFiltroRede('ramal',this)">Ramal</button>
        <button class="chip-btn-h" data-filtro="drop"    onclick="toggleFiltroRede('drop',this)">Drop</button>
        <button class="chip-btn-h" data-filtro="ptp"     onclick="toggleFiltroRede('ptp',this)">PTP</button>
        <button class="chip-btn-h" data-filtro="pop"     onclick="toggleFiltroRede('pop',this)">POP</button>
        <button class="chip-btn-h" data-filtro="poste"   onclick="toggleFiltroRede('poste',this)">Poste</button>
        <button class="chip-btn-h" data-filtro="reserva" onclick="toggleFiltroRede('reserva',this)">Reserva</button>
        <button class="chip-btn-h" data-filtro="torre"   onclick="toggleFiltroRede('torre',this)">Torre</button>
        <button class="chip-btn-h" data-filtro="ponto"   onclick="toggleFiltroRede('ponto',this)">Ponto</button>
        <button class="chip-btn-h" data-filtro="outro"   onclick="toggleFiltroRede('outro',this)">Outros</button>
    </div>

    <!-- 3. MAPA -->
    <div class="mapa-container">
        <div id="main-map"></div>
    </div>

    <!-- 4. BARRA CLIENTES -->
    <div class="clientes-bar" id="clientes-bar"></div>
</div>

<!-- MODAL MINI-MAPA -->
<div class="modal-overlay" id="modal-mapa">
    <div class="modal-content">
        <button class="modal-close" onclick="fecharModal()">✕</button>
        <div class="modal-header" id="modal-header"></div>
        <div class="modal-body" id="modal-body-mapa"></div>
        <div class="modal-footer" id="modal-footer-links"></div>
    </div>
</div>

<script>
const CLI_DATA   = <?= $jsCli ?>;
const CIDADES    = <?= $jsCidades ?>;
const COORDS_CID = <?= $jsCoordsCid ?>;

function getCSSVar(n){return getComputedStyle(document.documentElement).getPropertyValue(n).trim()}
const T={
    cyan:getCSSVar('--cyan')||'#00d4ff',green:getCSSVar('--green')||'#10b981',
    pink:getCSSVar('--pink')||'#ec4899',red:getCSSVar('--red')||'#ef4444',
    amber:getCSSVar('--amber')||'#f59e0b',muted:getCSSVar('--muted')||'#94a3b8',
    text:getCSSVar('--text')||'#e2e8f0'
};

const CORES_KML={
    cx:'#00d4ff',cto:'#00b8e6',ceo:'#ec4899',fo:'#a855f7',
    poste:'#94a3b8',reserva:'#fb923c',emenda:'#f59e0b',torre:'#ef4444',
    cr:'#8b5cf6',ponto:'#f97316',outro:'#94a3b8',
    feeder:'#ff4444',ramal:'#ffaa7f',drop:'#ff7700',
    ptp:'#00ff88',pop:'#ffff44',cep:'#55ff00',cel:'#55ff00',cabo:'#ff2222',
};

let map,satTile,darkTile;
let layerClientes=L.layerGroup();
let layerInfra=L.layerGroup();
let _kmlMarkers=[];
let _kmlCarregado=false,_kmlTentativas=0;
let _filtrosRedeAtivos=new Set();
let _mostrarClientes=true;
let _clienteSelecionado=null;
let _centralizarAtivo=false;
let _miniMapaModal=null;

function escHtml(s){return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')}

function criarIconeKML(tipo){
    const cor=CORES_KML[tipo]||CORES_KML.outro;
    const S=16;
    let html='<div style="width:'+(S-4)+'px;height:'+(S-4)+'px;border-radius:50%;background:'+cor+';margin:2px"></div>';
    if(tipo==='cx'||tipo==='cto')html='<div style="width:'+S+'px;height:'+S+'px;border:2px solid '+cor+';background:transparent;border-radius:2px;display:flex;align-items:center;justify-content:center;font-size:6px;font-weight:900;color:'+cor+'">'+tipo.toUpperCase()+'</div>';
    if(tipo==='ceo')html='<div style="width:'+S+'px;height:'+S+'px;border-radius:50%;border:2px solid '+cor+';background:transparent;display:flex;align-items:center;justify-content:center;font-size:6px;font-weight:900;color:'+cor+'">CEO</div>';
    if(tipo==='emenda')html='<div style="width:'+S+'px;height:'+S+'px;background:'+cor+';clip-path:polygon(50% 0%,100% 50%,50% 100%,0% 50%)"></div>';
    if(tipo==='torre'||tipo==='pop')html='<div style="width:0;height:0;border-left:'+(S/2)+'px solid transparent;border-right:'+(S/2)+'px solid transparent;border-bottom:'+S+'px solid '+cor+'"></div>';
    if(tipo==='poste')html='<div style="position:relative;width:'+S+'px;height:'+S+'px"><div style="position:absolute;left:50%;top:0;transform:translateX(-50%);width:3px;height:100%;background:'+cor+'"></div><div style="position:absolute;top:2px;left:0;width:100%;height:3px;background:'+cor+'"></div></div>';
    if(tipo==='reserva')html='<div style="width:'+S+'px;height:'+S+'px;border-radius:50%;border:2px dashed '+cor+';background:transparent"></div>';
    return L.divIcon({className:'',html:html,iconSize:[S,S],iconAnchor:[S/2,S/2],popupAnchor:[0,-S/2]});
}

function criarIconeCliente(cor,destaque){
    const S=destaque?22:10;
    return L.divIcon({className:'',html:'<div style="width:'+S+'px;height:'+S+'px;border-radius:50%;background:'+cor+';border:2px solid #fff;'+(destaque?'box-shadow:0 0 16px '+cor+';':'')+'"></div>',iconSize:[S,S],iconAnchor:[S/2,S/2]});
}

// ═══════════════════ INICIALIZAÇÃO ═══════════════════
(function(){
    const sel=document.getElementById('filtro-cidade');
    CIDADES.forEach(c=>{const o=document.createElement('option');o.value=c;o.textContent=c;sel.appendChild(o)});

    map=L.map('main-map',{center:[-20.27,-50.55],zoom:12,zoomControl:false,attributionControl:false});
    L.control.zoom({position:'bottomright'}).addTo(map);

    darkTile=L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',{maxZoom:21});
    satTile=L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',{maxZoom:21});
    satTile.addTo(map);
    L.control.layers({'🌑 Dark':darkTile,'🛰 Satélite':satTile},{},{position:'topright'}).addTo(map);

    const ctrlCentralizar=L.control({position:'bottomright'});
    ctrlCentralizar.onAdd=function(){
        const div=L.DomUtil.create('div','leaflet-control-centralizar');
        div.innerHTML='⊙';div.title='Centralizar 100m';
        div.onclick=function(e){L.DomEvent.stopPropagation(e);toggleCentralizar();div.classList.toggle('ativo',_centralizarAtivo)};
        return div;
    };
    ctrlCentralizar.addTo(map);

    layerClientes.addTo(map);
    layerInfra.addTo(map);

    setTimeout(()=>map.invalidateSize(),300);
    window.addEventListener('resize',()=>map.invalidateSize());

    carregarKML();
    plotarClientes();
    renderClientesBar();
})();

// ═══════════════════ CLIENTES NO MAPA ═══════════════════
function plotarClientes(){
    layerClientes.clearLayers();
    if(!_mostrarClientes)return;
    const cidadeSel=document.getElementById('filtro-cidade').value;
    CLI_DATA.forEach(c=>{
        if(!c.lat||!c.lng)return;
        if(cidadeSel&&c.cidade!==cidadeSel)return;
        const destaque=_clienteSelecionado&&_clienteSelecionado.id===c.id;
        const cor=c.osA>0?T.amber:(c.bloqueado?T.red:T.cyan);
        const m=L.marker([c.lat,c.lng],{icon:criarIconeCliente(destaque?T.pink:cor,destaque),zIndexOffset:destaque?2000:1000}).addTo(layerClientes);
        m.on('click',e=>{L.DomEvent.stopPropagation(e);clicouIconeCliente(c)});
        m._cliData=c;
    });
}

function clicouIconeCliente(c){
    _clienteSelecionado=c;
    plotarClientes();
    map.flyTo([c.lat,c.lng],18,{duration:0.8});
    if(_centralizarAtivo)aplicarCentralizacao(c);
    renderClientesBar();
}

function selecionarCliente(c){
    _clienteSelecionado=c;
    plotarClientes();
    map.flyTo([c.lat,c.lng],17,{duration:0.8});
    if(_centralizarAtivo)aplicarCentralizacao(c);
    renderClientesBar();
}

// ═══════════════════ BARRA CLIENTES ═══════════════════
function renderClientesBar(){
    const cont=document.getElementById('clientes-bar');
    const cidadeSel=document.getElementById('filtro-cidade').value;
    const lista=CLI_DATA.filter(c=>c.lat&&c.lng&&(!cidadeSel||c.cidade===cidadeSel));
    if(!lista.length){cont.innerHTML='<div style="padding:20px;color:var(--muted);font-size:11px;white-space:nowrap">Nenhum cliente nesta cidade</div>';return}
    let h='';
    lista.forEach(c=>{
        const sc=c.bloqueado?T.red:T.green;
        let st=c.bloqueado?'Bloqueado':'Ativo';
        if(c.osA>0)st=c.osA+' OS';
        const sel=_clienteSelecionado&&_clienteSelecionado.id===c.id;
        const tel=(c.telefone||'').replace(/[^\d]/g,'');
        h+='<div class="cli-card-h'+(sel?' sel':'')+'" onclick="selecionarCliente(CLI_DATA.find(x=>x.id==='+c.id+'))" ondblclick="abrirModalCliente('+c.id+')">'+
            '<div class="cli-card-h-top">'+
                '<span class="cli-card-h-dot" style="background:'+(c.osA>0?T.amber:sc)+'"></span>'+
                '<span class="cli-card-h-nome">'+escHtml(c.nome)+'</span>'+
            '</div>'+
            '<div class="cli-card-h-end">'+escHtml(c.endereco||c.cidade||'—')+'</div>'+
            '<div class="cli-card-h-status" style="color:'+(c.osA>0?T.amber:sc)+'">● '+st+'</div>'+
            '<div class="cli-card-h-acts">'+
                (tel?'<a class="cli-act-mini wpp" href="https://wa.me/55'+tel+'" target="_blank" onclick="event.stopPropagation()" title="WhatsApp">💬</a>':'')+
                (tel?'<a class="cli-act-mini tel" href="tel:+55'+tel+'" onclick="event.stopPropagation()" title="Ligar">📞</a>':'')+
                '<span class="cli-act-mini ficha" onclick="event.stopPropagation();event.preventDefault();abrirModalCliente('+c.id+')" title="Ver detalhes">📋</span>'+
            '</div>'+
        '</div>';
    });
    cont.innerHTML=h;
}

// ═══════════════════ MODAL COM MINI-MAPA LEAFLET ═══════════════════
function abrirModalCliente(id){
    const c=CLI_DATA.find(x=>x.id===id);if(!c)return;
    const sc=c.bloqueado?T.red:T.green;

    document.getElementById('modal-header').innerHTML=
        '<span class="modal-header-dot" style="background:'+(c.osA>0?T.amber:sc)+'"></span>'+
        '<div class="modal-header-info">'+
            '<div class="modal-header-nome">👤 '+escHtml(c.nome)+'</div>'+
            '<div class="modal-header-end">📍 '+escHtml(c.endereco||c.cidade||'—')+'</div>'+
        '</div>';

    document.getElementById('modal-body-mapa').innerHTML=
        '<div id="mini-mapa-modal" style="width:100%;height:100%"></div>';

    const tel=(c.telefone||'').replace(/[^\d]/g,'');
    document.getElementById('modal-footer-links').innerHTML=
        '<a href="https://maps.google.com/?q='+c.lat+','+c.lng+'" target="_blank" class="modal-btn maps">🗺 Maps</a>'+
        '<a href="https://waze.com/ul?ll='+c.lat+','+c.lng+'&navigate=yes" target="_blank" class="modal-btn waze">🔵 Waze</a>'+
        '<a href="https://www.google.com/maps/@?api=1&map_action=pano&viewpoint='+c.lat+','+c.lng+'" target="_blank" class="modal-btn street">🏠 Street View</a>'+
        (tel?'<a href="https://wa.me/55'+tel+'" target="_blank" class="modal-btn wpp">💬 WhatsApp</a>':'')+
        (tel?'<a href="tel:+55'+tel+'" class="modal-btn tel">📞 Ligar</a>':'')+
        '<a href="cliente_detalhe.php?id='+c.id+'" target="_blank" class="modal-btn ficha">📋 Ficha</a>';

    document.getElementById('modal-mapa').classList.add('show');

    setTimeout(function(){
        if(_miniMapaModal){_miniMapaModal.remove();_miniMapaModal=null;}
        _miniMapaModal=L.map('mini-mapa-modal',{
            center:[c.lat,c.lng],zoom:17,zoomControl:true,attributionControl:false
        });
        L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',{maxZoom:21}).addTo(_miniMapaModal);
        L.marker([c.lat,c.lng],{
            icon:L.divIcon({className:'',html:'<div style="width:20px;height:20px;border-radius:50%;background:'+T.pink+';border:3px solid #fff;box-shadow:0 0 12px '+T.pink+'"></div>',iconSize:[20,20],iconAnchor:[10,10]})
        }).addTo(_miniMapaModal).bindPopup('<b>'+escHtml(c.nome)+'</b><br>'+escHtml(c.endereco||c.cidade||'—')).openPopup();
        L.circle([c.lat,c.lng],{radius:100,color:T.green,fillColor:T.green,fillOpacity:0.06,weight:2,dashArray:'6,4'}).addTo(_miniMapaModal);
        setTimeout(()=>_miniMapaModal.invalidateSize(),100);
    },300);
}

function fecharModal(){
    document.getElementById('modal-mapa').classList.remove('show');
    document.getElementById('modal-body-mapa').innerHTML='';
    if(_miniMapaModal){_miniMapaModal.remove();_miniMapaModal=null;}
}

document.getElementById('modal-mapa').addEventListener('click',function(e){if(e.target===this)fecharModal()});
document.addEventListener('keydown',e=>{if(e.key==='Escape')fecharModal()});

// ═══════════════════ CENTRALIZAR ═══════════════════
function toggleCentralizar(){
    _centralizarAtivo=!_centralizarAtivo;
    if(_centralizarAtivo&&_clienteSelecionado)aplicarCentralizacao(_clienteSelecionado);
    else{if(map._circuloRaio){map.removeLayer(map._circuloRaio);map._circuloRaio=null}}
}
function aplicarCentralizacao(c){
    if(!c||!c.lat||!c.lng)return;
    if(map._circuloRaio)map.removeLayer(map._circuloRaio);
    map._circuloRaio=L.circle([c.lat,c.lng],{radius:100,color:T.green,fillColor:T.green,fillOpacity:0.06,weight:2,dashArray:'6,4'}).addTo(map);
}

// ═══════════════════ FILTROS ═══════════════════
function toggleFiltroRede(tipo,btn){
    if(tipo==='clientes'){
        _mostrarClientes=!_mostrarClientes;
        btn.classList.toggle('on',_mostrarClientes);
        plotarClientes();renderClientesBar();return;
    }
    if(_filtrosRedeAtivos.has(tipo)){_filtrosRedeAtivos.delete(tipo);btn.classList.remove('on')}
    else{_filtrosRedeAtivos.add(tipo);btn.classList.add('on')}
    aplicarFiltrosInfra();
}
function aplicarFiltrosInfra(){
    layerInfra.clearLayers();
    if(_filtrosRedeAtivos.size===0)return;
    if(!_kmlCarregado){carregarKML().then(()=>aplicarFiltrosInfra());return}
    _kmlMarkers.forEach(mk=>{
        if(!_filtrosRedeAtivos.has(mk.kmlTipo))return;
        if(mk.isLinha){
            L.polyline(mk.latlngs,{color:mk.cor,weight:3,opacity:.9}).addTo(layerInfra)
             .bindPopup('<b style="color:'+mk.cor+'">〰️ '+escHtml(mk.nome)+'</b><br><span style="font-size:9px;color:'+T.muted+'">📍 '+mk.lat.toFixed(5)+', '+mk.lng.toFixed(5)+'</span>');
        }else{
            L.marker([mk.lat,mk.lng],{icon:criarIconeKML(mk.kmlTipo)}).addTo(layerInfra)
             .bindPopup('<b style="color:'+mk.cor+'">📍 '+escHtml(mk.nome)+'</b><br><span style="font-size:9px;color:'+T.muted+'">📍 '+mk.lat.toFixed(5)+', '+mk.lng.toFixed(5)+'</span>');
        }
    });
}

function filtrarTudo(){
    const cidade=document.getElementById('filtro-cidade').value;
    if(cidade&&COORDS_CID[cidade])map.flyTo(COORDS_CID[cidade],14,{duration:0.8});
    plotarClientes();renderClientesBar();
}

// ═══════════════════ KML ═══════════════════
function carregarKML(){
    if(_kmlCarregado||_kmlTentativas>=2)return Promise.resolve();
    _kmlTentativas++;
    return fetch('projeto_rede.kml?v='+Date.now()).then(r=>r.ok?r.text():null).then(txt=>{
        if(!txt||txt.trim().startsWith('<!DOCTYPE'))return;
        const xml=new DOMParser().parseFromString(txt,'text/xml');
        if(xml.querySelector('parsererror'))return;
        function classificar(nome){
            const n=nome.toUpperCase();
            if(/^CX\b/.test(n))return'cx';if(/^CTO\b/.test(n))return'cto';
            if(/CEO/.test(n))return'ceo';if(/^CR[\s\-]?\d|\bCR\b/.test(n))return'cr';
            if(/^CEP\b/.test(n))return'cep';if(/^CEL\b/.test(n))return'cel';
            if(/EMENDA|FUS[AÃ]O/.test(n))return'emenda';
            if(/\bFEEDER\b/.test(n))return'feeder';if(/\bRAMAL\b/.test(n))return'ramal';
            if(/\bDROP\b/.test(n))return'drop';if(/\bPTP\b/.test(n))return'ptp';
            if(/^CB\b|^CABO\b/.test(n))return'cabo';if(/\bFO\b|FIBRA/.test(n))return'fo';
            if(/POSTE/.test(n))return'poste';if(/RESERVA|RESEVA|\bRES\b|PASSAGEM/.test(n))return'reserva';
            if(/TORRE/.test(n))return'torre';if(/\bPOP\b|DTC/.test(n))return'pop';
            if(/PONTO/.test(n))return'ponto';return'outro';
        }
        _kmlMarkers=[];
        xml.querySelectorAll('Placemark').forEach(p=>{
            const nome=p.querySelector('name')?.textContent?.trim();if(!nome)return;
            const kmlTipo=classificar(nome);
            const lineEl=p.querySelector('LineString');
            if(lineEl){
                const coordEl=lineEl.querySelector('coordinates');if(!coordEl)return;
                const latlngs=coordEl.textContent.trim().split(/\s+/).map(tok=>{const pts=tok.split(',');return[parseFloat(pts[1]),parseFloat(pts[0])]}).filter(ll=>!isNaN(ll[0]));
                if(latlngs.length<2)return;
                const mid=Math.floor(latlngs.length/2);
                _kmlMarkers.push({nome,kmlTipo,cor:CORES_KML[kmlTipo]||CORES_KML.outro,lat:latlngs[mid][0],lng:latlngs[mid][1],latlngs,isLinha:true});
                return;
            }
            const ptEl=p.querySelector('Point');if(!ptEl)return;
            const coordEl=ptEl.querySelector('coordinates');if(!coordEl)return;
            const raw=coordEl.textContent.trim().split(',');if(raw.length<2)return;
            const lng=parseFloat(raw[0]),lat=parseFloat(raw[1]);if(isNaN(lat)||isNaN(lng))return;
            _kmlMarkers.push({nome,kmlTipo,cor:CORES_KML[kmlTipo]||CORES_KML.outro,lat,lng,isLinha:false});
        });
        _kmlCarregado=true;
    }).catch(()=>{});
}
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>