<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

use OpenLocationCode\OpenLocationCode;

$output = [];

$lat = round($VARS["latitude"], 5);
$lon = round($VARS["longitude"], 5);

$cacheresp = $memcache->get("gis.geocode.reverse.$lat,$lon");
if ($cacheresp !== false) {
    exitWithJson(json_decode($cacheresp, true));
}

$json = file_get_contents("http://www.mapquestapi.com/geocoding/v1/reverse?outFormat=json&thumbMaps=false&location=$lat,$lon&key=" . env("mapquest_key", ""));

$geocode = json_decode($json, TRUE);

$location = $geocode['results'][0]['locations'][0];

$output = [
    "status" => "OK",
    "address" => [
        "street" => $location['street'],
        "city" => $location['adminArea5'],
        "county" => $location['adminArea4'],
        "state" => $location['adminArea3'],
        "country" => $location['adminArea1'],
        "postalCode" => $location['postalCode']
    ],
    "pluscode" => OpenLocationCode::encode($lat, $lon),
    "fixphrase" => FixPhrase::encode($lat, $lon),
    "coords" => [
        $lat,
        $lon
    ],
];

$memcache->set("gis.geocode.reverse.$lat,$lon", json_encode($output));
exitWithJson($output);
