<?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 AnthonyMartin\GeoLocation\GeoLocation as GeoLocation;

$userlocation = GeoLocation::fromDegrees($VARS["latitude"], $VARS["longitude"]);

$radius = 2;
if (!empty($VARS["radius"])) {
    $radius = min(10.0, $VARS["radius"] * 1.0);
}
$searchbounds = $userlocation->boundingCoordinates($radius, "miles");

$people = $database->select("accounts", [
    "publicid",
    "name",
    "username",
    "verified",
    "latitude",
    "longitude"
        ], [
    "AND" => [
        'latitude[><]' => [$searchbounds[0]->getLatitudeInDegrees(), $searchbounds[1]->getLatitudeInDegrees()],
        'longitude[><]' => [$searchbounds[0]->getLongitudeInDegrees(), $searchbounds[1]->getLongitudeInDegrees()],
        "lastgpsfix[>]" => date("Y-m-d H:i:s", strtotime("-1 hour")),
        "type" => 2
    ],
    "LIMIT" => 100
        ]
);

$nearby = [];

if (!empty($VARS["format"]) && $VARS["format"] == "geojson") {
    $geojson = [
        "name" => "Nearby People",
        "type" => "FeatureCollection",
        "features" => []
    ];

    foreach ($people as $person) {
        $geojson["features"][] = [
            "type" => "Feature",
            "geometry" => [
                "type" => "Point",
                "coordinates" => [
                    $person["longitude"] * 1.0,
                    $person["latitude"] * 1.0
                ]
            ],
            "properties" => [
                "id" => $person["publicid"],
                "name" => utf8_encode(empty($person["name"]) ? $person["username"] : $person["name"]),
                "username" => $person["username"],
                "verified" => $person["verified"] == 1
            ]
        ];
    }

    exitWithJson($geojson);
}

foreach ($people as $person) {
    $nearby[] = [
        "name" => (empty($person["name"]) ? $person["username"] : $person["name"]),
        "username" => $person["username"],
        "verified" => $person["verified"] == 1,
        "publicid" => $person["publicid"],
        "latitude" => $person["latitude"] * 1.0,
        "longitude" => $person["longitude"] * 1.0
    ];
}

exitWithJson([
    "status" => "OK",
    "radius" => $radius,
    "bounds" => [
        0 => [
            "latitude" => $searchbounds[0]->getLatitudeInDegrees(),
            "longitude" => $searchbounds[0]->getLongitudeInDegrees()
        ],
        1 => [
            "latitude" => $searchbounds[1]->getLatitudeInDegrees(),
            "longitude" => $searchbounds[1]->getLongitudeInDegrees()
        ],
    ],
    "nearby" => $nearby
]);
