<?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'];
$auth_settings = sml_get_viewer_auth_settings($id_map);
$id_user = ((int)$auth_settings['viewer_auth_mode']>0) ? sml_get_viewer_user_id() : null;
if(!sml_viewer_can_use_feature($id_map,'live_tracking')) {
    ob_end_clean();
    echo json_encode(array("status"=>"auth_required","positions"=>[]));
    exit;
}
$lat = strip_tags($_POST['lat']);
$lon = strip_tags($_POST['lon']);
$name = strip_tags($_POST['name']);
$hash = strip_tags($_POST['hash']);
$timeout = (int)$_POST['timeout']*1000;
$colorsPool = [
    "#60360e", "#033124", "#553c01", "#63312b", "#09230f", "#0f2728", "#050200", "#021628",
    "#254968", "#332c01", "#40290e", "#153f27", "#061725", "#024533", "#1c1603", "#171f47",
    "#1c331e", "#3d310c", "#080400", "#000000", "#091326", "#3c2d12", "#091e39", "#063654",
    "#030200", "#071e23", "#320129", "#082e28", "#010300", "#371909", "#0c2d18", "#013744",
    "#5d0e1e", "#3c1467", "#402149", "#020000", "#353511", "#252d68", "#0d0801", "#00060c",
    "#061820", "#01274d", "#411127", "#1d4f3c", "#132745", "#030100", "#0f3120", "#4b1f54",
    "#4a0484", "#631a49", "#2b4515", "#051a0d", "#3d411f", "#180004", "#280124", "#000201",
    "#074914", "#01181f", "#300c5e", "#2b491f", "#353c80", "#2a4076", "#4f1234", "#251134",
    "#1b0a1a", "#0c0701", "#010000", "#80181f", "#3e3b15", "#050003", "#1e0117", "#30130c",
    "#45147b", "#0a3519", "#64371a", "#010e30", "#06262d", "#270e00", "#1c2303", "#1f2791",
    "#40470c", "#022021", "#011627", "#662728", "#370156", "#01251d", "#2d3d80", "#0d0306",
    "#02394c", "#010d0d", "#1f0719", "#000101", "#031328", "#28300e", "#044b3b", "#420e25",
    "#19051a", "#1e002b", "#5e281a", "#233905"
];
if(isset($_SESSION['lt_color'])) {
    $color = $_SESSION['lt_color'];
} else {
    $color = getUniqueColor($id, $colorsPool, $id_map);
}
$_SESSION['lt_color'] = $color;
$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;
    }
}
session_write_close();
$now = date('Y-m-d H:i:s');
$query = "INSERT INTO sml_live_tracking(id, id_map, id_user, lat, lon, name, color, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                id_user = VALUES(id_user),
                lat = VALUES(lat),
                lon = VALUES(lon),
                name = VALUES(name),
                updated_at = VALUES(updated_at);";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('siisssss',$id,$id_map,$id_user,$lat,$lon,$name,$color,$now);
    $smt->execute();
    $smt->close();
}
$now = date('Y-m-d H:i:s');
$query = "INSERT INTO sml_live_tracking_history(id, id_map, id_user, lat, lon, name, tracked_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE id_user = VALUES(id_user), updated_at = VALUES(updated_at);";
if($smt = $mysqli->prepare($query)) {
    $smt->bind_param('siisssss',$id,$id_map,$id_user,$lat,$lon,$name,$now,$now);
    $smt->execute();
    $smt->close();
}
if($live_tracking_only_admin) {
    if (md5(1 . 'smladmin') !== $hash) {
        ob_end_clean();
        echo json_encode(array("status" => "ok", "positions" => []));
        exit;
    }
}
$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();

function getUniqueColor($id, $colorsPool, $id_map) {
    global $mysqli;
    $query = "SELECT DISTINCT color FROM sml_live_tracking WHERE id_map = ?";
    $usedColors = [];
    if ($smt = $mysqli->prepare($query)) {
        $smt->bind_param('i', $id_map);
        $smt->execute();
        $result = get_result($smt);
        if(count($result)>0) {
            while($row = array_shift($result)) {
                $usedColors[] = $row['color'];
            }
        }
        $smt->close();
    }
    $availableColors = array_diff($colorsPool, $usedColors);
    if (!empty($availableColors)) {
        return array_values($availableColors)[0];
    }
    $hash = hexdec(substr(hash('sha256', $id), 0, 8));
    $index = $hash % count($colorsPool);
    return $colorsPool[$index];
}
