<?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
[encoded data, 4658 characters]
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");
}
