<?php
// mapa.php — Mapa Operacional (VERSÃO CORRIGIDA - ESTILO GOOGLE EARTH)
$pageActive = 'mapa';
$pageTitle  = 'Mapa Operacional';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

// Cores do tema
$corPrincipal = getConfig('cor_primaria', '#00d4ff');
$corAcento    = getConfig('cor_acento',    '#ec4899');
$corFundo     = getConfig('cor_fundo',     '#0d0714');
$corSidebar   = getConfig('cor_sidebar',   '#150a1e');

$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']));
$bloqueados     = count(array_filter($clientes, fn($c)=>$c['bloqueado']));
$comOS          = count(array_unique(array_column(
    array_filter($clientes, fn($c)=>($osAbertas[$c['id']]??0)>0), 'id')));

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

$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']        ?? '',
    '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);

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>
/* ═══════════════════════════════════════════════
   LAYOUT PRINCIPAL
   ═══════════════════════════════════════════════ */
.mapa-layout {
    display: grid;
    grid-template-columns: 320px 1fr;
    height: calc(100vh - 56px);
    overflow: hidden;
    gap: 12px;
    padding: 12px;
    padding-bottom: calc(12px + 10vh);
    background: var(--bg);
}

.mapa-painel {
    background: var(--surface);
    border-radius: 14px;
    border: 1px solid var(--border);
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    box-shadow: 0 4px 24px rgba(0,0,0,.4);
}

#map-area {
    position: relative;
    overflow: hidden;
    background: <?= e($corFundo) ?>;
}

#main-map {
    width: 100%;
    height: 100%;
    border-radius: 12px;
}

/* ═══════════════════════════════════════════════
   PAINEL LATERAL
   ═══════════════════════════════════════════════ */
.mapa-painel::-webkit-scrollbar { width: 4px; }
.mapa-painel::-webkit-scrollbar-thumb { background: var(--border2); border-radius: 2px; }

.painel-header {
    padding: 16px;
    border-bottom: 1px solid var(--border);
    flex-shrink: 0;
}

.painel-title {
    font-size: 13px;
    font-weight: 700;
    margin-bottom: 12px;
    color: var(--text);
    letter-spacing: 0.5px;
}

.painel-search {
    position: relative;
    margin-bottom: 8px;
}

.painel-search input {
    width: 100%;
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 10px 12px 10px 34px;
    font-family: var(--ui);
    font-size: 12px;
    color: var(--text);
    outline: none;
    transition: all .2s;
}

.painel-search input:focus {
    border-color: <?= e($corPrincipal) ?>;
    box-shadow: 0 0 0 3px <?= e($corPrincipal) ?>22;
}

.painel-search span {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    color: var(--muted);
}

/* ═══════════════════════════════════════════════
   TOGGLE: CLIENTE x INFRAESTRUTURA
   ═══════════════════════════════════════════════ */
.modo-toggle {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
    margin-bottom: 10px;
}

.modo-btn {
    padding: 9px 6px;
    border-radius: 8px;
    font-size: 11px;
    font-weight: 700;
    font-family: var(--mono);
    cursor: pointer;
    border: 1px solid var(--border);
    background: var(--card);
    color: var(--muted);
    transition: all .2s;
    text-align: center;
}

.modo-btn.on {
    background: <?= e($corPrincipal) ?>;
    color: #050e1a;
    border-color: <?= e($corPrincipal) ?>;
    box-shadow: 0 2px 8px <?= e($corPrincipal) ?>44;
}

.modo-btn:hover:not(.on) {
    border-color: var(--border2);
    color: var(--text);
}

.painel-select {
    width: 100%;
    background: var(--card);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 10px 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='%234a6a8a' d='M5 7L1 3h8z'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 12px center;
    padding-right: 32px;
    cursor: pointer;
    transition: all .2s;
}

.painel-select:focus {
    border-color: <?= e($corPrincipal) ?>;
    box-shadow: 0 0 0 3px <?= e($corPrincipal) ?>22;
}

/* ═══════════════════════════════════════════════
   FILTROS KML (CX / CEO / FO)
   ═══════════════════════════════════════════════ */
.filtros-chips {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    padding: 10px 16px;
    border-bottom: 1px solid var(--border);
    flex-shrink: 0;
}

.chip-btn {
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 700;
    font-family: var(--mono);
    cursor: pointer;
    border: 1px solid var(--border);
    background: var(--card);
    color: var(--muted);
    transition: all .2s;
    white-space: nowrap;
}

.chip-btn.on {
    background: <?= e($corPrincipal) ?>;
    color: #050e1a;
    border-color: <?= e($corPrincipal) ?>;
    box-shadow: 0 2px 8px <?= e($corPrincipal) ?>44;
}

.chip-btn.on.fo {
    background: #a855f7;
    border-color: #a855f7;
    box-shadow: 0 2px 8px #a855f744;
}

.chip-btn:hover:not(.on) {
    border-color: var(--border2);
    color: var(--text);
    background: var(--card2);
}

/* ═══════════════════════════════════════════════
   LISTA DE CLIENTES
   ═══════════════════════════════════════════════ */
.painel-lista {
    flex: 1;
    overflow-y: auto;
}

.painel-lista::-webkit-scrollbar { width: 3px; }

.cli-item {
    padding: 12px 16px;
    border-bottom: 1px solid rgba(30,51,86,.3);
    cursor: pointer;
    transition: all .15s;
    display: flex;
    align-items: center;
    gap: 10px;
}

.cli-item:hover {
    background: rgba(0,212,255,.04);
}

.cli-item.focused {
    background: rgba(0,212,255,.1);
    border-left: 3px solid <?= e($corPrincipal) ?>;
    padding-left: 13px;
}

.cli-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    flex-shrink: 0;
}

.cli-info {
    flex: 1;
    min-width: 0;
}

.cli-nome {
    font-size: 12px;
    font-weight: 600;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 2px;
}

.cli-sub {
    font-size: 9px;
    color: var(--muted);
    font-family: var(--mono);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* ═══════════════════════════════════════════════
   CARD DE CLIENTE — ENDEREÇO + AÇÕES RÁPIDAS
   ═══════════════════════════════════════════════ */
.cli-card {
    padding: 10px 14px;
    border-bottom: 1px solid rgba(30,51,86,.3);
    cursor: pointer;
    transition: all .15s;
}
.cli-card:hover { background: rgba(0,212,255,.04); }
.cli-card.focused {
    background: rgba(0,212,255,.1);
    border-left: 3px solid <?= e($corPrincipal) ?>;
    padding-left: 11px;
}
.cli-card-nome {
    font-size: 12px;
    font-weight: 700;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 2px;
}
.cli-card-end {
    font-size: 10px;
    color: var(--muted);
    line-height: 1.35;
    margin-bottom: 6px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}
.cli-card-acts {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}
.cli-act {
    padding: 4px 9px;
    border-radius: 6px;
    font-size: 9px;
    font-weight: 700;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 3px;
    transition: all .15s;
}
.cli-act.maps { background: rgba(66,133,244,.12); color: #4285F4; }
.cli-act.waze { background: rgba(51,204,255,.12); color: #33ccff; }
.cli-act.wpp  { background: rgba(37,211,102,.12); color: #25D366; }
.cli-act.tel  { background: var(--card2); color: var(--text); border: 1px solid var(--border); }
.cli-act:hover { transform: translateY(-1px); filter: brightness(1.15); }

/* ═══════════════════════════════════════════════
   CARD DE INFRAESTRUTURA (KML)
   ═══════════════════════════════════════════════ */
.infra-card {
    padding: 10px 14px;
    border-bottom: 1px solid rgba(30,51,86,.3);
    cursor: pointer;
    transition: all .15s;
    display: flex;
    align-items: center;
    gap: 10px;
}
.infra-card:hover { background: rgba(0,212,255,.04); }
.infra-card.focused {
    background: rgba(0,212,255,.1);
    border-left: 3px solid <?= e($corPrincipal) ?>;
    padding-left: 11px;
}
.infra-dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    flex-shrink: 0;
}
.infra-info { flex: 1; min-width: 0; }
.infra-nome {
    font-size: 12px;
    font-weight: 600;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 2px;
}
.infra-cat {
    font-size: 9px;
    color: var(--muted);
    font-family: var(--mono);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* ═══════════════════════════════════════════════
   MAPA - ESTILO GOOGLE EARTH
   ═══════════════════════════════════════════════ */
.leaflet-container {
    background: #1a1a2e !important;
}

.leaflet-popup-content-wrapper {
    background: <?= e($corSidebar) ?> !important;
    color: #dde8f5 !important;
    border: 1px solid rgba(255,255,255,.15) !important;
    border-radius: 10px !important;
    box-shadow: 0 8px 32px rgba(0,0,0,.7) !important;
    font-family: 'Exo 2', sans-serif !important;
}

.leaflet-popup-tip {
    background: <?= e($corSidebar) ?> !important;
}

.leaflet-popup-content {
    margin: 12px 16px !important;
    font-size: 12px !important;
    line-height: 1.6 !important;
}

/* ═══════════════════════════════════════════════
   BADGE DO CLIENTE NO MAPA
   ═══════════════════════════════════════════════ */
.cliente-badge {
    background: rgba(13, 7, 20, 0.95);
    border: 1px solid rgba(255,255,255,.2);
    border-radius: 10px;
    padding: 14px;
    color: #fff;
    font-family: 'Exo 2', sans-serif;
    font-size: 12px;
    min-width: 240px;
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 32px rgba(0,0,0,.6);
}

.cliente-badge .badge-nome {
    font-size: 14px;
    font-weight: 700;
    color: <?= e($corAcento) ?>;
    margin-bottom: 8px;
}

.cliente-badge .badge-info {
    color: #a0b4cc;
    font-size: 11px;
    margin-bottom: 4px;
}

.cliente-badge .badge-botoes {
    display: flex;
    gap: 6px;
    margin-top: 10px;
    flex-wrap: wrap;
}

.cliente-badge .badge-btn {
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 10px;
    font-weight: 600;
    text-decoration: none;
    transition: all .2s;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.badge-btn.waze {
    background: #33ccff;
    color: #000;
}

.badge-btn.maps {
    background: #4285F4;
    color: #fff;
}

.badge-btn.whatsapp {
    background: #25D366;
    color: #fff;
}

.badge-btn.ligar {
    background: var(--card);
    border: 1px solid var(--border);
    color: var(--text);
}

.badge-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0,0,0,.3);
}

/* ═══════════════════════════════════════════════
   TOOLTIP DO LEAFLET
   ═══════════════════════════════════════════════ */
.leaflet-tooltip {
    background: rgba(13, 7, 20, 0.95) !important;
    color: <?= e($corPrincipal) ?> !important;
    border: 1px solid <?= e($corAcento) ?> !important;
    border-radius: 6px !important;
    font-family: 'Exo 2', sans-serif !important;
    font-size: 10px !important;
    font-weight: 700 !important;
    padding: 4px 8px !important;
}

.leaflet-tooltip-top:before { border-top-color: <?= e($corAcento) ?> !important; }
.leaflet-tooltip-bottom:before { border-bottom-color: <?= e($corAcento) ?> !important; }
.leaflet-tooltip-left:before { border-left-color: <?= e($corAcento) ?> !important; }
.leaflet-tooltip-right:before { border-right-color: <?= e($corAcento) ?> !important; }

/* ═══════════════════════════════════════════════
   RESPONSIVO
   ═══════════════════════════════════════════════ */
@media(max-width:768px) {
    .mapa-layout {
        grid-template-columns: 1fr;
        grid-template-rows: auto 1fr;
        padding: 8px;
        gap: 8px;
    }
    
    .mapa-painel {
        height: auto;
        max-height: 45vh;
    }
    
    #map-area {
        min-height: 400px;
    }
}
</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-layout">
    <div class="mapa-painel">
        <div class="painel-header">
            <div class="painel-title">◎ Buscar no Mapa</div>
            <div class="modo-toggle">
                <button class="modo-btn on" id="modo-cliente" onclick="setModo('cliente',this)">👤 Clientes</button>
                <button class="modo-btn" id="modo-infra" onclick="setModo('infra',this)">🏗 Infraestrutura</button>
            </div>
            <div class="painel-search">
                <span>⌕</span>
                <input type="text" id="busca-cli" placeholder="Buscar por nome..." oninput="filtrarLista()"/>
            </div>
            <select class="painel-select" id="filtro-cidade" onchange="filtrarLista()">
                <option value="">Todas as cidades</option>
            </select>
        </div>
        <div class="filtros-chips" id="filtros-kml" style="display:none">
            <button class="chip-btn on" onclick="setFiltroKML('todos',this)">Todos</button>
            <button class="chip-btn" onclick="setFiltroKML('cx',this)">CX</button>
            <button class="chip-btn" onclick="setFiltroKML('ceo',this)">CEO</button>
            <button class="chip-btn" onclick="setFiltroKML('fo',this)">FO</button>
        </div>
        <div class="painel-lista" id="lista-clientes"></div>
    </div>
    <div id="map-area">
        <div id="main-map"></div>
    </div>
</div>

<script>
// ═══════════════════════════════════════════════
//  DADOS DO PHP
// ═══════════════════════════════════════════════
const CLI_DATA  = <?= $jsCli  ?>;
const CIDADES   = <?= $jsCidades ?>;
const COR_PRINCIPAL = '<?= e($corPrincipal) ?>';
const COR_ACENTO    = '<?= e($corAcento) ?>';
</script>

<script>
// ═══════════════════════════════════════════════
//  VARIÁVEIS GLOBAIS
// ═══════════════════════════════════════════════
let map, darkTile, satTile, layerCTOs, layerCli, layerFixos;
let sateliteAtivo = false;
let badgeAtual = null;
let modoAtivo = 'cliente';
let _kmlMarkers = [];

// ═══════════════════════════════════════════════
//  INICIALIZAÇÃO DO MAPA
// ═══════════════════════════════════════════════
(function() {
    // Preenche dropdown de cidades
    const sel = document.getElementById('filtro-cidade');
    CIDADES.forEach(function(cid) {
        const opt = document.createElement('option');
        opt.value = cid;
        opt.textContent = cid;
        sel.appendChild(opt);
    });

    // Inicializa mapa
    map = L.map('main-map', { 
        center: [-20.27, -50.55], 
        zoom: 11, 
        zoomControl: false, 
        preferCanvas: true 
    });
    L.control.zoom({position:'bottomright'}).addTo(map);

    darkTile = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
        attribution: '© CARTO',
        maxZoom: 21
    });
    satTile = L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
        attribution: '© Google',
        maxZoom: 21
    });
    darkTile.addTo(map);

    // Camadas
    layerCTOs = L.layerGroup();
    layerCli  = L.layerGroup();
    layerFixos = L.layerGroup();
    layerFixos.addTo(map);

    // Inicializa dados
    atualizarMapa();
    renderLista();
    carregarKML();
    plotarClientesFixos();
    
    setTimeout(() => map.invalidateSize(), 150);
    window.addEventListener('resize', () => map.invalidateSize());

    // Botão flutuante CTOs
    var btnCTOs = L.control({position: 'topleft'});
    btnCTOs.onAdd = function() {
        var div = L.DomUtil.create('div');
        div.innerHTML = '<button id="btn-ctos-flutuante" style="background:rgba(13,7,20,.95);border:1px solid '+COR_ACENTO+';border-radius:8px;color:'+COR_ACENTO+';font-family:monospace;font-size:11px;padding:8px 14px;cursor:pointer;margin:10px;backdrop-filter:blur(8px);font-weight:700;transition:all .2s">▣ CTOs</button>';
        return div;
    };
    btnCTOs.addTo(map);

    // Botão flutuante satélite
    var btnSat = L.control({position: 'topleft'});
    btnSat.onAdd = function() {
        var div = L.DomUtil.create('div');
        div.innerHTML = '<button id="btn-sat-flutuante" style="background:rgba(13,7,20,.95);border:1px solid rgba(255,255,255,.3);border-radius:8px;color:#888;font-family:monospace;font-size:11px;padding:8px 14px;cursor:pointer;margin:10px;margin-top:0;backdrop-filter:blur(8px);font-weight:700;transition:all .2s">🛰 Satélite</button>';
        return div;
    };
    btnSat.addTo(map);

    // Delegação de eventos para botões flutuantes
    document.addEventListener('click', function(e) {
        if (e.target && e.target.id === 'btn-ctos-flutuante') {
            var btn = e.target;
            if(map.hasLayer(layerCTOs)) {
                map.removeLayer(layerCTOs);
                btn.style.borderColor = 'rgba(255,255,255,.3)';
                btn.style.color = '#888';
            } else {
                layerCTOs.addTo(map);
                btn.style.borderColor = COR_ACENTO;
                btn.style.color = COR_ACENTO;
            }
        }
        if (e.target && e.target.id === 'btn-sat-flutuante') {
            var btnSat = e.target;
            if(!sateliteAtivo) {
                map.removeLayer(darkTile);
                satTile.addTo(map);
                sateliteAtivo = true;
                btnSat.style.borderColor = COR_PRINCIPAL;
                btnSat.style.color = COR_PRINCIPAL;
                btnSat.textContent = '🛰 Mapa';
            } else {
                map.removeLayer(satTile);
                darkTile.addTo(map);
                sateliteAtivo = false;
                btnSat.style.borderColor = 'rgba(255,255,255,.3)';
                btnSat.style.color = '#888';
                btnSat.textContent = '🛰 Satélite';
            }
        }
    });

})();

// ═══════════════════════════════════════════════
//  PONTOS FIXOS DOS CLIENTES (BADGE NO MAPA)
// ═══════════════════════════════════════════════
function plotarClientesFixos() {
    layerFixos.clearLayers();
    CLI_DATA.forEach(function(c) {
        if (!c.lat || !c.lng) return;
        
        var corIcon = c.osA > 0 ? '#f59e0b' : (c.bloqueado ? '#ef4444' : COR_ACENTO);
        
        var icon = L.divIcon({
            className: '',
            html: '<div style="width:28px;height:28px;border-radius:50%;background:'+COR_PRINCIPAL+';border:3px solid '+corIcon+';box-shadow:0 0 20px '+corIcon+'AA, 0 0 40px '+corIcon+'44;cursor:pointer;transition:transform 0.2s;display:flex;align-items:center;justify-content:center"><div style="width:8px;height:8px;border-radius:50%;background:#fff;box-shadow:0 0 6px #fff"></div></div>',
            iconSize: [28, 28],
            iconAnchor: [14, 14]
        });
        
        var marker = L.marker([c.lat, c.lng], {
            icon: icon,
            opacity: 1,
            zIndexOffset: 1000
        }).addTo(layerFixos);
        
        marker.bindTooltip(c.nome, {
            permanent: false,
            direction: 'top',
            offset: [0, -18]
        });
        
        marker.on('click', function(e) {
            L.DomEvent.stopPropagation(e);
            abrirBadgeCliente(c, [c.lat, c.lng]);
        });
        
        marker._cliData = c;
    });
}

// ═══════════════════════════════════════════════
//  ABRIR BADGE NO MAPA (SUBSTITUI O MODAL)
// ═══════════════════════════════════════════════
function abrirBadgeCliente(c, latlng) {
    // Fecha badge anterior se existir
    if (badgeAtual) {
        map.removeLayer(badgeAtual);
    }
    
    var html = '<div class="cliente-badge">'+
        '<div class="badge-nome">👤 ' + escHtml(c.nome) + '</div>'+
    '</div>';
    
    badgeAtual = L.popup({
        closeButton: true,
        autoClose: false,
        closeOnClick: false,
        className: 'badge-popup',
        maxWidth: 300,
        offset: [0, -15]
    })
    .setLatLng(latlng)
    .setContent(html)
    .openOn(map);
    
    // Centraliza o mapa no cliente
    map.flyTo(latlng, 17, { duration: 0.8 });
}

// ═══════════════════════════════════════════════
//  CLIENTES DINÂMICOS
// ═══════════════════════════════════════════════
function atualizarMapa() {
    layerCli.clearLayers();
    var lista = filtrados();
    lista.forEach(function(c) {
        if (!c.lat || !c.lng) return;
        var cor = c.osA > 0 ? '#f59e0b' : (c.bloqueado ? '#ef4444' : COR_ACENTO);
        var icon = L.divIcon({
            className: '',
            html: '<div style="width:12px;height:12px;border-radius:50%;background:'+cor+';border:2px solid '+cor+';box-shadow:0 0 8px '+cor+'88"></div>',
            iconSize: [12, 12],
            iconAnchor: [6, 6]
        });
        
        var m = L.marker([c.lat, c.lng], {icon: icon}).addTo(layerCli);
        m._cliId = c.id;
        m._cliData = c;
        
        m.on('click', function(e) {
            L.DomEvent.stopPropagation(e);
            abrirBadgeCliente(c, [c.lat, c.lng]);
        });
    });
    if (!map.hasLayer(layerCli)) {
        layerCli.addTo(map);
    }
}

// ═══════════════════════════════════════════════
//  LISTA LATERAL
// ═══════════════════════════════════════════════
function renderLista() {
    if (modoAtivo === 'infra') { renderListaInfra(); return; }
    var cont = document.getElementById('lista-clientes');
    var lista = filtrados();
    if (!lista.length) {
        cont.innerHTML = '<div style="padding:20px;text-align:center;color:var(--muted);font-size:11px">Nenhum cliente encontrado.</div>';
        return;
    }
    var html = '';
    lista.forEach(function(c) {
        var gps = c.lat && c.lng;
        var telefoneLimpo = (c.telefone || '').replace(/[^\d]/g, '');
        var endTxt = c.endereco || c.cidade || 'Endereço não cadastrado';
        html += '<div class="cli-card" id="li-'+c.id+'" onclick="cliClick('+c.id+','+gps+')">'+
            '<div class="cli-card-nome">'+escHtml(c.nome)+'</div>'+
            '<div class="cli-card-end">'+(gps ? escHtml(endTxt) : '<span style="color:#f59e0b">⚠ Sem GPS — '+escHtml(endTxt)+'</span>')+'</div>'+
            '<div class="cli-card-acts">'+
                (gps ? '<a class="cli-act maps" href="https://maps.google.com/?q='+c.lat+','+c.lng+'" target="_blank" onclick="event.stopPropagation()">🗺 Maps</a>' : '')+
                (gps ? '<a class="cli-act waze" href="https://waze.com/ul?ll='+c.lat+','+c.lng+'&navigate=yes" target="_blank" onclick="event.stopPropagation()">🔵 Waze</a>' : '')+
                (telefoneLimpo ? '<a class="cli-act wpp" href="https://wa.me/55'+telefoneLimpo+'" target="_blank" onclick="event.stopPropagation()">💬 WhatsApp</a>' : '')+
                (telefoneLimpo ? '<a class="cli-act tel" href="tel:+55'+telefoneLimpo+'" onclick="event.stopPropagation()">📞 Ligar</a>' : '')+
            '</div>'+
        '</div>';
    });
    cont.innerHTML = html;
}

// ═══════════════════════════════════════════════
//  LISTA DE INFRAESTRUTURA (KML)
// ═══════════════════════════════════════════════
function renderListaInfra() {
    var cont = document.getElementById('lista-clientes');
    var busca = document.getElementById('busca-cli').value.toLowerCase();
    var lista = _kmlMarkers.filter(function(k) {
        if (filtroKMLAtivo !== 'todos' && k.kmlTipo !== filtroKMLAtivo) return false;
        if (busca && !k.nome.toLowerCase().includes(busca)) return false;
        return true;
    });
    if (!lista.length) {
        cont.innerHTML = '<div style="padding:20px;text-align:center;color:var(--muted);font-size:11px">Nenhuma marcação encontrada.</div>';
        return;
    }
    var html = '';
    lista.forEach(function(k, idx) {
        html += '<div class="infra-card" id="ki-'+idx+'" onclick="infraClick('+idx+')">'+
            '<span class="infra-dot" style="background:'+k.cor+'"></span>'+
            '<div class="infra-info">'+
                '<div class="infra-nome">'+escHtml(k.nome)+'</div>'+
                '<div class="infra-cat">'+escHtml(k.categoriaLabel)+'</div>'+
            '</div>'+
        '</div>';
    });
    cont.innerHTML = html;
}

function infraClick(idx) {
    document.querySelectorAll('.infra-card').forEach(el => el.classList.remove('focused'));
    var el = document.getElementById('ki-'+idx);
    if (el) { el.classList.add('focused'); el.scrollIntoView({behavior:'smooth', block:'nearest'}); }
    var k = _kmlMarkers[idx];
    if (!k) return;
    if (!map.hasLayer(layerCTOs)) {
        layerCTOs.addTo(map);
        var btnCTO = document.getElementById('btn-ctos-flutuante');
        if (btnCTO) { btnCTO.style.borderColor = COR_ACENTO; btnCTO.style.color = COR_ACENTO; }
    }
    map.flyTo([k.lat, k.lng], 18, { duration: 0.8 });
    setTimeout(function(){ k.marker.openPopup(); }, 850);
}

// ═══════════════════════════════════════════════
//  ALTERNAR MODO: CLIENTES x INFRAESTRUTURA
// ═══════════════════════════════════════════════
function setModo(modo, btn) {
    modoAtivo = modo;
    document.querySelectorAll('.modo-btn').forEach(b => b.classList.remove('on'));
    btn.classList.add('on');
    var busca = document.getElementById('busca-cli');
    var cidade = document.getElementById('filtro-cidade');
    var filtrosKml = document.getElementById('filtros-kml');
    if (modo === 'cliente') {
        busca.placeholder = 'Buscar por nome...';
        cidade.style.display = '';
        filtrosKml.style.display = 'none';
    } else {
        busca.placeholder = 'Buscar CX, CEO, FO...';
        cidade.style.display = 'none';
        filtrosKml.style.display = 'flex';
    }
    busca.value = '';
    renderLista();
}

function cliClick(id, temGPS) {
    document.querySelectorAll('.cli-item').forEach(el => el.classList.remove('focused'));
    var el = document.getElementById('li-'+id);
    if (el) { 
        el.classList.add('focused'); 
        el.scrollIntoView({behavior:'smooth', block:'nearest'}); 
    }
    if (!temGPS) { return; }
    
    // Encontra o cliente e centraliza no mapa com badge
    var cliente = CLI_DATA.find(function(c) { return c.id === id; });
    if (cliente && cliente.lat && cliente.lng) {
        abrirBadgeCliente(cliente, [cliente.lat, cliente.lng]);
    }
}

// ═══════════════════════════════════════════════
//  FILTROS
// ═══════════════════════════════════════════════
function filtrados() {
    var busca = document.getElementById('busca-cli').value.toLowerCase();
    var cidadeSel = document.getElementById('filtro-cidade').value;
    return CLI_DATA.filter(function(c) {
        if (busca && !c.nome.toLowerCase().includes(busca)) return false;
        if (cidadeSel && c.cidade !== cidadeSel) return false;
        return true;
    });
}

// ═══════════════════════════════════════════════
//  FILTRO DAS MARCAÇÕES KML (CX / CEO / FO)
// ═══════════════════════════════════════════════
var filtroKMLAtivo = 'todos';
function setFiltroKML(tipo, btn) {
    filtroKMLAtivo = tipo;
    document.querySelectorAll('.filtros-chips .chip-btn').forEach(b => b.classList.remove('on','fo'));
    btn.classList.add('on');
    if (tipo === 'fo') btn.classList.add('fo');
    if (!map.hasLayer(layerCTOs)) {
        layerCTOs.addTo(map);
        var btnCTO = document.getElementById('btn-ctos-flutuante');
        if (btnCTO) { btnCTO.style.borderColor = COR_ACENTO; btnCTO.style.color = COR_ACENTO; }
    }
    layerCTOs.eachLayer(function(m) {
        var t = m._kmlTipo || 'outro';
        var mostra = (tipo === 'todos') || (t === tipo);
        var el = m.getElement ? m.getElement() : null;
        if (el) el.style.display = mostra ? '' : 'none';
    });
    if (modoAtivo === 'infra') renderListaInfra();
}

function filtrarLista() { 
    atualizarMapa(); 
    renderLista(); 
}

// ═══════════════════════════════════════════════
//  KML (CTOs) - ESTILO GOOGLE EARTH
// ═══════════════════════════════════════════════
function carregarKML() {
    fetch('projeto_rede.kml?v='+Date.now())
        .then(function(r) { return r.ok ? r.text() : null; })
        .then(function(txt) {
            if (!txt) return;
            var xml = new DOMParser().parseFromString(txt, 'text/xml');
            
            // Processa todos os Placemarks mantendo TODAS as informações
            xml.querySelectorAll('Placemark').forEach(function(p) {
                var nome = p.querySelector('name') ? p.querySelector('name').textContent.trim() : 'Ponto';
                var descricao = p.querySelector('description') ? p.querySelector('description').textContent.trim() : '';
                var rc = p.querySelector('coordinates');
                if (!rc) return;
                
                var raw = rc.textContent.trim().split(',');
                if (raw.length < 2) return;
                
                var lng = parseFloat(raw[0]), lat = parseFloat(raw[1]);
                if (isNaN(lat) || isNaN(lng)) return;
                
                var isCX = /^CX/i.test(nome);
                var isCEO = /CEO/i.test(nome);
                var isCTO = /CTO/i.test(nome);
                var isOLT = /OLT/i.test(nome);
                var isTORRE = /TORRE/i.test(nome);
                var isFO = /\bFO\b/i.test(nome) || /FO[\s\-_]/i.test(nome) || /FIBRA\s*OPTICA/i.test(nome);

                // Categoria usada no filtro lateral (CX / CEO / FO / outro)
                var kmlTipo = 'outro';
                if (isFO) kmlTipo = 'fo';
                else if (isCX) kmlTipo = 'cx';
                else if (isCEO) kmlTipo = 'ceo';

                // Rótulo de categoria exibido no badge
                var categoriaLabel = isFO ? '🔗 Cabo de Fibra Óptica (FO)'
                    : isCX  ? '📦 Caixa de Atendimento (CX)'
                    : isCEO ? '🧩 CEO — Caixa de Emenda Óptica'
                    : isCTO ? '📦 Caixa de Atendimento (CTO)'
                    : isOLT ? '🟩 OLT'
                    : isTORRE ? '🔺 Torre'
                    : '📍 Ponto de Rede';

                // Estilo Google Earth
                var iconeHTML = '';
                var tamanho = 20;
                var corFO = '#a855f7';

                if (isFO) {
                    // Cabo/marcação de fibra óptica - destaque roxo, independente da categoria
                    iconeHTML = '<div style="width:20px;height:20px;border-radius:50%;background:rgba(168,85,247,.25);border:3px solid '+corFO+';box-shadow:0 0 16px '+corFO+'AA, inset 0 0 8px '+corFO+'44"><div style="width:6px;height:6px;border-radius:50%;background:'+corFO+';margin:4.5px auto"></div></div>';
                    tamanho = 20;
                } else if (isCX) {
                    // Caixa de atendimento - diamante azul
                    iconeHTML = '<div style="width:24px;height:24px;background:rgba(0,212,255,.2);border:3px solid '+COR_PRINCIPAL+';transform:rotate(45deg);box-shadow:0 0 16px '+COR_PRINCIPAL+'88, inset 0 0 8px '+COR_PRINCIPAL+'44"></div>';
                    tamanho = 24;
                } else if (isCTO) {
                    // CTO - círculo laranja
                    iconeHTML = '<div style="width:22px;height:22px;border-radius:50%;background:rgba(236,72,153,.2);border:3px solid '+COR_ACENTO+';box-shadow:0 0 16px '+COR_ACENTO+'88, inset 0 0 8px '+COR_ACENTO+'44"><div style="width:6px;height:6px;border-radius:50%;background:'+COR_ACENTO+';margin:5px auto"></div></div>';
                    tamanho = 22;
                } else if (isOLT) {
                    // OLT - hexágono verde
                    iconeHTML = '<div style="width:24px;height:24px;background:rgba(16,185,129,.2);border:3px solid #10b981;clip-path:polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%);box-shadow:0 0 16px #10b98188"></div>';
                    tamanho = 24;
                } else if (isTORRE) {
                    // Torre - triângulo vermelho
                    iconeHTML = '<div style="width:0;height:0;border-left:12px solid transparent;border-right:12px solid transparent;border-bottom:22px solid #ef4444;filter:drop-shadow(0 0 10px #ef444488)"></div>';
                    tamanho = 24;
                } else {
                    // Ponto genérico - círculo amarelo
                    iconeHTML = '<div style="width:18px;height:18px;border-radius:50%;background:rgba(245,158,11,.2);border:3px solid #f59e0b;box-shadow:0 0 12px #f59e0b88"><div style="width:4px;height:4px;border-radius:50%;background:#f59e0b;margin:4px auto"></div></div>';
                    tamanho = 18;
                }
                
                var icon = L.divIcon({
                    className: '',
                    html: iconeHTML,
                    iconSize: [tamanho, tamanho],
                    iconAnchor: [tamanho/2, tamanho/2]
                });
                
                // Descrição completa do KML
                var descHtml = '';
                if (descricao) {
                    descHtml = '<div style="font-size:10px;color:#5a7a9a;margin-top:4px;max-height:80px;overflow-y:auto">' + escHtml(descricao) + '</div>';
                }
                
                var popupContent = '<div style="min-width:200px;font-size:12px">'+
                    '<b style="color:'+COR_ACENTO+';font-size:13px">📦 '+escHtml(nome)+'</b><br>'+
                    '<span style="display:inline-block;margin-top:2px;padding:2px 8px;border-radius:10px;font-size:9px;font-weight:700;background:rgba(255,255,255,.08);color:'+(isFO?corFO:COR_ACENTO)+'">'+categoriaLabel+'</span><br>'+
                    '<span style="color:#5a7a9a;font-size:10px">📍 Carregando endereço...</span><br>'+
                    '<span style="color:#5a7a9a;font-size:9px;font-family:monospace">'+lat.toFixed(6)+', '+lng.toFixed(6)+'</span>'+
                    descHtml +
                    '<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap">'+
                        '<a href="https://maps.google.com/?q='+lat+','+lng+'" target="_blank" style="color:#4285F4;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(66,133,244,.1)">◉ Google Maps</a>'+
                        '<a href="https://waze.com/ul?ll='+lat+','+lng+'&navigate=yes" target="_blank" style="color:#33ccff;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(51,204,255,.1)">🔵 Waze</a>'+
                        '<a href="https://earth.google.com/web/search/'+lat+','+lng+'" target="_blank" style="color:#10b981;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(16,185,129,.1)">🌍 Google Earth</a>'+
                    '</div>'+
                '</div>';
                
                var marker = L.marker([lat, lng], {icon: icon}).bindPopup(popupContent).addTo(layerCTOs);
                marker._kmlTipo = kmlTipo;
                marker._kmlNome = nome;

                _kmlMarkers.push({
                    nome: nome,
                    kmlTipo: kmlTipo,
                    categoriaLabel: categoriaLabel,
                    cor: isFO ? corFO : (isCX ? COR_PRINCIPAL : (isCEO || isCTO ? COR_ACENTO : (isOLT ? '#10b981' : (isTORRE ? '#ef4444' : '#f59e0b')))),
                    lat: lat, lng: lng,
                    marker: marker
                });
                if (modoAtivo === 'infra') renderListaInfra();

                // Aplica filtro KML ativo (mantém oculto se categoria não corresponder)
                if (filtroKMLAtivo !== 'todos' && kmlTipo !== filtroKMLAtivo) {
                    marker.once('add', function() {
                        var el = marker.getElement ? marker.getElement() : null;
                        if (el) el.style.display = 'none';
                    });
                }
                
                // Geocodificação reversa para obter endereço
                fetch('ajax/geocodificar.php?acao=reverse&lat='+lat+'&lng='+lng)
                    .then(function(r) { return r.json(); })
                    .then(function(d) {
                        var end = lat.toFixed(5) + ', ' + lng.toFixed(5);
                        if (d.ok) {
                            end = [d.logradouro, d.bairro, d.cidade].filter(Boolean).join(', ');
                            if (d.cep) end += ' — CEP ' + d.cep;
                        }
                        var popupContent2 = '<div style="min-width:200px;font-size:12px">'+
                            '<b style="color:'+COR_ACENTO+';font-size:13px">📦 '+escHtml(nome)+'</b><br>'+
                            '<span style="display:inline-block;margin-top:2px;padding:2px 8px;border-radius:10px;font-size:9px;font-weight:700;background:rgba(255,255,255,.08);color:'+(isFO?corFO:COR_ACENTO)+'">'+categoriaLabel+'</span><br>'+
                            '<span style="color:#5a7a9a;font-size:10px">📍 '+escHtml(end)+'</span><br>'+
                            '<span style="color:#5a7a9a;font-size:9px;font-family:monospace">'+lat.toFixed(6)+', '+lng.toFixed(6)+'</span>'+
                            descHtml +
                            '<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap">'+
                                '<a href="https://maps.google.com/?q='+lat+','+lng+'" target="_blank" style="color:#4285F4;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(66,133,244,.1)">◉ Google Maps</a>'+
                                '<a href="https://waze.com/ul?ll='+lat+','+lng+'&navigate=yes" target="_blank" style="color:#33ccff;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(51,204,255,.1)">🔵 Waze</a>'+
                                '<a href="https://earth.google.com/web/search/'+lat+','+lng+'" target="_blank" style="color:#10b981;font-size:10px;text-decoration:none;font-weight:600;padding:4px 8px;border-radius:4px;background:rgba(16,185,129,.1)">🌍 Google Earth</a>'+
                            '</div>'+
                        '</div>';
                        marker.setPopupContent(popupContent2);
                    })
                    .catch(function() {});
            });
        })
        .catch(function() {});
}

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

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

