<?php
include '../config.php';
include "../ServerSelection.php";
date_default_timezone_set('Asia/Kolkata');
$user=$_POST['user'];
$password=$_POST['password'];
error_log("Distance API Call");
if(!($user==$apiusername && $password==$apipassword)){
    echo '{"result": "' ."Incorrect API credentials" .'"}';
    return;
}
if(isset($_POST['accountID'])) {
    $accountID=$_POST['accountID'];
} else {
    echo '{"result": "' ."Incorrect Account ID" .'"}';
    return;
}
$formate='json';
$fromDate = $_POST['fromDate'];
$toDate = $_POST['toDate'];
$requestTime=time();
$response='';
$jsonresponse='';
if($_POST['fromDate'] <= $_POST['toDate'] && abs($_POST['fromDate']-$_POST['toDate'])<86400){
    $caseDist=getCaseDistance($accountID,$deviceID,$fromDate,$toDate);
    $caseDistsplit=explode('*',$caseDist);
    $casedistance=$caseDistsplit[0];
    $caseStartLat=$caseDistsplit[1];
    $caseStartLong=$caseDistsplit[2];
    $caseEndLat=$caseDistsplit[3];
    $caseEndLong=$caseDistsplit[4];
    $motionstarttime=$caseDistsplit[5];
    $motinendtime=$caseDistsplit[6];
    $offlineTime=$caseDistsplit[7];
    $offlineStus="false";
    if($offlineTime>600){ //more than 10 minits
        $offlineStus="true";
    }
    //error_log("case Distance".$casedistance);
    saveRequest($accountID,$deviceID,$fromDate,$toDate,$casedistance,$requestTime,'success','distance Offline Status:'.$offlineStus);
    $jsonresponse= '{"Status":"success","ReceivedTime":"'.date('d-M-Y h:i:s a',time()).'","Distance":"'.$casedistance.'","StartLat":"'.$caseStartLat.'","StartLong":"'.$caseStartLong.'","EndLat":"'.$caseEndLat.'","EndLong":"'.$caseEndLong.'","TripStartTime":"'.($motionstarttime==0?'':date('d-M-Y h:i:s a',$motionstarttime)).'","TripEndTime":"'.($motinendtime==0?'':date('d-M-Y h:i:s a',$motinendtime)).'","OfflineStatus":"'.$offlineStus.'"}';
    $response="success";         
    if($formate=="xml"){
       header("Content-Type: text/xml;charset=utf-8");  
       echo "<?xml version='1.0' standalone='yes'?><casemanager><Status>".$response."</Status><ReceivedTime>".date('d-M-Y h:i:s a',time())."</ReceivedTime></casemanager>";
    } else {
       header('Content-Type: application/json');
       echo $jsonresponse;
    }
} else {//fail if
    if($_POST['fromDate']>$_POST['toDate']){
       echo '{"result": "' ."From Date Should be less then To Date" .'"}';
       saveRequest($accountID,$deviceID,$fromDate,$toDate,0,$requestTime,"From Date Should be less then To Date","distance");
    } else {
       echo '{"result": "' ."Requested Time Range Should be in 24 Hr" .'"}';
       saveRequest($accountID,$deviceID,$fromDate,$toDate,0,$requestTime,"Requested Time Range Should be in 24 Hr","distance");
    }
}

function getCaseDistance($accountID,$deviceID,$fromDate,$toDate) {
    global $gtsusername, $gtspassword, $gtsdb, $apiname,$gtsserver,$LiveEventDBserver;
   $currentTime=time();
   $difftime1=$currentTime-$fromDate;
   $difftime2=$currentTime-$toDate;
   if( $difftime1<11700 || $difftime2<11700){
         // request for before 3 hours 15 mts data go to production server
       $gtsserver=$LiveEventDBserver;
   }
   $gtsconnect = mysqli_connect($gtsserver,$gtsusername, $gtspassword) or die ("Unable to connect to gtsdb: " . mysqli_error($gtsconnect));
   mysqli_select_db($gtsconnect, $gtsdb);
    $totaldis=0;
   $startlat=0;
   $startlong=0;
   $endlat=0;
   $endlong=0;
   $stime=0;
   $etime=0;
   $i=0;
   $eventData=array(array());
   $Query = " SELECT heading, geozoneID,timestamp,deviceID,FROM_UNIXTIME(timestamp) as 'time1',speedKPH,address,odometerKM+odometerOffsetKM as 'distance',statusCode,analog0,latitude,longitude FROM `EventData` where accountID='$accountID' and deviceID='$deviceID'  and  timestamp between '$fromDate' and '$toDate' and latitude<>0 and longitude<>0  order by timestamp asc ";  //request from web for particular vehicle
   $qry_result = mysqli_query($gtsconnect, $Query) or die(mysqli_error($gtsconnect));
   $offlineTime=0;
   while($row = mysqli_fetch_assoc($qry_result)) {
        if($row['latitude']!= 0 && $row['longitude']!=0){
             $eventData[$i][0]=$row['latitude'];
             $eventData[$i][1]=$row['longitude'];
             $eventData[$i][2]=$row['timestamp'];
             if($i>0) {

                   
                  $endlat=$row['latitude'];
                  $endlong=$row['longitude'];
                  $etime=$row['timestamp'];
                  $eventtoeventdistance=distance1($row['latitude'],$row['longitude'], $eventData[$i-1][0], $eventData[$i-1][1]);
                  $difftimes=abs(($eventData[$i][2])-($eventData[$i-1][2]));
                  if($difftimes>600){
                      $offlineTime +=$difftimes;
                  }
                  $maxDistanceTravelledperMint=2;//max km travelled per mint
                  $calculatedDistenceTravelledperMint=intval($eventtoeventdistance)/$difftimes;
                  if(is_nan($eventtoeventdistance) || ($eventtoeventdistance/ $difftimes>0.04)){//if distnace greater than 2 km with 5 minits then distnace=0 bzc drift point in 
                     $eventtoeventdistance=0;
                  }else{
                       $totaldis=$totaldis+$eventtoeventdistance;
                       $i++;
                  }
              }

              if($i==0){ $startlat=$row['latitude'];$startlong=$row['longitude'];$stime=$row['timestamp']; $i++;}
        }
    }
   $startlat=round($startlat,5);
   $startlong=round($startlong,5);
   $endlat=round($endlat,5);
   $endlong=round($endlong,5);
   $totaldis=round($totaldis,2);
   $resultdata=$totaldis.'*'.$startlat.'*'.$startlong.'*'.$endlat.'*'.$endlong."*".$stime."*".$etime."*".$offlineTime; 
   mysqli_close($gtsconnect);
   return $resultdata;
}


?>
