<?php
/**
 * API: Geocode a city name and calculate road distance from Office.
 * Source: Grevenon 56, Ano Liosia (38.0827, 23.6918)
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
$pdo = crm_pdo();

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

$city = trim((string)($_GET['city'] ?? ''));
if ($city === '') {
    echo json_encode(['ok' => false, 'error' => 'Missing city']); exit;
}

// Office Coords (Ano Liosia)
$officeLat = 38.082717;
$officeLng = 23.691761;

$result = [
    'ok' => false,
    'city' => $city,
    'lat' => null,
    'lng' => null,
    'distance_km' => null
];

// 1. Geocode via Nominatim (Free, but be respectful)
$geoUrl = "https://nominatim.openstreetmap.org/search?q=" . urlencode($city . ", Greece") . "&format=json&limit=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $geoUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'GoPoolsCRM/1.0 (contact: info@gopools.gr)');
curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$geoRes = curl_exec($ch);
curl_close($ch);

if ($geoRes) {
    $geoData = json_decode($geoRes, true);
    if (!empty($geoData[0])) {
        $result['lat'] = (float)$geoData[0]['lat'];
        $result['lng'] = (float)$geoData[0]['lon'];
    }
}

if ($result['lat'] && $result['lng']) {
    // 2. Distance via OSRM (Driving distance)
    $osrmUrl = "http://router.project-osrm.org/route/v1/driving/{$officeLng},{$officeLat};{$result['lng']},{$result['lat']}?overview=false";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $osrmUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $osrmRes = curl_exec($ch);
    curl_close($ch);

    if ($osrmRes) {
        $osrmData = json_decode($osrmRes, true);
        if (!empty($osrmData['routes'][0]['distance'])) {
            // Distance is in meters, convert to KM
            $result['distance_km'] = round($osrmData['routes'][0]['distance'] / 1000, 1);
            $result['ok'] = true;
        }
    }
}

// Fallback: If OSRM fails but we have coords, use Haversine (Straight line)
if (!$result['ok'] && $result['lat'] && $result['lng']) {
    $theta = $officeLng - $result['lng'];
    $dist = sin(deg2rad($officeLat)) * sin(deg2rad($result['lat'])) +  cos(deg2rad($officeLat)) * cos(deg2rad($result['lat'])) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $result['distance_km'] = round($miles * 1.609344, 1);
    $result['ok'] = true;
    $result['note'] = 'Straight-line fallback';
}

if (!$result['ok']) {
    $result['error'] = 'Could not calculate distance for this location';
}

echo json_encode($result);
