<?php
session_start();

if (!isset($_GET['lat']) || !isset($_GET['lon'])) {
    echo "NO_GPS";
    exit;
}

$lat = $_GET['lat'];
$lon = $_GET['lon'];

$url = "https://nominatim.openstreetmap.org/reverse?lat={$lat}&lon={$lon}&format=json&zoom=10&addressdetails=1";

$opts = [
    "http" => [
        "header" => "User-Agent: PHP"
    ]
];

$context = stream_context_create($opts);

$response = json_decode(file_get_contents($url, false, $context), true);

$city = $response['address']['city']
    ?? $response['address']['town']
    ?? $response['address']['village']
    ?? $response['address']['state_district']
    ?? "Unknown";

$_SESSION['gps_city'] = $city;

echo $city;
