<?php

require_once __DIR__ . "/FixPhrase.lib.php";

/**
 * Build and send a simple JSON response.
 * @param string $msg A message
 * @param string $status "OK" or "ERROR"
 * @param array $data More JSON data
 */
function sendJsonResp(string $msg = null, string $status = "OK", array $data = null) {
    $resp = [];
    if (!is_null($data)) {
        $resp = $data;
    }
    if (!is_null($msg)) {
        $resp["msg"] = $msg;
    }
    $resp["status"] = $status;
    header("Content-Type: application/json");
    exit(json_encode($resp));
}

function exitWithJson(array $json) {
    header("Content-Type: application/json");
    exit(json_encode($json));
}

$output = [];

try {
    if (!empty($_GET["words"])) {
        // convert words to coordinates
        $words = urldecode($_GET["words"]);
        $words = trim(strtolower($words));
        $words = preg_replace('/\s+/', ' ', $words);
        $coords = FixPhrase::decode($words);

        $output = [
            "status" => "OK",
            "action" => "decodeFromWords",
            "words" => $words,
            "coords" => $coords
        ];
    } else if (!empty($_GET["latitude"]) && !empty($_GET["longitude"])) {
        // convert coordinates to words
        $lat = round($_GET["latitude"], 4);
        $lon = round($_GET["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");
}

exitWithJson($output);
