<?php
/**
 * ajax/calcular_rota.php
 * Calcula rota entre dois pontos usando OSRM.
 *
 * Estratégia:
 *   1. Tenta OSRM via PHP (curl)
 *   2. Fallback: tenta OSRM via file_get_contents
 *   3. Fallback final: retorna linha reta (haversine) + URLs para JS tentar do navegador
 */
require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../functions.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache');

$lat1 = (float)($_GET['origem_lat']  ?? 0);
$lng1 = (float)($_GET['origem_lng']  ?? 0);
$lat2 = (float)($_GET['destino_lat'] ?? 0);
$lng2 = (float)($_GET['destino_lng'] ?? 0);

if (!$lat1 || !$lng1 || !$lat2 || !$lng2) {
    echo json_encode(['success' => false, 'erro' => 'Coordenadas inválidas']);
    exit;
}

// ── Haversine (distância em linha reta) ────────────────────────────
function haversineM(float $la1, float $lo1, float $la2, float $lo2): float {
    $R = 6371000;
    $dL = deg2rad($la2 - $la1);
    $dG = deg2rad($lo2 - $lo1);
    $a = sin($dL / 2) ** 2 + cos(deg2rad($la1)) * cos(deg2rad($la2)) * sin($dG / 2) ** 2;
    return $R * 2 * atan2(sqrt($a), sqrt(1 - $a));
}

// ── Tenta OSRM via curl ────────────────────────────────────────────
function osrmViaCurl(float $lat1, float $lng1, float $lat2, float $lng2): ?array {
    if (!function_exists('curl_init')) {
        return null;
    }

    $servidores = [
        "https://router.project-osrm.org/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
        "https://routing.openstreetmap.de/routed-car/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
    ];

    foreach ($servidores as $url) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTPHEADER     => [
                'User-Agent: MKTTelecom/2.6',
                'Accept: application/json',
            ],
        ]);
        
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err  = curl_error($ch);
        curl_close($ch);

        if ($err || $code !== 200 || !$resp) {
            continue;
        }

        $data = json_decode($resp, true);
        if (!empty($data['routes'][0])) {
            return $data['routes'][0];
        }
    }

    return null;
}

// ── Tenta OSRM via file_get_contents ───────────────────────────────
function osrmViaFileGetContents(float $lat1, float $lng1, float $lat2, float $lng2): ?array {
    $servidores = [
        "https://router.project-osrm.org/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
        "https://routing.openstreetmap.de/routed-car/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
    ];

    foreach ($servidores as $url) {
        $ctx = stream_context_create([
            'http' => [
                'method'  => 'GET',
                'header'  => "User-Agent: MKTTelecom/2.6\r\nAccept: application/json\r\n",
                'timeout' => 8,
                'ignore_errors' => true,
            ],
            'ssl' => [
                'verify_peer'      => false,
                'verify_peer_name' => false,
            ],
        ]);

        $resp = @file_get_contents($url, false, $ctx);
        if ($resp === false) {
            continue;
        }

        $data = json_decode($resp, true);
        if (!empty($data['routes'][0])) {
            return $data['routes'][0];
        }
    }

    return null;
}

// ── Extrai instruções da rota ──────────────────────────────────────
function extrairInstrucoes(array $route): array {
    $steps = [];
    
    foreach ($route['legs'][0]['steps'] ?? [] as $s) {
        $man  = $s['maneuver']['type']     ?? '';
        $mod  = $s['maneuver']['modifier'] ?? '';
        $nome = $s['name'] ?? '';
        $dist = (int)round($s['distance']);
        
        if ($dist < 5 && $man !== 'arrive') {
            continue;
        }
        
        $texto = match (true) {
            $man === 'depart'                   => "Sair" . ($nome ? " de $nome" : ""),
            $man === 'arrive'                   => "Chegou ao destino",
            $mod === 'left'                     => "Vire à esquerda" . ($nome ? " em $nome" : ""),
            $mod === 'right'                    => "Vire à direita" . ($nome ? " em $nome" : ""),
            $mod === 'slight left'              => "Levemente à esquerda",
            $mod === 'slight right'             => "Levemente à direita",
            $mod === 'sharp left'               => "Curva fechada à esquerda",
            $mod === 'sharp right'              => "Curva fechada à direita",
            $mod === 'straight' || $man === 'continue' => "Siga em frente" . ($nome ? " por $nome" : ""),
            $mod === 'uturn'                    => "Retorno",
            default                              => trim(ucfirst("$man $mod") . ($nome ? " ($nome)" : "")),
        };
        
        $steps[] = [
            'texto'     => trim($texto),
            'distancia' => $dist,
        ];
    }
    
    return $steps;
}

// ═══════════════════════════════════════════════════════════════════
//  Execução principal
// ═══════════════════════════════════════════════════════════════════

// 1ª tentativa: curl
$route = osrmViaCurl($lat1, $lng1, $lat2, $lng2);

// 2ª tentativa: file_get_contents
if (!$route) {
    $route = osrmViaFileGetContents($lat1, $lng1, $lat2, $lng2);
}

// Se conseguiu rota via PHP
if ($route) {
    $distM  = round($route['distance']);
    $distKm = round($distM / 1000, 2);
    $durMin = round($route['duration'] / 60);
    
    if ($durMin < 60) {
        $durTxt = "{$durMin} min";
    } else {
        $horas = floor($durMin / 60);
        $mins  = $durMin % 60;
        $durTxt = $mins > 0 ? "{$horas}h {$mins}min" : "{$horas}h";
    }

    $coords  = $route['geometry']['coordinates'] ?? [];
    $latlngs = array_map(fn($c) => [$c[1], $c[0]], $coords);
    $instrucoes = extrairInstrucoes($route);

    echo json_encode([
        'success'      => true,
        'fonte'        => 'osrm_php',
        'distancia_m'  => $distM,
        'distancia_km' => $distKm,
        'duracao'      => $durTxt,
        'duracao_min'  => $durMin,
        'instrucoes'   => $instrucoes,
        'latlngs'      => $latlngs,
    ]);
    exit;
}

// ═══════════════════════════════════════════════════════════════════
//  PHP sem internet → retorna haversine + URLs para JS tentar
// ═══════════════════════════════════════════════════════════════════
$distM  = haversineM($lat1, $lng1, $lat2, $lng2);
$distKm = round($distM / 1000, 2);

echo json_encode([
    'success'      => true,
    'fonte'        => 'js_osrm',
    'distancia_m'  => (int)$distM,
    'distancia_km' => $distKm,
    'duracao'      => '— (calculando...)',
    'duracao_min'  => 0,
    'instrucoes'   => [],
    'latlngs'      => [[$lat1, $lng1], [$lat2, $lng2]],
    'osrm_url'     => "https://router.project-osrm.org/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
    'osrm_url2'    => "https://routing.openstreetmap.de/routed-car/route/v1/driving/{$lng1},{$lat1};{$lng2},{$lat2}?overview=full&geometries=geojson&steps=true&alternatives=false&language=pt-BR",
]);