<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
session_start();
ob_start();
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    die();
}
require_once("../../db/connection.php");
require_once("../../backend/functions.php");
$settings = get_settings();
if(!empty($settings['timezone'])) {
    date_default_timezone_set($settings['timezone']);
}
$id = strip_tags($_POST['id']);
$id_map = (int)$_POST['id_map'];
$timeout = (int)$_POST['timeout']*1000;
$hash = strip_tags($_POST['hash']);
$live_tracking_only_admin = false;
if(isset($_SESSION['live_tracking_only_admin'])) {
    $live_tracking_only_admin = $_SESSION['live_tracking_only_admin'];
} else {
    $query = "SELECT live_tracking_only_admin FROM sml_maps WHERE id=$id_map LIMIT 1;";
    $result = $mysqli->query($query);
    if($result->num_rows === 1){
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $live_tracking_only_admin = $row['live_tracking_only_admin'];
        $_SESSION['live_tracking_only_admin'] = $live_tracking_only_admin;
    }
}
if($live_tracking_only_admin) {
    if (md5(1 . 'smladmin') !== $hash) {
        ob_end_clean();
        echo json_encode(array("status" => "ok", "positions" => []));
        exit;
    }
}
session_write_close();
$now = date('Y-m-d H:i:s');
$query = "SELECT id, lat, lon, name, color FROM sml_live_tracking WHERE id_map=? AND id!=? AND updated_at >= ? - INTERVAL ? MICROSECOND;";
if ($smt = $mysqli->prepare($query)) {
    $smt->bind_param('issi', $id_map,$id,$now,$timeout);
    $smt->execute();
    $result = get_result($smt);
    $positions = array();
    if(count($result)>0) {
        while($row = array_shift($result)) {
            $positions[] = $row;
        }
    }
    $smt->close();
    ob_end_clean();
    echo json_encode(array("status" => "ok", "positions" => $positions));
} else {
    ob_end_clean();
    echo json_encode(array("status" => "error"));
}
$mysqli->close();