<?php
// geocalizacao.php — Geolocalização GPS ou por endereço
// Adaptado de geocalizacao.php (PulseNeti) para o sistema MKT Telecom
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/functions.php';
requireLogin();

$id   = (int)($_GET['id']   ?? 0);
$mode = trim($_GET['mode']  ?? 'address'); // 'live' = GPS real-time | 'address' = Nominatim

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

$c = getClienteById($id);
if (!$c) { header('Location: clientes.php'); 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>Geolocalização — <?= e($c['nome']) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@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>
<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:rgba(10,18,34,.95); --border:#1e3356;
    --cyan:#00d4ff; --green:#10b981; --red:#ef4444; --amber:#f59e0b;
    --text:#dde8f5; --muted:#4a6a8a; --mono:'Share Tech Mono',monospace; --ui:'Exo 2',sans-serif;
  }
  html,body { width:100%; height:100%; background:var(--bg); color:var(--text); font-family:var(--ui); overflow:hidden; }
  #map { position:absolute; inset:0; z-index:0; }
  .leaflet-container { background:#0a1220 !important; }

  /* ── PAINEL SUPERIOR (nome + modo) ── */
  .top-bar {
    position:absolute; top:16px; left:50%; transform:translateX(-50%);
    z-index:1000; width:92%; max-width:460px;
    background:var(--surface); border:1px solid var(--border);
    border-radius:14px; padding:14px 18px;
    backdrop-filter:blur(14px);
    display:flex; align-items:center; justify-content:space-between; gap:10px;
  }
  .top-bar-name { font-size:14px; font-weight:700; color:var(--text); }
  .top-bar-addr { font-size:11px; color:var(--muted); font-family:var(--mono); margin-top:2px; }
  .mode-toggle { display:flex; gap:6px; flex-shrink:0; }
  .mode-btn {
    padding:6px 11px; border-radius:8px; border:1px solid var(--border);
    background:transparent; color:var(--muted); font-family:var(--ui);
    font-size:10px; font-weight:700; cursor:pointer; transition:.15s;
  }
  .mode-btn.active { background:var(--cyan); color:#060b17; border-color:var(--cyan); }

  /* ── STATUS ── */
  .status-pill {
    position:absolute; top:90px; left:50%; transform:translateX(-50%);
    z-index:1000; background:var(--surface); border:1px solid var(--border);
    border-radius:20px; padding:6px 16px;
    font-family:var(--mono); font-size:10px; color:var(--green);
    display:flex; align-items:center; gap:7px;
    backdrop-filter:blur(10px); transition:.3s;
  }
  .status-dot { width:7px; height:7px; border-radius:50%; background:currentColor;
    box-shadow:0 0 8px currentColor; animation:blink 1.6s infinite; }
  @keyframes blink { 0%,100%{opacity:1} 50%{opacity:.2} }

  /* ── PAINEL INFERIOR ── */
  .bottom-panel {
    position:absolute; bottom:0; left:0; right:0; z-index:1000;
    background:var(--surface); border-top:1px solid var(--border);
    padding:18px 20px 28px; backdrop-filter:blur(18px);
  }
  .coord-display {
    display:flex; gap:10px; margin-bottom:14px;
  }
  .coord-box {
    flex:1; background:rgba(0,0,0,.4); border:1px solid var(--border);
    border-radius:8px; padding:8px 12px;
  }
  .coord-label { font-size:9px; font-family:var(--mono); color:var(--muted); letter-spacing:1px; margin-bottom:3px; }
  .coord-val { font-size:13px; font-weight:700; font-family:var(--mono); color:var(--cyan); }

  .btn-actions { display:flex; gap:8px; }
  .btn-cancel {
    width:46px; flex-shrink:0; background:rgba(239,68,68,.1);
    border:1px solid rgba(239,68,68,.3); border-radius:10px;
    color:var(--red); font-size:16px; cursor:pointer; transition:.15s;
    display:flex; align-items:center; justify-content:center;
  }
  .btn-cancel:hover { background:rgba(239,68,68,.2); }
  .btn-save {
    flex:1; background:var(--cyan); color:#060b17;
    border:none; border-radius:10px; padding:14px;
    font-family:var(--ui); font-size:14px; font-weight:800;
    cursor:pointer; transition:.15s;
    display:flex; align-items:center; justify-content:center; gap:8px;
  }
  .btn-save:hover { background:#22dcff; box-shadow:0 0 20px rgba(0,212,255,.4); }
  .btn-save:active { transform:scale(.98); }

  /* ── CROSSHAIR CENTRAL ── */
  .crosshair {
    position:absolute; top:50%; left:50%;
    transform:translate(-50%, -60%);
    z-index:500; pointer-events:none;
    width:40px; height:40px;
  }
  .crosshair::before, .crosshair::after {
    content:''; position:absolute; background:var(--cyan);
    opacity:.8;
  }
  .crosshair::before { width:2px; height:100%; left:50%; transform:translateX(-50%); }
  .crosshair::after  { height:2px; width:100%; top:50%;  transform:translateY(-50%); }
  .crosshair-dot {
    position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);
    width:8px; height:8px; border-radius:50%; background:var(--cyan);
    box-shadow:0 0 12px var(--cyan);
  }
</style>
</head>
<body>

<div id="map"></div>

<!-- Crosshair para modo arrasto -->
<div class="crosshair" id="crosshair" style="display:none">
  <div class="crosshair-dot"></div>
</div>

<!-- PAINEL SUPERIOR -->
<div class="top-bar">
  <div style="min-width:0">
    <div class="top-bar-name"><?= e($c['nome']) ?></div>
    <div class="top-bar-addr"><?= e(mb_strimwidth($enderecoFull, 0, 55, '...')) ?></div>
  </div>
  <div class="mode-toggle">
    <button class="mode-btn <?= $mode==='address'?'active':'' ?>"
            onclick="location.href='?id=<?= $id ?>&mode=address'">📍 ENDEREÇO</button>
    <button class="mode-btn <?= $mode==='live'?'active':'' ?>"
            onclick="location.href='?id=<?= $id ?>&mode=live'">🛰 GPS</button>
  </div>
</div>

<!-- STATUS -->
<div class="status-pill" id="status-pill">
  <span class="status-dot"></span>
  <span id="status-text">Inicializando...</span>
</div>

<!-- PAINEL INFERIOR -->
<div class="bottom-panel">
  <div class="coord-display">
    <div class="coord-box">
      <div class="coord-label">LATITUDE</div>
      <div class="coord-val" id="disp-lat"><?= $c['latitude'] ?: '—' ?></div>
    </div>
    <div class="coord-box">
      <div class="coord-label">LONGITUDE</div>
      <div class="coord-val" id="disp-lng"><?= $c['longitude'] ?: '—' ?></div>
    </div>
  </div>
  <form action="salvar_geocalizacao.php" method="POST" id="form-geo">
    <input type="hidden" name="id"        value="<?= $id ?>">
    <input type="hidden" name="latitude"  id="lat-input" value="<?= e($c['latitude'] ?? '') ?>">
    <input type="hidden" name="longitude" id="lng-input" value="<?= e($c['longitude'] ?? '') ?>">
    <div class="btn-actions">
      <button type="button" class="btn-cancel" onclick="history.back()" title="Cancelar">
        <i class="fas fa-times"></i>
      </button>
      <button type="submit" class="btn-save" id="btn-salvar">
        <i class="fas fa-check-circle"></i> SALVAR POSIÇÃO
      </button>
    </div>
  </form>
</div>

<script>
const INIT_LAT  = <?= $c['latitude']  ? (float)$c['latitude']  : -20.2681 ?>;
const INIT_LNG  = <?= $c['longitude'] ? (float)$c['longitude'] : -50.5458 ?>;
const MODE      = '<?= $mode ?>';
const ADDR_FULL = '<?= addslashes($enderecoFull) ?>';

// ── MAPA ──
const map = L.map('map', { zoomControl: false, attributionControl: false })
              .setView([INIT_LAT, INIT_LNG], 18);

L.tileLayer('https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}', {
  maxZoom: 21
}).addTo(map);

L.control.zoom({ position: 'topright' }).addTo(map);

// Ícone personalizado
const iconPin = L.divIcon({
  className: '',
  html: `<div style="
    width:44px;height:44px;border-radius:50%;
    background:var(--cyan,#00d4ff);
    border:3px solid #fff;
    display:flex;align-items:center;justify-content:center;
    box-shadow:0 0 22px rgba(0,212,255,.7);
    font-size:18px;color:#040e1c;
  ">📍</div>`,
  iconSize: [44, 44],
  iconAnchor: [22, 22],
});

let marker = L.marker([INIT_LAT, INIT_LNG], { draggable: true, icon: iconPin }).addTo(map);

function setStatus(msg, color) {
  const pill = document.getElementById('status-pill');
  const txt  = document.getElementById('status-text');
  txt.textContent = msg;
  pill.style.color = color || '#10b981';
  const dot = pill.querySelector('.status-dot');
  if (dot) dot.style.background = color || '#10b981';
}

function atualizarCoordenadas(lat, lng) {
  const la = parseFloat(lat).toFixed(6);
  const ln = parseFloat(lng).toFixed(6);
  document.getElementById('lat-input').value = la;
  document.getElementById('lng-input').value = ln;
  document.getElementById('disp-lat').textContent = la;
  document.getElementById('disp-lng').textContent = ln;
  marker.setLatLng([parseFloat(la), parseFloat(ln)]);
  map.flyTo([parseFloat(la), parseFloat(ln)], 19, { duration: 1.2 });
}

// ── MODO GPS REAL-TIME ──
if (MODE === 'live') {
  setStatus('GPS REAL-TIME ATIVADO', '#00d4ff');
  if ('geolocation' in navigator) {
    navigator.geolocation.watchPosition(
      pos => {
        atualizarCoordenadas(pos.coords.latitude, pos.coords.longitude);
        setStatus(`GPS: ±${Math.round(pos.coords.accuracy)}m`, '#10b981');
      },
      err => setStatus('Erro GPS: ' + err.message, '#ef4444'),
      { enableHighAccuracy: true, maximumAge: 3000 }
    );
  } else {
    setStatus('GPS não disponível neste dispositivo', '#f59e0b');
  }
}

// ── MODO ENDEREÇO (Nominatim) ──
if (MODE === 'address') {
  if (INIT_LAT !== -20.2681 || INIT_LNG !== -50.5458) {
    setStatus('Coordenadas já registradas — arraste o pin para ajustar', '#f59e0b');
  } else {
    setStatus('Buscando endereço...', '#f59e0b');
    fetch('https://nominatim.openstreetmap.org/search?format=json&limit=1&countrycodes=br&q=' +
          encodeURIComponent(ADDR_FULL), {
      headers: { 'Accept-Language': 'pt-BR', 'User-Agent': 'MKTTelecom/2.6' }
    })
    .then(r => r.json())
    .then(data => {
      if (data && data.length > 0) {
        atualizarCoordenadas(data[0].lat, data[0].lon);
        setStatus('Endereço localizado — ajuste se necessário', '#10b981');
      } else {
        setStatus('Endereço não encontrado — posicione manualmente', '#ef4444');
      }
    })
    .catch(() => setStatus('Erro na busca — posicione manualmente', '#ef4444'));
  }
}

// ── ARRASTAR MARKER ──
marker.on('dragend', function() {
  const p = marker.getLatLng();
  atualizarCoordenadas(p.lat, p.lng);
  setStatus('Ajuste manual — confirme a posição', '#f59e0b');
});

// ── CLIQUE NO MAPA (modo endereço) ──
if (MODE === 'address') {
  map.on('click', function(e) {
    atualizarCoordenadas(e.latlng.lat, e.latlng.lng);
    setStatus('Posição definida por clique', '#f59e0b');
  });
}

// ── VALIDAÇÃO ANTES DE SALVAR ──
document.getElementById('form-geo').addEventListener('submit', function(e) {
  const lat = document.getElementById('lat-input').value;
  const lng = document.getElementById('lng-input').value;
  if (!lat || lat === '0' || !lng || lng === '0') {
    e.preventDefault();
    setStatus('Defina uma posição antes de salvar!', '#ef4444');
    return;
  }
  const btn = document.getElementById('btn-salvar');
  btn.disabled = true;
  btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> SALVANDO...';
});
</script>
</body>
</html>
