<?php

// Created by Ahmadjonov Ibrohimjon Ilhomjon o'g'li on 29.09.2021

  $list_region = array();
  $response =array();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    require_once('connect.php');

    mysqli_set_charset($conn,"utf8");
    $query = mysqli_query($conn,"SET NAMES utf8");

    $query = mysqli_query($conn, "SELECT users.fio, users.user_id, users.telefon, last_lats.*, STR_TO_DATE(last_lats.vaqti, '%d.%m.%Y %H:%i:%s') AS vaqti2
FROM users
left JOIN (
     SELECT *
     FROM agent_locations
     WHERE agent_locations.Id IN (
        SELECT MAX(agent_locations.Id)
        FROM agent_locations
        GROUP BY agent_locations.agent_id
)
) AS last_lats
ON users.user_id = last_lats.agent_id
ORDER BY users.fio ASC;");


    if ($query !== false && $query->num_rows > 0) {

        while($row = mysqli_fetch_assoc($query)){

            $agent_id=$row['user_id'];
            $latitude=$row['latitude'];
            $longitude=$row['longitude'];
            $battery=$row['battery'];
            $fio=$row['fio'];
            $telefon=$row['telefon'];
            $time_update=$row['vaqti2'];
            $izox=$row['izox'];

            array_push($list_region,
            array(
                    'Id' => $agent_id,
                    'lat' => $latitude,
                    'lng' => $longitude,
                    'battery' => $battery,
                    'telefon' => $telefon,
                    'time_update' => $time_update,
                    'fio' => $fio,
                    'izox' => $izox
                 )
                );
        }

    }

}

echo json_encode($list_region);

$conn->close();
?>
