<?php
// mapa_roteiro.php - Mapa com roteamento real entre cliente e OLT
$pageActive = 'mapa';
$pageTitle = 'Roteiro Cliente → OLT';
require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/auth.php';
requireLogin();

$cliente_id = (int)($_GET['cliente_id'] ?? 0);
$cliente = getClienteById($cliente_id);

if (!$cliente || !$cliente['latitude'] || !$cliente['longitude']) {
    header('Location: clientes.php?erro=Cliente sem coordenadas');
    exit;
}

// Buscar OLT mais próxima (em linha reta primeiro)
$olts = getOLTs();
$oltProxima = null;
$menorDistancia = INF;

foreach ($olts as $olt) {
    if ($olt['latitude'] && $olt['longitude']) {
        $dist = haversineDistance(
            $cliente['latitude'], $cliente['longitude'],
            $olt['latitude'], $olt['longitude']
        );
        if ($dist < $menorDistancia) {
            $menorDistancia = $dist;
            $oltProxima = $olt;
        }
    }
}

function haversineDistance($lat1, $lng1, $lat2, $lng2) {
    $earthRadius = 6371;
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $a = sin($dLat/2) * sin($dLat/2) +
         cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
         sin($dLng/2) * sin($dLng/2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    return $earthRadius * $c;
}

require_once __DIR__ . '/includes/header.php';
?>

<style>
.rota-panel {
    position: absolute;
    bottom: 20px;
    left: 20px;
    right: 20px;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 16px;
    z-index: 1000;
    backdrop-filter: blur(10px);
    max-width: 400px;
}

.rota-info {
    display: flex;
    gap: 16px;
    margin-bottom: 12px;
    flex-wrap: wrap;
}

.rota-card {
    flex: 1;
    background: var(--card);
    border-radius: 12px;
    padding: 12px;
    text-align: center;
}

.rota-value {
    font-size: 24px;
    font-weight: 800;
    color: var(--cyan);
}

.rota-label {
    font-size: 10px;
    color: var(--muted);
    font-family: var(--mono);
}

.instrucoes-list {
    max-height: 200px;
    overflow-y: auto;
    margin-top: 12px;
}

.instrucao-item {
    display: flex;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid var(--border);
    font-size: 12px;
}

.instrucao-icon {
    width: 24px;
    text-align: center;
}

.loading-overlay-local {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1001;
}

#map {
    height: 100vh;
    width: 100%;
}

@media (min-width: 768px) {
    .rota-panel {
        bottom: 20px;
        left: 20px;
        right: auto;
        width: 380px;
    }
}
</style>

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

<div class="rota-panel" id="rota-panel" style="display: none;">
    <div class="rota-info">
        <div class="rota-card">
            <div class="rota-value" id="distancia-val">--</div>
            <div class="rota-label">Distância (km)</div>
        </div>
        <div class="rota-card">
            <div class="rota-value" id="duracao-val">--</div>
            <div class="rota-label">Tempo estimado</div>
        </div>
        <div class="rota-card">
            <div class="rota-value" id="linhareta-val"><?= round($menorDistancia, 2) ?></div>
            <div class="rota-label">Linha reta (km)</div>
        </div>
    </div>
    <div class="instrucoes-list" id="instrucoes-list"></div>
    <div style="margin-top: 12px; display: flex; gap: 8px;">
        <button onclick="abrirGoogleMaps()" class="btn btn-primary" style="flex:1">
            🗺️ Abrir no Google Maps
        </button>
        <button onclick="fecharPainel()" class="btn btn-ghost">Fechar</button>
    </div>
</div>

<div class="loading-overlay-local" id="loading-overlay">
    <div class="loading-spinner"></div>
</div>

<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="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.css" />

<script>
const clienteLat = <?= $cliente['latitude'] ?>;
const clienteLng = <?= $cliente['longitude'] ?>;
const clienteNome = "<?= addslashes($cliente['nome']) ?>";
const oltLat = <?= $oltProxima ? $oltProxima['latitude'] : 0 ?>;
const oltLng = <?= $oltProxima ? $oltProxima['longitude'] : 0 ?>;
const oltNome = "<?= addslashes($oltProxima ? $oltProxima['nome'] : 'Nenhuma OLT próxima') ?>";

let map;
let routingControl;

// Inicializar mapa
map = L.map('map').setView([clienteLat, clienteLng], 14);

L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OSM</a>'
}).addTo(map);

// Ícones customizados
const clienteIcon = L.divIcon({
    html: `<div style="background:#00d4ff;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 0 12px #00d4ff">
            <span style="font-size:16px">🏠</span>
           </div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
});

const oltIcon = L.divIcon({
    html: `<div style="background:#10b981;width:32px;height:32px;border-radius:8px;transform:rotate(45deg);display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 0 12px #10b981">
            <span style="transform:rotate(-45deg);font-size:16px">📡</span>
           </div>`,
    iconSize: [32, 32],
    iconAnchor: [16, 16]
});

// Adicionar marcadores
L.marker([clienteLat, clienteLng], { icon: clienteIcon })
    .addTo(map)
    .bindPopup(`<b>Cliente:</b> ${clienteNome}`)
    .openPopup();

if (oltLat && oltLng) {
    L.marker([oltLat, oltLng], { icon: oltIcon })
        .addTo(map)
        .bindPopup(`<b>OLT:</b> ${oltNome}`);
}

// Calcular rota real com Leaflet Routing Machine
if (oltLat && oltLng) {
    routingControl = L.Routing.control({
        waypoints: [
            L.latLng(clienteLat, clienteLng),
            L.latLng(oltLat, oltLng)
        ],
        routeWhileDragging: false,
        showAlternatives: false,
        lineOptions: {
            styles: [{ color: '#00d4ff', weight: 5, opacity: 0.8 }],
            addWaypoints: false
        },
        createMarker: function() { return null; }, // Não criar marcadores extras
        fitSelectedRoutes: true,
        show: false // Não mostrar painel padrão
    }).addTo(map);
    
    // Capturar eventos da rota
    routingControl.on('routesfound', function(e) {
        const routes = e.routes;
        if (routes && routes.length > 0) {
            const route = routes[0];
            const distanciaKm = (route.summary.totalDistance / 1000).toFixed(2);
            const duracaoMin = (route.summary.totalTime / 60).toFixed(1);
            
            document.getElementById('distancia-val').textContent = distanciaKm;
            document.getElementById('duracao-val').textContent = `${duracaoMin} min`;
            document.getElementById('rota-panel').style.display = 'block';
            
            // Exibir instruções
            const instrucoesList = document.getElementById('instrucoes-list');
            instrucoesList.innerHTML = '';
            
            route.instructions.forEach((inst, idx) => {
                const div = document.createElement('div');
                div.className = 'instrucao-item';
                div.innerHTML = `
                    <div class="instrucao-icon">${getInstrucaoIcon(inst.text)}</div>
                    <div style="flex:1">${inst.text}</div>
                    <div style="color:var(--cyan)">${(inst.distance / 1000).toFixed(1)} km</div>
                `;
                instrucoesList.appendChild(div);
            });
        }
        document.getElementById('loading-overlay').style.display = 'none';
    });
    
    routingControl.on('routingerror', function() {
        document.getElementById('loading-overlay').style.display = 'none';
        alert('Não foi possível calcular a rota. Verifique as coordenadas.');
    });
} else {
    document.getElementById('loading-overlay').style.display = 'none';
    document.getElementById('rota-panel').style.display = 'block';
    document.getElementById('distancia-val').textContent = 'N/A';
    document.getElementById('duracao-val').textContent = 'N/A';
    document.getElementById('instrucoes-list').innerHTML = '<div style="text-align:center;color:var(--red)">Nenhuma OLT encontrada próxima</div>';
}

function getInstrucaoIcon(texto) {
    if (texto.includes('esquerda')) return '⬅️';
    if (texto.includes('direita')) return '➡️';
    if (texto.includes('seguir')) return '⬆️';
    if (texto.includes('chegou')) return '🏁';
    return '📍';
}

function abrirGoogleMaps() {
    const url = `https://www.google.com/maps/dir/${clienteLat},${clienteLng}/${oltLat},${oltLng}`;
    window.open(url, '_blank');
}

function fecharPainel() {
    document.getElementById('rota-panel').style.display = 'none';
}

// Esconder loading após 10 segundos (fallback)
setTimeout(() => {
    document.getElementById('loading-overlay').style.display = 'none';
}, 10000);
</script>

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