<?php

require_once('connect.php');

$agent_id       = $_GET['agent_id'];
$latitude       = $_GET['latitude'];
$longitude      = $_GET['longitude'];
$battery        = $_GET['battery'];
$zakaz_raqam    = $_GET['zakaz_raqam'];
$izox           = $_GET['izox'];
$vaqti          = $_GET['vaqti'];


$sql_sorov = "SELECT Id, latitude, longitude, time_create FROM agent_locations WHERE agent_id = '$agent_id' ORDER BY Id DESC LIMIT 1";


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


if ($javob !== false && $javob->num_rows > 0 && $zakaz_raqam == "0") {
    while($row=mysqli_fetch_array($javob)){
        
        $eski_latitude  = $row['latitude'];
        $eski_longitude = $row['longitude'];
        $time_create    = $row['time_create'];

        $latFrom = deg2rad($eski_latitude);
        $lonFrom = deg2rad($eski_longitude);
        $latTo = deg2rad($latitude);
        $lonTo = deg2rad($longitude);
        
        $lonDelta = $lonTo - $lonFrom;
        $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
        $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);
        
        $angle = atan2(sqrt($a), $b);
        $earthRadius = 6371000;
        $farqi =  $angle * $earthRadius;
        
        if($farqi > 15){
            $query = mysqli_query($conn, "INSERT INTO agent_locations (agent_id, latitude, longitude, battery, farqi, zakaz_raqam, vaqti, izox) VALUES ('$agent_id', '$latitude', '$longitude', '$battery', '$farqi', '$zakaz_raqam', '$vaqti', '$izox')");

            if($query== TRUE){
                echo "ok";
            } else {
                echo "no";
            }
        }else {
            echo 'ok';
        }
    }
}
else
{
    $query = mysqli_query($conn, "INSERT INTO agent_locations (agent_id, latitude, longitude, battery, zakaz_raqam, vaqti, izox) VALUES ('$agent_id', '$latitude', '$longitude', '$battery', '$zakaz_raqam', '$vaqti', '$izox')");
    
    if($query== TRUE){
        echo "ok";
    } else {
        echo "no";
    }
}

$conn->close();
?>
