<?php
// infraestrutura.php — Viabilidade Óptica / CTO / OLT
// Adaptado de infraestrutura.php (PulseNeti) para MKT Telecom
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/functions.php';
requireLogin();

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

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

if (!$c['latitude'] || !$c['longitude']) {
    header("Location: geocalizacao.php?id=$id&msg=Defina+a+geolocalização+primeiro");
    exit;
}

$enderecoFull = trim(
    ($c['endereco_logradouro'] ?? '') . ', ' .
    ($c['endereco_numero']     ?? '') . ' — ' .
    ($c['endereco_bairro']     ?? '') . ', ' .
    ($c['endereco_cidade']     ?? '')
);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>Infraestrutura — <?= e($c['nome']) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;600;700;800&family=Share+Tech+Mono&display=swap" rel="stylesheet"/>
<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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  :root {
    --bg: #060b17; --surface: #0b1526; --card: #0f1d35; --card2: #121e32;
    --border: #1a2e50; --border2: #1e3f72;
    --cyan: #00d4ff; --green: #10b981; --amber: #f59e0b; --red: #ef4444;
    --text: #dde8f5; --muted: #4a6a8a;
    --mono: 'Share Tech Mono', monospace; --ui: 'Exo 2', sans-serif;
  }
  html, body { background: var(--bg); color: var(--text); font-family: var(--ui); min-height: 100vh; }
  a { color: inherit; text-decoration: none; }

  /* ── TOPBAR ── */
  .topbar {
    background: var(--surface); border-bottom: 1px solid var(--border);
    padding: 12px 16px; display: flex; align-items: center;
    justify-content: space-between; position: sticky; top: 0; z-index: 200;
  }
  .topbar-left { display: flex; align-items: center; gap: 10px; }
  .topbar-back { width: 34px; height: 34px; border-radius: 8px; border: 1px solid var(--border); background: none; color: var(--muted); cursor: pointer; display: flex; align-items: center; justify-content: center; }
  .topbar-back:hover { border-color: var(--border2); color: var(--text); }
  .topbar-name { font-size: 14px; font-weight: 700; }
  .topbar-addr { font-size: 10px; color: var(--muted); font-family: var(--mono); }

  /* ── NAVEGAÇÃO MAPA ── */
  .nav-btns { display: flex; gap: 6px; }
  .nav-btn {
    width: 34px; height: 34px; border-radius: 8px; border: none;
    display: flex; align-items: center; justify-content: center;
    font-size: 13px; cursor: pointer; text-decoration: none;
  }
  .nav-google { background: #4285F4; color: #fff; }
  .nav-waze   { background: #33ccff; color: #000; }

  /* ── CONTEÚDO ── */
  .content { padding: 14px 16px 120px; max-width: 520px; margin: 0 auto; }

  /* ── PAGINAÇÃO OLTs ── */
  .olt-pagination {
    background: var(--card); border: 1px solid var(--border);
    border-radius: 12px; padding: 10px 12px; margin-bottom: 12px;
    display: flex; align-items: center; gap: 8px;
  }
  .olt-list { display: flex; flex: 1; gap: 6px; overflow: hidden; }
  .olt-card {
    flex: 0 0 calc(20% - 5px); min-width: 0;
    background: var(--card2); border: 1px solid var(--border);
    border-radius: 8px; padding: 7px 4px; cursor: pointer;
    text-align: center; transition: .15s; user-select: none;
  }
  .olt-card.active { border-color: var(--green); background: rgba(16,185,129,.08); }
  .olt-card:hover:not(.active) { border-color: var(--border2); }
  .olt-name { font-size: 10px; font-weight: 700; color: var(--text); display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .olt-dist { font-size: 10px; color: var(--green); font-family: var(--mono); }
  .pag-btn { background: var(--card2); border: 1px solid var(--border); border-radius: 6px; color: var(--muted); width: 28px; height: 28px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 11px; flex-shrink: 0; }
  .pag-btn:hover { border-color: var(--border2); color: var(--text); }

  /* ── PAINEL PONTO ── */
  .info-panel { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; margin-bottom: 12px; }
  .panel-row { display: flex; justify-content: space-between; align-items: flex-start; }
  .panel-label { font-size: 9px; font-family: var(--mono); color: var(--muted); letter-spacing: 1.5px; margin-bottom: 5px; }
  .panel-val { font-size: 13px; font-weight: 600; color: var(--text); }
  .panel-addr { font-size: 12px; color: var(--text); flex: 1; padding-right: 10px; }

  /* Viabilidade */
  .viability-row { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
  .viab-label { font-size: 9px; font-family: var(--mono); color: var(--muted); letter-spacing: 1px; }
  .viab-val { font-size: 24px; font-weight: 900; color: var(--green); font-family: var(--mono); }
  .viab-badge { font-size: 10px; font-family: var(--mono); }
  .viab-ok   { color: var(--green); }
  .viab-warn { color: var(--amber); }
  .viab-bad  { color: var(--red); }

  /* ── MAPA ── */
  #mapa { height: 280px; border-radius: 12px; border: 1px solid var(--border); margin-bottom: 12px; overflow: hidden; }
  .leaflet-container { background: #0a1220 !important; }

  /* ── SINAL ── */
  .sinal-section { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px; margin-bottom: 12px; }
  .sinal-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
  .sinal-box { background: var(--card2); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; }
  .sinal-box input {
    width: 100%; background: none; border: none; color: var(--cyan);
    font-family: var(--mono); font-size: 18px; font-weight: 700;
    outline: none; text-align: center; padding: 4px 0;
  }
  .sinal-box input::placeholder { color: var(--muted); font-size: 13px; }

  /* ── BTN FIXO ── */
  .btn-fixed { position: fixed; bottom: 16px; left: 0; right: 0; z-index: 300; padding: 0 16px; max-width: 520px; margin: 0 auto; }
  .btn-finalizar {
    width: 100%; background: var(--green); color: #060b17;
    border: none; border-radius: 50px; padding: 16px;
    font-family: var(--ui); font-size: 14px; font-weight: 800;
    cursor: pointer; box-shadow: 0 8px 28px rgba(16,185,129,.35);
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: .15s;
  }
  .btn-finalizar:hover { background: #12d08f; box-shadow: 0 8px 28px rgba(16,185,129,.5); }
  .btn-finalizar:active { transform: scale(.98); }
</style>
</head>
<body>

<!-- TOPBAR -->
<div class="topbar">
  <div class="topbar-left">
    <button class="topbar-back" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
    <div>
      <div class="topbar-name"><?= e($c['nome']) ?></div>
      <div class="topbar-addr"><?= e(mb_strimwidth($enderecoFull, 0, 50, '...')) ?></div>
    </div>
  </div>
  <div class="nav-btns">
    <a href="https://www.google.com/maps/dir/?api=1&destination=<?= urlencode($c['latitude'].','.$c['longitude']) ?>"
       target="_blank" class="nav-btn nav-google" title="Google Maps"><i class="fab fa-google"></i></a>
    <a href="https://waze.com/ul?ll=<?= urlencode($c['latitude'].','.$c['longitude']) ?>&navigate=yes"
       target="_blank" class="nav-btn nav-waze" title="Waze"><i class="fab fa-waze"></i></a>
  </div>
</div>

<div class="content">

  <!-- PAGINAÇÃO OLTs -->
  <div class="panel-label" style="margin-bottom:8px">CAIXAS CTO / OLTs PRÓXIMAS (ordenadas por distância)</div>
  <div class="olt-pagination">
    <button class="pag-btn" onclick="mudarPagina(-1)"><i class="fas fa-chevron-left"></i></button>
    <div class="olt-list" id="olt-list"></div>
    <button class="pag-btn" onclick="mudarPagina(1)"><i class="fas fa-chevron-right"></i></button>
  </div>

  <!-- PAINEL PONTO SELECIONADO -->
  <div class="info-panel">
    <div class="panel-row">
      <div style="flex:1">
        <div class="panel-label">LOCALIZAÇÃO APROXIMADA DO PONTO</div>
        <div class="panel-addr" id="txt-endereco" style="color:var(--muted);font-style:italic">Selecione uma CTO na lista acima...</div>
      </div>
      <div class="nav-btns" id="nav-ponto">
        <a id="link-maps-ponto" href="#" target="_blank" class="nav-btn nav-google" style="opacity:.3;pointer-events:none"><i class="fas fa-map-marker-alt"></i></a>
        <a id="link-waze-ponto" href="#" target="_blank" class="nav-btn nav-waze" style="opacity:.3;pointer-events:none"><i class="fab fa-waze"></i></a>
      </div>
    </div>
    <div class="viability-row">
      <div>
        <div class="viab-label">DISTÂNCIA VIA RUAS (OSRM)</div>
        <div class="viab-badge" id="txt-viab">—</div>
      </div>
      <div class="viab-val" id="txt-dist">—</div>
    </div>
  </div>

  <!-- MAPA -->
  <div id="mapa"></div>

  <!-- SINAL ÓPTICO -->
  <div class="sinal-section">
    <div class="panel-label">SINAL ÓPTICO (dBm)</div>
    <div class="sinal-grid">
      <div class="sinal-box">
        <div class="panel-label">NA CAIXA (BOX)</div>
        <input type="number" id="sinal-box-input" step="0.1" placeholder="-22.0" min="-40" max="0"/>
        <div style="font-size:9px;color:var(--muted);text-align:center;margin-top:2px">Ideal: ≥ -27 dBm</div>
      </div>
      <div class="sinal-box">
        <div class="panel-label">NO CLIENTE (RX)</div>
        <input type="number" id="sinal-cli-input" step="0.1" placeholder="-24.0" min="-40" max="0"/>
        <div style="font-size:9px;color:var(--muted);text-align:center;margin-top:2px">Ideal: ≥ -27 dBm</div>
      </div>
    </div>
  </div>

  <!-- FORM HIDDEN -->
  <form action="salvar_infraestrutura.php" method="POST" id="form-infra">
    <input type="hidden" name="id"        value="<?= $id ?>">
    <input type="hidden" name="cto_nome"  id="h-cto-nome">
    <input type="hidden" name="olt_gps"   id="h-olt-gps">
    <input type="hidden" name="cto_porta" id="h-cto-porta">
    <input type="hidden" name="sinal_box" id="h-sinal-box">
    <input type="hidden" name="sinal_cli" id="h-sinal-cli">
  </form>

</div><!-- /content -->

<!-- BTN FIXO -->
<div class="btn-fixed">
  <button class="btn-finalizar" onclick="finalizarConfiguracao()">
    <i class="fas fa-check-circle"></i> FINALIZAR CONFIGURAÇÃO
  </button>
</div>

<script>
const CLI_LAT = <?= (float)$c['latitude'] ?>;
const CLI_LNG = <?= (float)$c['longitude'] ?>;

// ── MAPA ──
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}');
const map = L.map('mapa', { center:[CLI_LAT,CLI_LNG], zoom:16, layers:[darkLayer] });
L.control.layers({'🌑 Dark':darkLayer,'🛰 Satélite':satelliteLayer},{},{position:'topright'}).addTo(map);
L.control.zoom({position:'bottomright'}).addTo(map);

const iconCasa = L.divIcon({className:'',
  html:`<div style="width:38px;height:38px;border-radius:50%;background:#00d4ff;border:2px solid #fff;display:flex;align-items:center;justify-content:center;box-shadow:0 0 14px #00d4ff;font-size:16px;">🏠</div>`,
  iconSize:[38,38],iconAnchor:[19,19]});
const iconCTO = L.divIcon({className:'',
  html:`<div style="width:38px;height:38px;border-radius:50%;background:#10b981;border:2px solid #fff;display:flex;align-items:center;justify-content:center;box-shadow:0 0 14px #10b981;font-size:16px;">📦</div>`,
  iconSize:[38,38],iconAnchor:[19,19]});

L.marker([CLI_LAT,CLI_LNG],{icon:iconCasa}).addTo(map)
  .bindPopup(`<b><?= e($c['nome']) ?></b><br>Cliente`);

let pontos=[], pageIdx=0, markerCTO=null, routeLine=null;

// ── CARREGA KML ──
fetch('projeto_rede.kml?v='+Date.now())
  .then(r => { if(!r.ok) throw new Error('KML não encontrado'); return r.text(); })
  .then(txt => {
    const xml = new DOMParser().parseFromString(txt, 'text/xml');
    xml.querySelectorAll('Placemark').forEach(p => {
      const nome = p.querySelector('name')?.textContent?.trim() || 'Ponto';
      const raw  = p.querySelector('coordinates')?.textContent?.trim().split(',');
      if (!raw || raw.length < 2) return;
      const lng = parseFloat(raw[0]), lat = parseFloat(raw[1]);
      if (isNaN(lat) || isNaN(lng)) return;
      const d = haversine(CLI_LAT, CLI_LNG, lat, lng);
      pontos.push({ nome, lat, lng, dist: d });
    });
    pontos.sort((a,b) => a.dist - b.dist);
    renderPagina();
  })
  .catch(err => {
    document.getElementById('olt-list').innerHTML =
      `<div style="color:var(--red);font-size:11px;padding:6px">⚠ ${err.message}. Faça o upload em Configurar Projeto.</div>`;
  });

function renderPagina() {
  const list  = document.getElementById('olt-list');
  const slice = pontos.slice(pageIdx, pageIdx + 5);
  list.innerHTML = '';
  slice.forEach((p,i) => {
    const card = document.createElement('div');
    card.className = 'olt-card';
    card.innerHTML = `<span class="olt-name">${p.nome}</span><span class="olt-dist">${fmt(p.dist)}</span>`;
    card.onclick = () => selecionarCTO(p, card);
    list.appendChild(card);
  });
}

async function selecionarCTO(p, el) {
  document.querySelectorAll('.olt-card').forEach(c => c.classList.remove('active'));
  el.classList.add('active');

  // Campos ocultos
  document.getElementById('h-cto-nome').value = p.nome;
  document.getElementById('h-olt-gps').value  = p.lat + ',' + p.lng;

  // Links de navegação
  const lm = document.getElementById('link-maps-ponto');
  const lw = document.getElementById('link-waze-ponto');
  lm.href = `https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}`;
  lw.href = `https://waze.com/ul?ll=${p.lat},${p.lng}&navigate=yes`;
  lm.style.opacity='1'; lm.style.pointerEvents='';
  lw.style.opacity='1'; lw.style.pointerEvents='';

  // ── Endereço reverso da CTO via proxy PHP (evita bloqueio CORS/Android) ──
  const elEnd = document.getElementById('txt-endereco');
  elEnd.textContent = 'Buscando localização aproximada...';
  elEnd.style.color = 'var(--muted)';
  elEnd.style.fontStyle = 'italic';

  fetch(`ajax/geocodificar.php?acao=reverse&lat=${p.lat}&lng=${p.lng}`)
    .then(r => r.json())
    .then(d => {
      elEnd.style.fontStyle = '';
      if (d.ok) {
        // Monta endereço completo com as partes disponíveis
        const partes = [d.logradouro, d.bairro, d.cidade].filter(Boolean);
        const cep    = d.cep ? ` — CEP ${d.cep}` : '';
        elEnd.textContent = partes.length
          ? partes.join(', ') + cep
          : `${p.lat.toFixed(6)}, ${p.lng.toFixed(6)}`;
        elEnd.style.color = 'var(--text)';
      } else {
        // Fallback: mostra coordenadas + tenta Nominatim direto
        _nominatimFallback(p.lat, p.lng, elEnd);
      }
    })
    .catch(() => _nominatimFallback(p.lat, p.lng, elEnd));

  // Marcador CTO
  if (markerCTO) map.removeLayer(markerCTO);
  markerCTO = L.marker([p.lat, p.lng], {icon: iconCTO}).addTo(map)
               .bindPopup(`<b>${p.nome}</b><br>CTO`).openPopup();

  // Loading
  const distEl = document.getElementById('txt-dist');
  const viab   = document.getElementById('txt-viab');
  distEl.textContent = '...';
  distEl.style.color = 'var(--muted)';
  viab.textContent   = 'Calculando rota pelas ruas...';
  viab.className     = 'viab-badge';
  viab.style.color   = 'var(--muted)';

  // ── Rota com rota.js (PHP → JS → fallback) ──────────────────────
  const layerRef = { layers: routeLine ? (Array.isArray(routeLine) ? routeLine : [routeLine]) : [] };
  layerRef.layers.forEach(l => { try{ map.removeLayer(l); }catch(e){} });
  layerRef.layers = [];

  const resultado = await calcularERenderRota(
    map, CLI_LAT, CLI_LNG, p.lat, p.lng,
    layerRef,
    {
      cor: '#10b981',
      onKpis: (r) => {
        const isDash = r.fonte === 'haversine';
        distEl.textContent = r.distancia_km + ' km' + (isDash ? ' ≈' : '');
        distEl.style.color = isDash ? 'var(--amber)' : 'var(--green)';
        atualizarViabilidade(r.distancia_m, isDash);
      }
    }
  );
  routeLine = layerRef.layers;
}

// Fallback: tenta Nominatim direto se proxy falhar
function _nominatimFallback(lat, lng, el) {
  fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=pt-BR`)
    .then(r => r.json())
    .then(d => {
      const addr = d.address || {};
      const partes = [
        addr.road || addr.pedestrian || addr.path,
        addr.suburb || addr.neighbourhood || addr.city_district,
        addr.city || addr.town || addr.village
      ].filter(Boolean);
      const cep = addr.postcode ? ` — CEP ${addr.postcode.replace(/\D/g,'')}` : '';
      el.textContent = partes.length
        ? '📍 ' + partes.join(', ') + cep
        : `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
      el.style.color = 'var(--text)';
      el.style.fontStyle = '';
    })
    .catch(() => {
      el.textContent = `📍 ${lat.toFixed(5)}, ${lng.toFixed(5)} (localização aproximada)`;
      el.style.color = 'var(--muted)';
      el.style.fontStyle = '';
    });
}

function mudarPagina(dir) {
  pageIdx = Math.max(0, Math.min(pageIdx + dir*5, Math.max(0, pontos.length - 5)));
  renderPagina();
}

function finalizarConfiguracao() {
  const cto = document.getElementById('h-cto-nome').value;
  if (!cto) { alert('Selecione uma CTO antes de finalizar.'); return; }

  // Copia sinais para campos hidden
  document.getElementById('h-sinal-box').value = document.getElementById('sinal-box-input').value;
  document.getElementById('h-sinal-cli').value = document.getElementById('sinal-cli-input').value;

  document.getElementById('form-infra').submit();
}

// ── Haversine ──
function haversine(lat1,lon1,lat2,lon2) {
  const R=6371e3, d2r=Math.PI/180;
  const dLat=(lat2-lat1)*d2r, dLon=(lon2-lon1)*d2r;
  const a=Math.sin(dLat/2)**2+Math.cos(lat1*d2r)*Math.cos(lat2*d2r)*Math.sin(dLon/2)**2;
  return R*2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));
}
function fmt(m) { return m>=1000 ? (m/1000).toFixed(2)+'km' : Math.round(m)+'m'; }

// ── Viabilidade ──
function atualizarViabilidade(distM, isFallback = false) {
  const viab   = document.getElementById('txt-viab');
  const distEl = document.getElementById('txt-dist');

  let label, cls, cor;
  if (distM <= 800) {
    label = '✓ VIÁVEL';       cls = 'viab-badge viab-ok';   cor = 'var(--green)';
  } else if (distM <= 1500) {
    label = '⚠ VERIFICAR';   cls = 'viab-badge viab-warn'; cor = 'var(--amber)';
  } else {
    label = '✕ INVIÁVEL';    cls = 'viab-badge viab-bad';  cor = 'var(--red)';
  }

  if (isFallback) label += ' (est.)';
  viab.textContent = label;
  viab.className   = cls;
  distEl.style.color = cor;
}
</script>
</body>
</html>

