<?php
// cliente_detalhe.php — Detalhes do Cliente (MAPA COM ROTA REAL)
$pageActive = 'clientes';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);
if (!$id) { header('Location: clientes.php'); exit; }

$cliente = getClienteById($id);
if (!$cliente) { header('Location: clientes.php'); exit; }

$msg = $_GET['msg'] ?? '';

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

// Conta OS abertas
$stmtOsAb = pdo()->prepare(
    "SELECT COUNT(*) FROM ordens_servico
     WHERE cliente_id=? AND status IN ('ABERTA','AGENDADA','EM_ANDAMENTO')"
);
$stmtOsAb->execute([$id]);
$osAbertas = (int)$stmtOsAb->fetchColumn();

// Histórico de OS
$ordens = getOrdens(['cliente_id' => $id]);

// Fotos do cliente
$stmtFotos = pdo()->prepare(
    "SELECT * FROM clientes_fotos WHERE cliente_id=? ORDER BY data_envio DESC"
);
$stmtFotos->execute([$id]);
$todasFotos   = $stmtFotos->fetchAll();
$fotoFachada  = null;
$fotosCameras = [];
foreach ($todasFotos as $f) {
    if ($f['tipo'] === 'INSTALACAO' && !$fotoFachada) $fotoFachada = $f;
    if ($f['tipo'] === 'CAMERA') $fotosCameras[] = $f;
}

// Ações GET
if (isset($_GET['toggle_bloqueio'])) {
    if (!verifyCsrf($_GET['csrf'] ?? '')) { header("Location: cliente_detalhe.php?id=$id&erro=CSRF"); exit; }
    $novo = $cliente['bloqueado'] ? 0 : 1;
    pdo()->prepare("UPDATE clientes SET bloqueado=? WHERE id=?")->execute([$novo, $id]);
    header("Location: cliente_detalhe.php?id=$id&msg=" . ($novo ? 'Cliente+bloqueado.' : 'Cliente+desbloqueado.'));
    exit;
}

// GPS do cliente
$temGPS  = !empty($cliente['latitude']) && !empty($cliente['longitude']);
$cliLat  = $temGPS ? (float)$cliente['latitude']  : 0.0;
$cliLng  = $temGPS ? (float)$cliente['longitude'] : 0.0;
$clienteNomeJs = json_encode($cliente['nome']);

// GPS da CTO
$temCtoGps = !empty($cliente['olt_gps']);
$ctoCoords = $temCtoGps ? explode(',', $cliente['olt_gps']) : [];
$ctoLat    = isset($ctoCoords[0]) ? (float)trim($ctoCoords[0]) : 0.0;
$ctoLng    = isset($ctoCoords[1]) ? (float)trim($ctoCoords[1]) : 0.0;
$ctoNome   = $cliente['cto_nome'] ?? 'Caixa';

$pageTitle = $cliente['nome'];
require_once __DIR__ . '/includes/header.php';

if ($temGPS):
?>
<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>
<script src="assets/rota.js"></script>
<?php endif; ?>

<style>
.detalhe-grid{display:grid;grid-template-columns:1fr 1.3fr;gap:20px}
@media(max-width:767px){.detalhe-grid{grid-template-columns:1fr}}

/* Mapa */
#mini-map-cli{height:320px;border-radius:12px;border:1px solid var(--border);margin-bottom:18px;overflow:hidden}
.leaflet-container{background:<?= e($corFundo) ?>!important}
.leaflet-popup-content-wrapper{background:var(--card)!important;color:var(--text)!important;border:1px solid var(--border)!important;border-radius:10px!important;box-shadow:0 8px 32px rgba(0,0,0,.6)!important}
.leaflet-popup-tip{background:var(--card)!important}
.leaflet-popup-content{margin:10px 14px!important;font-size:12px!important;line-height:1.6!important}
.leaflet-popup-close-button{color:var(--muted)!important}

/* Status bar */
.status-bar{display:flex;align-items:center;gap:10px;margin-bottom:20px;flex-wrap:wrap}
.status-bar .badge-status{padding:5px 12px;border-radius:20px;font-size:11px;font-weight:700;font-family:var(--mono)}
.badge-ativo{background:rgba(16,185,129,.12);color:var(--green);border:1px solid rgba(16,185,129,.3)}
.badge-bloqueado{background:rgba(239,68,68,.12);color:var(--red);border:1px solid rgba(239,68,68,.3)}
.badge-os{background:rgba(245,158,11,.12);color:var(--amber);border:1px solid rgba(245,158,11,.3)}
.btn-acao{padding:6px 14px;border-radius:8px;font-size:11px;font-weight:700;cursor:pointer;transition:.15s;text-decoration:none;display:inline-flex;align-items:center;gap:5px;border:1px solid var(--border);background:var(--card);color:var(--text)}
.btn-acao:hover{border-color:var(--border2);background:var(--card2)}
.btn-acao.primary{background:<?= e($corPrincipal) ?>;color:#050e1a;border-color:<?= e($corPrincipal) ?>}
.btn-acao.danger{color:var(--red);border-color:rgba(239,68,68,.3)}
.btn-acao.danger:hover{background:rgba(239,68,68,.1)}

/* Fachada */
.fachada-card{margin-bottom:18px}
.fachada-card img{width:100%;max-height:200px;border-radius:12px;object-fit:cover;border:1px solid var(--border);cursor:zoom-in;transition:transform .15s}
.fachada-card img:hover{transform:scale(1.02)}

/* OS row */
.os-row{background:var(--card);border:1px solid var(--border);border-radius:10px;padding:14px 16px;margin-bottom:8px;transition:border .15s;display:block;text-decoration:none}
.os-row:hover{border-color:<?= e($corPrincipal) ?>44}
.os-row-header{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.os-num{font-family:var(--mono);font-size:12px;color:<?= e($corPrincipal) ?>;font-weight:700}
.os-tipo{font-size:11px;color:var(--muted);font-family:var(--mono);margin-bottom:4px}
.os-desc{font-size:12.5px;color:var(--text);margin-bottom:4px;line-height:1.5}
.os-meta{font-size:10px;color:var(--muted);font-family:var(--mono)}

/* Fotos */
.fotos-mini{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
.foto-mini{width:80px;height:80px;border-radius:8px;object-fit:cover;border:1px solid var(--border);cursor:zoom-in;transition:transform .15s}
.foto-mini:hover{transform:scale(1.05)}
</style>

<!-- Lightbox para fotos -->
<div id="lb" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:9000;align-items:center;justify-content:center;flex-direction:column;gap:12px;padding:20px">
  <button onclick="document.getElementById('lb').style.display='none'" style="position:absolute;top:18px;right:22px;font-size:28px;color:#fff;cursor:pointer;background:none;border:none">✕</button>
  <img id="lb-img" src="" style="max-width:92vw;max-height:80vh;border-radius:10px;object-fit:contain"/>
  <div id="lb-cap" style="font-size:11px;font-family:var(--mono);color:rgba(255,255,255,.5)"></div>
</div>

<div class="topbar">
  <button class="btn-hamburger" onclick="abrirDrawer()" aria-label="Menu">☰</button>
  <div>
    <div class="page-title"><?= e($cliente['nome']) ?></div>
    <div class="page-sub"><?= e($cliente['documento'] ?: '—') ?> · <?= e($cliente['endereco_cidade'] ?: '—') ?></div>
  </div>
  <div class="topbar-actions">
    <a href="clientes.php" class="btn btn-ghost btn-sm">← Voltar</a>
    <a href="os_form.php?cliente_id=<?= $id ?>" class="btn btn-primary btn-sm">+ OS</a>
    <a href="cliente_form.php?id=<?= $id ?>" class="btn btn-primary btn-sm">✎ Editar</a>
  </div>
</div>

<div class="content">

<?php if ($msg): ?>
  <div class="alert alert-success"><?= e($msg) ?></div>
<?php endif; ?>
<?php if (!empty($_GET['erro'])): ?>
  <div class="alert alert-danger"><?= e($_GET['erro']) ?></div>
<?php endif; ?>

<!-- Barra de status e ações -->
<div class="status-bar">
  <?php if ($cliente['bloqueado']): ?>
    <span class="badge-status badge-bloqueado">🔴 BLOQUEADO</span>
  <?php else: ?>
    <span class="badge-status badge-ativo">🟢 ATIVO</span>
  <?php endif; ?>
  
  <?php if ($osAbertas > 0): ?>
    <span class="badge-status badge-os">⚠ <?= $osAbertas ?> OS aberta<?= $osAbertas>1?'s':'' ?></span>
  <?php endif; ?>
  
  <a href="?id=<?= $id ?>&toggle_bloqueio=1&csrf=<?= csrfToken() ?>" class="btn-acao <?= $cliente['bloqueado'] ? '' : 'danger' ?>">
    <?= $cliente['bloqueado'] ? '✓ Desbloquear' : '⊘ Bloquear' ?>
  </a>
  
  <a href="cliente_form.php?id=<?= $id ?>" class="btn-acao">✎ Editar</a>
  <a href="os_form.php?cliente_id=<?= $id ?>" class="btn-acao primary">+ Nova OS</a>
  
  <?php if (usuarioLogado()['perfil'] === 'ADMIN'): ?>
  <a href="excluir_cliente.php?id=<?= $id ?>" class="btn-acao danger" onclick="return confirm('Tem certeza que deseja excluir este cliente?')">✕ Excluir</a>
  <?php endif; ?>
</div>

<div class="detalhe-grid">

  <!-- COLUNA ESQUERDA -->
  <div>

    <!-- Foto da Fachada (se houver) -->
    <?php if ($fotoFachada): ?>
    <div class="fachada-card">
      <div class="section-head"><span class="section-title">🏠 Fachada</span></div>
      <img src="<?= e($fotoFachada['caminho_arquivo']) ?>"
           onclick="lbAbrir('<?= e($fotoFachada['caminho_arquivo']) ?>','Fachada da residência')"
           onerror="this.style.display='none'"
           alt="Fachada"/>
    </div>
    <?php endif; ?>

    <!-- Dados do Cliente -->
    <div class="section-head">
      <span class="section-title">◎ Dados do Cliente</span>
    </div>
    <div class="detail-grid" style="margin-bottom:16px">
      <div class="detail-item">
        <div class="detail-label">TELEFONE</div>
        <div class="detail-val mono">
          <?php if ($cliente['telefone']): ?>
            <a href="tel:<?= e(preg_replace('/\D/','',$cliente['telefone'])) ?>" style="color:<?= e($corPrincipal) ?>"><?= e($cliente['telefone']) ?></a>
          <?php else: ?>—<?php endif; ?>
        </div>
      </div>
      <div class="detail-item">
        <div class="detail-label">E-MAIL</div>
        <div class="detail-val" style="font-size:12px"><?= e($cliente['email'] ?: '—') ?></div>
      </div>
      <div class="detail-item" style="grid-column:1/-1">
        <div class="detail-label">ENDEREÇO</div>
        <div class="detail-val" style="font-size:12px;line-height:1.6">
          <?= e($cliente['endereco_logradouro'] ?: '—') ?>
          <?php if ($cliente['endereco_numero']): ?>, <?= e($cliente['endereco_numero']) ?><?php endif; ?>
          <?php if ($cliente['endereco_complemento']): ?> — <?= e($cliente['endereco_complemento']) ?><?php endif; ?><br>
          <?php if ($cliente['endereco_bairro']): ?><?= e($cliente['endereco_bairro']) ?> · <?php endif; ?>
          <?= e($cliente['endereco_cidade'] ?: '—') ?>-SP
          <?php if ($cliente['endereco_cep']): ?> · CEP <?= e($cliente['endereco_cep']) ?><?php endif; ?>
          
          <?php if ($temGPS): ?>
            <br><span style="font-family:var(--mono);color:var(--muted);font-size:10px">📍 <?= round($cliLat, 6) ?>, <?= round($cliLng, 6) ?></span>
            <a href="https://maps.google.com/?q=<?= $cliLat ?>,<?= $cliLng ?>" target="_blank" style="color:<?= e($corPrincipal) ?>;margin-left:8px;font-size:10px;text-decoration:none;font-weight:600">◉ Maps</a>
            <a href="https://waze.com/ul?ll=<?= $cliLat ?>,<?= $cliLng ?>&navigate=yes" target="_blank" style="color:#33ccff;margin-left:6px;font-size:10px;text-decoration:none;font-weight:600">🔵 Waze</a>
          <?php else: ?>
            <br><span style="color:var(--amber);font-size:10px">⚠ Não geolocalizado</span>
            <a href="geocalizacao.php?id=<?= $id ?>" style="color:<?= e($corPrincipal) ?>;margin-left:8px;font-size:10px">+ Adicionar GPS</a>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Caixa CTO -->
    <?php if (!empty($cliente['cto_nome'])): ?>
    <div class="section-head">
      <span class="section-title">📦 Caixa: <?= e($cliente['cto_nome']) ?></span>
    </div>
    <div style="margin-bottom:18px;font-size:11px;color:var(--muted)">
      <?php if ($temCtoGps): ?>
        <span id="cto-endereco-texto">📍 Carregando endereço...</span>
        <br><span style="font-family:var(--mono);font-size:10px"><?= e($cliente['olt_gps']) ?></span>
        <a href="https://maps.google.com/?q=<?= urlencode($cliente['olt_gps']) ?>" target="_blank" style="color:<?= e($corPrincipal) ?>;margin-left:8px;font-size:10px;text-decoration:none;font-weight:600">◉ Maps</a>
        <a href="https://waze.com/ul?ll=<?= urlencode($cliente['olt_gps']) ?>&navigate=yes" target="_blank" style="color:#33ccff;margin-left:6px;font-size:10px;text-decoration:none;font-weight:600">🔵 Waze</a>
      <?php else: ?>
        ⚠ Caixa sem coordenadas GPS
      <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Mapa com rota -->
    <?php if ($temGPS): ?>
    <div class="section-head"><span class="section-title">◉ Mapa</span></div>
    <div id="mini-map-cli"></div>
    <?php endif; ?>

    <!-- Conexão -->
    <div class="section-head"><span class="section-title">⬡ Conexão</span></div>
    <div class="detail-grid" style="margin-bottom:18px">
      <div class="detail-item"><div class="detail-label">PLANO</div><div class="detail-val"><?= e($cliente['plano'] ?: '—') ?></div></div>
      <div class="detail-item"><div class="detail-label">VLAN</div><div class="detail-val mono"><?= e($cliente['vlan'] ?: '—') ?></div></div>
      <div class="detail-item"><div class="detail-label">PPPoE</div><div class="detail-val mono" style="font-size:11px"><?= e($cliente['pppoe_usuario'] ?: '—') ?> / <?= e($cliente['pppoe_senha'] ?: '—') ?></div></div>
      <div class="detail-item"><div class="detail-label">COD. CONEXÃO</div><div class="detail-val mono"><?= e($cliente['cod_conexao'] ?: '—') ?></div></div>
      <div class="detail-item" style="grid-column:1/-1">
        <div class="detail-label">WI-FI</div>
        <div class="detail-val mono" style="font-size:10px">
          2.4GHz: <?= e($cliente['wifi_ssid_2g'] ?: '—') ?> / <?= e($cliente['wifi_senha_2g'] ?: '—') ?><br>
          5GHz: <?= e($cliente['wifi_ssid_5g'] ?: '—') ?> / <?= e($cliente['wifi_senha_5g'] ?: '—') ?>
        </div>
      </div>
    </div>

    <!-- Equipamentos -->
    <div class="section-head"><span class="section-title">▣ Equipamentos</span></div>
    <div class="detail-grid" style="margin-bottom:18px">
      <div class="detail-item"><div class="detail-label">ROTEADOR</div><div class="detail-val"><?= $cliente['possui_roteador'] ? e($cliente['modelo_roteador'] ?: 'Sim') : 'Não possui' ?></div></div>
      <div class="detail-item"><div class="detail-label">SENHA EQUIP.</div><div class="detail-val mono"><?= e($cliente['password_equipamento'] ?: '—') ?></div></div>
      <div class="detail-item"><div class="detail-label">REPETIDOR</div><div class="detail-val"><?= $cliente['possui_repetidor'] ? e($cliente['modelo_repetidor'] ?: 'Sim') : 'Não possui' ?></div></div>
      <div class="detail-item"><div class="detail-label">CÂMERAS</div><div class="detail-val"><?= $cliente['possui_cameras'] ? '✓ Possui' : 'Não possui' ?></div></div>
      <?php if ($cliente['possui_cameras'] && $cliente['camera_local']): ?>
      <div class="detail-item" style="grid-column:1/-1"><div class="detail-label">LOCAL DAS CÂMERAS</div><div class="detail-val"><?= e($cliente['camera_local']) ?></div></div>
      <?php endif; ?>
    </div>

    <!-- Fotos das Câmeras -->
    <?php if ($fotosCameras): ?>
    <div style="margin-bottom:18px">
      <div class="section-head"><span class="section-title">📷 Fotos das Câmeras (<?= count($fotosCameras) ?>)</span></div>
      <div class="fotos-mini">
        <?php foreach ($fotosCameras as $f): ?>
        <img src="<?= e($f['caminho_arquivo']) ?>" class="foto-mini"
             onclick="lbAbrir('<?= e($f['caminho_arquivo']) ?>','<?= e(addslashes($f['descricao'] ?: 'Câmera')) ?>')"
             onerror="this.style.display='none'"/>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- Observações -->
    <?php if ($cliente['observacoes']): ?>
    <div style="background:rgba(0,212,255,.05);border:1px solid rgba(0,212,255,.12);border-radius:8px;padding:12px 14px;margin-bottom:18px">
      <div class="form-label" style="margin-bottom:5px">OBSERVAÇÕES</div>
      <div style="font-size:12.5px;color:var(--muted);line-height:1.6"><?= nl2br(e($cliente['observacoes'])) ?></div>
    </div>
    <?php endif; ?>

  </div>

  <!-- COLUNA DIREITA - ORDENS DE SERVIÇO -->
  <div>
    <div class="section-head">
      <span class="section-title">◈ OS (<?= count($ordens) ?>)</span>
      <a href="os_form.php?cliente_id=<?= $id ?>" class="btn btn-primary btn-sm">+ Abrir OS</a>
    </div>

    <?php if (empty($ordens)): ?>
      <div style="color:var(--muted);font-size:13px;padding:20px 0">
        Nenhuma OS para este cliente.
        <a href="os_form.php?cliente_id=<?= $id ?>" style="color:<?= e($corPrincipal) ?>;margin-left:8px">+ Abrir primeira OS</a>
      </div>
    <?php else: foreach ($ordens as $os): ?>
      <a href="os_detalhe.php?id=<?= $os['id'] ?>" class="os-row">
        <div class="os-row-header">
          <span class="os-num"><?= e($os['numero_os']) ?></span>
          <?= badgeStatus($os['status']) ?>
        </div>
        <div class="os-tipo"><?= labelTipoOS($os['tipo_os']) ?></div>
        <?php if ($os['relato_cliente']): ?>
          <div class="os-desc"><?= e(mb_strimwidth($os['relato_cliente'], 0, 90, '…')) ?></div>
        <?php endif; ?>
        <div class="os-meta">
          📅 <?= fmtData($os['data_abertura']) ?>
          <?php if ($os['agendamento']): ?>
            · 🗓 <span style="color:var(--purple)"><?= fmtData($os['agendamento']) ?></span>
          <?php endif; ?>
          <?php if ($os['data_fechamento']): ?>
            · ✓ <span style="color:var(--green)"><?= fmtData($os['data_fechamento'], false) ?></span>
          <?php endif; ?>
          <?php if ($os['tecnico_nome']): ?>
            · 👷 <?= e($os['tecnico_nome']) ?>
          <?php endif; ?>
        </div>
      </a>
    <?php endforeach; endif; ?>
  </div>

</div></div>

<?php if ($temGPS): ?>
<script>
(function() {
  const CLI_LAT  = <?= $cliLat ?>;
  const CLI_LNG  = <?= $cliLng ?>;
  const CLI_NOME = <?= $clienteNomeJs ?>;
  const CTO_LAT  = <?= $ctoLat ?>;
  const CTO_LNG  = <?= $ctoLng ?>;
  const CTO_NOME = <?= json_encode($ctoNome) ?>;
  const TEM_CTO  = <?= ($temCtoGps && $ctoLat && $ctoLng) ? 'true' : 'false' ?>;
  const COR_PRINCIPAL = '<?= e($corPrincipal) ?>';
  const COR_ACENTO    = '<?= e($corAcento) ?>';

  // Geocodificação reversa
  async function geocodeReverso(lat, lng) {
    try {
      const r = await fetch(`ajax/geocodificar.php?acao=reverse&lat=${lat}&lng=${lng}`);
      const d = await r.json();
      if (d.ok) {
        const partes = [d.logradouro, d.bairro, d.cidade].filter(Boolean);
        return partes.length ? partes.join(', ') + (d.cep ? ` — CEP ${d.cep}` : '') : null;
      }
    } catch(e) {}
    try {
      const r = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=pt-BR`, {
        headers: { 'User-Agent': 'MKTTelecom/2.6' }
      });
      const d = await r.json();
      const a = d.address || {};
      const partes = [a.road || a.pedestrian || a.path, a.suburb || a.neighbourhood, a.city || a.town || a.village].filter(Boolean);
      return partes.length ? partes.join(', ') : null;
    } catch(e) {}
    return null;
  }

  // Inicializa mapa com rota real
  async function initMap() {
    if (typeof L === 'undefined') { setTimeout(initMap, 200); return; }
    const el = document.getElementById('mini-map-cli');
    if (!el) return;

    const m = L.map(el, { zoomControl: false, attributionControl: false });
    
    // Camadas
    const darkLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png');
    const satelliteLayer = L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}');
    darkLayer.addTo(m);
    L.control.layers({'🌑 Dark': darkLayer, '🛰 Satélite': satelliteLayer}, {}, {position: 'topright'}).addTo(m);
    L.control.zoom({position: 'bottomright'}).addTo(m);

    // Ícone cliente (dentro de um box)
    const iconCli = L.divIcon({
      className: '',
      html: `<div style="width:24px;height:24px;border-radius:4px;background:${COR_PRINCIPAL}22;border:2px solid ${COR_PRINCIPAL};display:flex;align-items:center;justify-content:center;box-shadow:0 0 10px ${COR_PRINCIPAL}44;">
        <div style="width:12px;height:12px;border-radius:50%;background:${COR_PRINCIPAL};border:2px solid #fff;"></div>
      </div>`,
      iconSize: [24,24],
      iconAnchor: [12,12]
    });

    const mkrCli = L.marker([CLI_LAT, CLI_LNG], {icon: iconCli, zIndexOffset: 100}).addTo(m);
    
    // Popup do cliente com endereço
    geocodeReverso(CLI_LAT, CLI_LNG).then(end => {
      const endereco = end || `${CLI_LAT.toFixed(6)}, ${CLI_LNG.toFixed(6)}`;
      mkrCli.bindPopup(`
        <div style="min-width:180px">
          <b style="color:${COR_PRINCIPAL}">🏠 ${CLI_NOME}</b><br>
          <span style="font-size:10px;color:#888">📍 ${endereco}</span><br>
          <small style="color:#666;font-family:monospace">${CLI_LAT.toFixed(6)}, ${CLI_LNG.toFixed(6)}</small><br>
          <div style="margin-top:4px">
            <a href="https://maps.google.com/?q=${CLI_LAT},${CLI_LNG}" target="_blank" style="color:#4285F4;font-size:10px;text-decoration:none;font-weight:600">◉ Maps</a>
            <a href="https://waze.com/ul?ll=${CLI_LAT},${CLI_LNG}&navigate=yes" target="_blank" style="color:#33ccff;font-size:10px;text-decoration:none;font-weight:600;margin-left:8px">🔵 Waze</a>
          </div>
        </div>
      `);
    });

    // Endereço da CTO no texto
    if (TEM_CTO) {
      geocodeReverso(CTO_LAT, CTO_LNG).then(end => {
        const elTexto = document.getElementById('cto-endereco-texto');
        if (elTexto) {
          elTexto.textContent = end ? '📍 ' + end : `📍 ${CTO_LAT.toFixed(6)}, ${CTO_LNG.toFixed(6)}`;
        }
      });
    }

    if (TEM_CTO) {
      // Ícone caixa (dentro de um box)
      const iconCTO = L.divIcon({
        className: '',
        html: `<div style="width:24px;height:24px;border-radius:4px;background:${COR_ACENTO}22;border:2px solid ${COR_ACENTO};display:flex;align-items:center;justify-content:center;box-shadow:0 0 10px ${COR_ACENTO}44;">
          <div style="width:12px;height:12px;border-radius:2px;background:${COR_ACENTO};border:2px solid #fff;transform:rotate(45deg)"></div>
        </div>`,
        iconSize: [24,24],
        iconAnchor: [12,12]
      });

      const mkrCTO = L.marker([CTO_LAT, CTO_LNG], {icon: iconCTO, zIndexOffset: 100}).addTo(m);

      // Popup da caixa com endereço
      geocodeReverso(CTO_LAT, CTO_LNG).then(end => {
        const endereco = end || `${CTO_LAT.toFixed(6)}, ${CTO_LNG.toFixed(6)}`;
        mkrCTO.bindPopup(`
          <div style="min-width:180px">
            <b style="color:${COR_ACENTO}">📦 ${CTO_NOME}</b><br>
            <span style="font-size:10px;color:#888">📍 ${endereco}</span><br>
            <small style="color:#666;font-family:monospace">${CTO_LAT.toFixed(6)}, ${CTO_LNG.toFixed(6)}</small><br>
            <div style="margin-top:4px">
              <a href="https://maps.google.com/?q=${CTO_LAT},${CTO_LNG}" target="_blank" style="color:#4285F4;font-size:10px;text-decoration:none;font-weight:600">◉ Maps</a>
              <a href="https://waze.com/ul?ll=${CTO_LAT},${CTO_LNG}&navigate=yes" target="_blank" style="color:#33ccff;font-size:10px;text-decoration:none;font-weight:600;margin-left:8px">🔵 Waze</a>
            </div>
          </div>
        `);
      });

      // ROTA REAL usando assets/rota.js (respeita ruas e esquinas)
      const layerRef = { layers: [] };
      
      try {
        await calcularERenderRota(
          m, CLI_LAT, CLI_LNG, CTO_LAT, CTO_LNG,
          layerRef,
          {
            cor: COR_ACENTO,
            onKpis: function(r) {
              // Opcional: mostrar distância no console
              console.log('Rota:', r.distancia_km + ' km', r.duracao);
            }
          }
        );
      } catch(e) {
        // Fallback: linha reta tracejada
        L.polyline([[CLI_LAT, CLI_LNG], [CTO_LAT, CTO_LNG]], {
          color: COR_ACENTO, weight: 3, opacity: 0.6, dashArray: '8 5'
        }).addTo(m);
      }

      m.fitBounds([[CLI_LAT, CLI_LNG], [CTO_LAT, CTO_LNG]], {padding: [50, 50]});
    } else {
      m.setView([CLI_LAT, CLI_LNG], 16);
    }

    setTimeout(() => m.invalidateSize(), 300);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMap);
  } else {
    initMap();
  }
})();
</script>
<?php endif; ?>

<script>
// Lightbox para fotos
function lbAbrir(src, cap) {
  const lb = document.getElementById('lb');
  document.getElementById('lb-img').src = src;
  document.getElementById('lb-cap').textContent = cap || '';
  lb.style.display = 'flex';
  document.body.style.overflow = 'hidden';
}

document.getElementById('lb').addEventListener('click', function(e) {
  if (e.target === this) {
    this.style.display = 'none';
    document.body.style.overflow = '';
  }
});

document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape') {
    document.getElementById('lb').style.display = 'none';
    document.body.style.overflow = '';
  }
});
</script>

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