<?php
require_once "../lib/config.php";
$lat = $_REQUEST["lat"];
$lon = $_REQUEST["lon"];
// =============== Get referral code api ===================================

$time = (time() - 60 * 60 * 10) * 1000;

$url = "https://api.fleeteng.com.au/v2/graph/role/vehicles?access_token=KX53ZweKgbbVIhD0_411iNWI9cQurfxbygZH9vpfsyX7";
			$curlObj = curl_init();
			curl_setopt($curlObj, CURLOPT_URL, $url);
			curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);

			$response = curl_exec($curlObj);

			curl_close($curlObj);
	
			$json = json_decode($response, true);
			
			function distance($lat1, $lon1, $lat2, $lon2, $unit) {

			  $theta = $lon1 - $lon2;
			  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
			  $dist = acos($dist);
			  $dist = rad2deg($dist);
			  $miles = $dist * 60 * 1.1515;
			  $unit = strtoupper($unit);
			
			  if ($unit == "K") {
			      return ($miles * 1.609344);
			  } else if ($unit == "N") {
			      return ($miles * 0.8684);
			  } else {
			      return $miles;
			  }
			}
			
			
			
			$checkdist = [10000000];
			$r = 1;
			foreach($json['items'] as $items) {
			
				$result = mysqli_query($conn, "SELECT * FROM drivers WHERE spat_id='".$items['id']."'");
				if(!$result) {
				    error_log($conn->error);
				}
			    $row = mysqli_fetch_assoc($result);
        			$drivername = $row['name'];
			
			    
			
				if($items['points']['items'][0]['reported'] >= $time && $drivername != "") {
				
				$dist = distance($lat, $lon, $items['points']['items'][0]['location']["lat"], $items['points']['items'][0]['location']["lon"], "K");
				//echo $dist;
				$x = count($checkdist);
				if($dist < $checkdist[$x-1]) {
					array_push($checkdist, $dist);
					sort($checkdist);
					if(count($checkdist) > 5) {
					unset($coords["$checkdist[6]"]);
					unset($checkdist[6]);
					
					}
					
					if($items['points']['items'][0]["heading"] != null) {
					    $heading = $items['points']['items'][0]["heading"];
					} else {
					    $heading = 0;
					}
				
				$coords["$dist"] = [$items['points']['items'][0]['location']["lat"], $items['points']['items'][0]['location']["lon"], $heading] ;
				
				}
				} 
			}
			if(count($checkdist) == 1) {
			 $Res["message"] = "No Drivers Found"; 
			$Res["status"] = "error";
			} else {
			
			
			if (($key = array_search(10000000, $checkdist)) !== false) {
    				unset($checkdist[$key]);
			}	
			
			//$array = array_filter($json['items'], function($v) use ($time) {
			//	
                        //                  return $v['points']['items'][0]['reported'] >= $time; });
                                           
                        //$array = reset($array);
                        
                        //echo "<br>lat: ".$coords["$checkdist[0]"][0];
                        $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$lat,$lon&destinations=".$coords["$checkdist[0]"][0].",".$coords["$checkdist[0]"][1]."&mode=driving&sensor=false&key=AIzaSyCCoesQpJz8mjizSKIng1cmBrx-T9VgXmw";
			    $ch = curl_init();
			    curl_setopt($ch, CURLOPT_URL, $url);
			    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
			    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			    $response = curl_exec($ch);
			   
			    curl_close($ch);
			    $response_a = json_decode($response, true);
			    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
			    $timeClose = ceil(($response_a['rows'][0]['elements'][0]['duration']['value'])/60)." mins";
			
			$x = count($checkdist) - 1;
			$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$lat,$lon&destinations=".$coords["$checkdist[$x]"][0].",".$coords["$checkdist[$x]"][1]."&mode=driving&sensor=false&key=AIzaSyCCoesQpJz8mjizSKIng1cmBrx-T9VgXmw";
			    $ch = curl_init();
			    curl_setopt($ch, CURLOPT_URL, $url);
			    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
			    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			    $response = curl_exec($ch);
			    curl_close($ch);
			    $response_a = json_decode($response, true);
			    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
			    $timeFar = ceil(($response_a['rows'][0]['elements'][0]['duration']['value'])/60)." mins";
			
                        

	$Res["message"] = "Drivers Found"; 
	$Res["status"] = "OK";
	$Res["timeClose"] = $timeClose;
	$Res["timeFar"] = $timeFar;
	if($coords["$checkdist[0]"][0] == null) {
	$Res["car1lat"] = 0;
	$Res["car1lon"] = 0;
	$Res["car1rot"] = 0;
	} else {
	$Res["car1lat"] = $coords["$checkdist[0]"][0];
	$Res["car1lon"] = $coords["$checkdist[0]"][1];
	$Res["car1rot"] = $coords["$checkdist[0]"][2];
	}
	if($coords["$checkdist[1]"][0] == null) {
	$Res["car2lat"] = 0;
	$Res["car2lon"] = 0;
	$Res["car2rot"] = 0;
	} else {
	$Res["car2lat"] = $coords["$checkdist[1]"][0];
	$Res["car2lon"] = $coords["$checkdist[1]"][1];
	$Res["car2rot"] = $coords["$checkdist[1]"][2];
	}
	if($coords["$checkdist[2]"][0] == null) {
	$Res["car3lat"] = 0;
	$Res["car3lon"] = 0;
	$Res["car3rot"] = 0;
	} else {
	$Res["car3lat"] = $coords["$checkdist[2]"][0];
	$Res["car3lon"] = $coords["$checkdist[2]"][1];
	$Res["car3rot"] = $coords["$checkdist[2]"][2];
	}
	if($coords["$checkdist[3]"][0] == null) {
	$Res["car4lat"] = 0;
	$Res["car4lon"] = 0;
	$Res["car4rot"] = 0;
	} else {
	$Res["car4lat"] = $coords["$checkdist[3]"][0];
	$Res["car4lon"] = $coords["$checkdist[3]"][1];
	$Res["car4rot"] = $coords["$checkdist[3]"][2];
	}
	if($coords["$checkdist[4]"][0] == null) {
	$Res["car5lat"] = 0;
	$Res["car5lon"] = 0;
	$Res["car5rot"] = 0;
	} else {
	$Res["car5lat"] = $coords["$checkdist[4]"][0];
	$Res["car5lon"] = $coords["$checkdist[4]"][1];
	$Res["car5rot"] = $coords["$checkdist[4]"][2];
	}
	if($coords["$checkdist[5]"][0] == null) {
	$Res["car6lat"] = 0;
	$Res["car6lon"] = 0;
	$Res["car6rot"] = 0;
	} else {
	$Res["car6lat"] = $coords["$checkdist[5]"][0];
	$Res["car6lon"] = $coords["$checkdist[5]"][1];
	$Res["car6rot"] = $coords["$checkdist[5]"][2];
	}
	
}	

echo json_encode(new ArrayObject($Res)); 


?>