<?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/.
 */


$output = [];

try {
    if (!empty($VARS["words"])) {
        // convert words to coordinates
        $words = urldecode($VARS["words"]);
        $coords = FixPhrase::decode($words);

        $output = [
            "status" => "OK",
            "action" => "decodeFromWords",
            "words" => $words,
            "coords" => $coords
        ];
    } else if (!empty($VARS["latitude"]) && !empty($VARS["longitude"])) {
        // convert coordinates to words
        $lat = round($VARS["latitude"], 4);
        $lon = round($VARS["longitude"], 4);

        $words = FixPhrase::encode($lat, $lon);
        $output = [
            "status" => "OK",
            "action" => "encodeToWords",
            "words" => $words,
            "coords" => [
                $lat,
                $lon
            ]
        ];
    } else {
        throw new Exception("Must supply either a string of words or a latitude/longitude pair.");
    }
} catch (Exception $ex) {
    sendJsonResp($ex->getMessage(), "ERROR");
    \Sentry\captureException($ex);
}

exitWithJson($output);
