<?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 Geocoder\Query\GeocodeQuery;

$address = urldecode($VARS["address"]);
$origaddress = $address;

$cacheresp = $memcache->get("gis.geocode." . sha1($origaddress));
if ($cacheresp !== false && empty($VARS["nocache"])) {
    exitWithJson(json_decode($cacheresp, true));
}

$geocoder = new \Geocoder\ProviderAggregator();
$adapter = new \Http\Adapter\Guzzle7\Client();

$chain = new \Geocoder\Provider\Chain\Chain([
    new \Geocoder\Provider\Mapbox\Mapbox($adapter, env("mapbox_key")),
    new \Geocoder\Provider\MapQuest\MapQuest($adapter, env("mapquest_key"))
        ]);

$geocoder->registerProvider($chain);

$query = GeocodeQuery::create($address)->withLimit(1);

if (isset($VARS["country"]) && preg_match("/^[A-Z]{2}$/", $VARS["country"])) {
    $query = $query->withData("country", $VARS["country"]);
}


$results = $geocoder->geocodeQuery($query);

if ($results->count() > 0) {
    $result = $results->first();
} else {
    $output = [
        "status" => "ERROR",
        "message" => "Address not found.",
        "address" => [
            "original" => $origaddress,
            "street" => "",
            "postalCode" => ""
        ],
        "coords" => [
            0,
            0
        ],
        "accuracy" => [
            "ok" => false
        ],
        "provider" => ""
    ];
    goto cacheout;
}

$geolatitude = $result->getCoordinates()->getLatitude();
$geolongitude = $result->getCoordinates()->getLongitude();

$accurate = !empty($result->getStreetNumber());

if ($accurate) {
    $address = implode(" ", [$result->getStreetNumber(), $result->getStreetName()]);
} else {
    $address = $result->getStreetName();
}

$output = [
    "status" => "OK",
    "address" => [
        "original" => $origaddress,
        "street" => ucwords(strtolower(StreetNormalizer::normalizeAddress($address))),
        "postalCode" => $result->getPostalCode()
    ],
    "coords" => [
        $geolatitude,
        $geolongitude
    ],
    "accuracy" => [
        "ok" => $accurate
    ],
    "provider" => $result->getProvidedBy()
];

cacheout:
$memcache->set("gis.geocode." . sha1($origaddress), json_encode($output));
exitWithJson($output);
