<?php
# Debug
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require "vendor/autoload.php";

if (isset($_GET["address"])) {
    $address = filter_var($_GET["address"], FILTER_SANITIZE_STRING);
    $address = base64_decode($address);
    $address = ucwords(trim($address));

    # Nominatim Usage Policy
    # https://operations.osmfoundation.org/policies/nominatim/
    # sleep(1);

    # OpenStreetMap Nominatim API
    $url = 'https://nominatim.openstreetmap.org/search?q=' . urlencode($address) . '&limit=1&format=json';
    $ch = curl_init();
    # Set cURL User Agent
    curl_setopt($ch, CURLOPT_USERAGENT, "PostmanRuntime/7.28.4");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    curl_close($ch);

    # Response
    $a = json_decode($response, true);
    $valid = false;
    foreach ($a as $array) {
        foreach ($array as $k => $v) {
            switch ("$k") {
                case "lat":
                    echo "<div class='alert alert-primary' role='alert'>";
                    echo "<b>Latitude</b>: " . round($v, 8) . "<br>";
                    $valid = true;
                    break;
                case "lon":
                    echo "<b>Longitude</b>: " . round($v, 8);
                    echo "</div>";
                    $valid = true;
                    break;
            }
        }
    }
    if ($valid === false) {
        echo "<div class='alert alert-danger' role='alert'>";
        echo "Something goes wrong!";
        echo "</div>";
    }
} else {
    $favicon = <<<EOL
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAABmJLR0QA/wD/AP+gvaeTAAANhUlEQVR4nO3dW6xeRRnG8f+mF
FosIgZoKRQJBloLCJWgEDmUkEYIAkYFFCJGIRATD/FCxXjDJYYLI3hDQI2iQCLxhFEixoYKiNBiRBNoEYGUFlrUFii0lNbtxXwbetjHb6/5nnlnnl/yJlyU
zMxa8+5v1rvWmjWERbQ/cBywsBeLgXnAwb04aIz/b3MvNgEvAE8Aq4EngaeAN7L22jo3pO6ATcoi4BxgKXAKcDQwo+M2dgLPAKuA5b1Y03EbZk04FLgK+Am
wDhg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RVxAtfLCdwAJ3C9nMBmgc3n7Wv
geeK+mFkf1uMCVtX2VXfAslpF+gW2SjmB6+YErpwTuG5O4MrNUHfAstpCug7eou6I5fF/vHbSxLeHmIAAAAAASUVORK5CYII=
EOL;

    // Smarty
    $smarty = new Smarty();
    $smarty->setTemplateDir("./smarty/template");
    $smarty->setCompileDir("./smarty/compile");

    $smarty->assign("title", "OSM Locator");
    $smarty->assign("favicon", $favicon);

    $smarty->display("locator.tpl");
}
