<?php
include '../config1.php';
include '../Hospitals.php';
date_default_timezone_set('Asia/Kolkata');
$user=$_GET['user'];
$password=$_GET['password'];
if(!($user==$apiusername && $password==$apipassword)){
    echo '{"status":"fail","result": "' ."Incorrect API credentials" .'"}';
    return;
}
if(isset($_GET['accountID'])) {
    $accountID=$_GET['accountID'];
} else {
    echo '{"status":"fail","result": "' ."Incorrect Account ID" .'"}';
    return;
}
$formate='json';
$fromDate = $_GET['assignedTime'];
$toDate = $_GET['tripEndTime'];

$sceneLat=$_GET['sourceLatitude'];
$sceneLng=$_GET['sourceLongitude'];


$destLat1=$_GET['destinationLatitude1'];
$destLng1=$_GET['destinationLongitude1'];

$destLat2=$_GET['destinationLatitude2'];
$destLng2=$_GET['destinationLongitude2'];

$destLat3=$_GET['destinationLatitude3'];
$destLng3=$_GET['destinationLongitude3'];

$backLat=$_GET['baseLatitude'];
$backLng=$_GET['baseLongitude'];
$sourceDistrict=$_GET['sourceDistrict'];
$sourceType=$_GET['sourceType'];
$destinationType=$_GET['destinationType'];
$destinationDistrict=$_GET['destinationDistrict'];
//http://up108westapi.glovision.co/API/CaseSceneDestinatinBackToBase/?user=gvkemri&password=glovision&accountID=gvk-up-108&deviceID=UP32BG8535&assignedTime=1568241773&tripEndTime=1568243453&sourceLatitude=26.916047&sourceLongitude=78.479157&&destinationLatitude1=16.886763&destinationLongitude1=78.37431&baseLatitude=27.88642&baseLongitude=78.380473&destinationLatitude2=16.886763&destinationLongitude2=78.37431&destinationLatitude3=26.886763&destinationLongitude3=78.37431&sourceDistrict=&sourceType=hospital&destinationType=hospital&destinationDistrict=
$requestTime=time();
$response='';
$jsonresponse='';
if($_GET['fromDate'] <= $_GET['toDate'] && abs($_GET['fromDate']-$_GET['toDate'])<14400){//14400  means 4 hours
    $casedata=getCaseData($accountID,$deviceID,$fromDate,$toDate);
  
  for($i=0;$i<count($casedata);$i++){
       echo $i." == ".$casedata[$i][0]."  ".$casedata[$i][1]." ".date('d-m-Y H:i:s',$casedata[$i][2])."-- ".$casedata[$i][3]."  ".$casedata[$i][4]." ".$casedata[$i][6]."<br>"; 
    }

   
    $forwordingIndx=0;
    $minwordingIndx=0;
    $sceneInfo= builArray("source");
    $tempData=array(array());



    if(strtolower($sourceType)=="hospital"){  //Incident /Home/Hospital
       //get Hospital list
       if($sceneLat!="" & $sceneLng!=""){
            $sceneInfo=findSceneOrDestinationLocation($sceneLat,$sceneLng,$forwordingIndx,$casedata,"source");
            //if found scene locations betwee 500 minter range then go for idle in found location 
            if(count($tempData)>2){
               $sceneIdleInfo=findIdleWithInRange($tempData,0,"source","firstIdle");
               if($sceneIdleInfo["sourceArrivelLatitude"]!=""){
                   $sceneInfo=$sceneIdleInfo;
               }
            }
            if($sceneInfo["sourceArrivelLatitude"]==""){
                 $hospitalList=array(array());
                 $hospitalList=getHospitalList($sourceDistrict);
                 //var_dump($hospitalList);
                 for($hindx=0;$hindx<count($hospitalList);$hindx++){
                     $hlat=$hospitalList[$hindx][0];
                     $hlng=$hospitalList[$hindx][1];
                     $sceneInfo=findSceneOrDestinationLocation($hlat,$hlng,$forwordingIndx,$casedata,"source");
                     if($sceneInfo["sourceArrivelLatitude"]!=""){
                        break;
                     }
                 }
                 if($sceneInfo["sourceArrivelLatitude"]==""){
                    $sceneInfo=findIdle($casedata,$forwordingIndx,"source","firstIdle"); 
                 }
           }
       }
    }else{
        if($sceneLat!="" & $sceneLng!=""){
            $sceneInfo=findSceneOrDestinationLocation($sceneLat,$sceneLng,$forwordingIndx,$casedata,"source");
            if($sceneInfo["sourceArrivelLatitude"]==""){
              $sceneInfo=findIdle($casedata,$forwordingIndx,"source","firstIdle"); 
           }
       }
   }
  
  $sceneInfo["distancTosource"]=round($sceneInfo["distancTosource"],2);
  $sceneindx=$minwordingIndx;
  echo $forwordingIndx; 
  $destInfo1= builArray("destination1");
   $tempData=array(array());
   if(strtolower($destinationType)=="hospital"){ 
        $destInfo1=findSceneOrDestinationLocation($destLat1,$destLng1,$forwordingIndx,$casedata,"destination1");

          //if found scene locations betwee 500 minter range then go for idle in found location 
          if(count($tempData)>2){
               $destIdleInfo1=findIdleWithInRange($tempData,0,"destination1");
               if($destIdleInfo1["destination1ArrivelLatitude"]!=""){
                   $destInfo1=$destIdleInfo1;
               }
            }


        if($destInfo1["destination1ArrivelLatitude"]==""){
            $hospitalList=array(array());
            $hospitalList=getHospitalList($destinationDistrict);
            for($hindx=0;$hindx<count($hospitalList);$hindx++){
                 $hlat=$hospitalList[$hindx][0];
                 $hlng=$hospitalList[$hindx][1];
                 $destInfo1=findSceneOrDestinationLocation($hlat,$hlng,$forwordingIndx,$casedata,"destination1");
                 if($destInfo1["destination1ArrivelLatitude"]!=""){
                     // echo "hospitla check ok".$forwordingIndx;
                       break;
                 }
             }
             if($destInfo1["destination1ArrivelLatitude"]==""){
                 $destInfo1=findIdle($casedata,$forwordingIndx,"destination1","firstIdle");  
             }
        }
   }else{
      if($destLat1!="" & $destLng1!=""){
            $destInfo1=findSceneOrDestinationLocation($destLat1,$destLng1,$forwordingIndx,$casedata,"destination1");
            if($destInfo1["destination1ArrivelLatitude"]==""){
                $destInfo1=findIdle($casedata,$forwordingIndx,"destination1","firstIdle");
               // var_dump($destInfo1);
            }
        }

   }

  $dest1indx=$minwordingIndx;
   $destInfo1["distancTodestination1"]=round(abs($casedata[$sceneindx][6]-$casedata[$dest1indx][6]),2); 
   $destInfo2= builArray("destination2");

   $tempData=array(array());
   if($destLat2!="" & $destLng2!=""){
        $destInfo2=findSceneOrDestinationLocation($destLat2,$destLng2,$forwordingIndx,$casedata,"destination2");
         //if found scene locations betwee 500 minter range then go for idle in found location 
          if(count($tempData)>2){
               $destIdleInfo2=findIdleWithInRange($tempData,0,"destination2");
               if($destIdleInfo2["destination2ArrivelLatitude"]!=""){
                   $destInfo2=$destIdleInfo2;
               }
            }

  
        if($destInfo2["destination2ArrivelLatitude"]==""){
            $destInfo2=findIdle($casedata,$forwordingIndx,"destination2","firstIdle");
        }

     }


// echo "destination2 "+$forwordingIndx."<br>";
     $dest2indx=$minwordingIndx;
     $destInfo2["distancTodestination2"]=round(abs($casedata[$dest1indx][6]-$casedata[$dest2indx][6]),2);
     $destInfo3= builArray("destination3");
     $tempData=array(array());
 
    if($destLat3!="" & $destLng3!=""){
       // echo "==================================================";
        $destInfo3=findSceneOrDestinationLocation($destLat3,$destLng3,$forwordingIndx,$casedata,"destination3");
        //if found scene locations betwee 500 minter range then go for idle in found location 
          if(count($tempData)>2){
               $destIdleInfo3=findIdleWithInRange($tempData,0,"destination3");
               if($destIdleInfo3["destination3ArrivelLatitude"]!=""){
                   $destInfo3=$destIdleInfo3;
               }
            }

       // echo "================================================";
        if($destInfo3["destination3ArrivelLatitude"]==""){
            $destInfo3=findIdle($casedata,$forwordingIndx,"destination3","firstIdle");
        }

     }
    $dest3indx=$minwordingIndx;
     $destInfo3["distancTodestination3"]=round(abs($casedata[$dest2indx][6]-$casedata[$dest3indx][6]),2);
    $backinfo= builArray("backtobase");
    $tempData=array(array());
    if($backLat!="" & $backLng!=""){
        $backinfo=findSceneOrDestinationLocation($backLat,$backLng,$forwordingIndx,$casedata,"backtobase");
       // var_dump($backinfo);
        //if found scene locations betwee 500 minter range then go for idle in found location 
          if(count($tempData)>2){
               $backIdleInfo=findIdleWithInRange($tempData,0,"backtobase");
               if($backIdleInfo["backtobaseArrivelLatitude"]!=""){
                   $backinfo=$backIdleInfo;
               }
            }

       if((strtolower($sourceType)=="hospital"  && strtolower($destinationType)=="hospital") || abs($fromDate-$toDate)>7200 ){
              if($backinfo["backtobaseArrivelLatitude"]==""){
                  $backinfo=findIdle($casedata,$forwordingIndx,"backtobase","lastIdle");
                //echo $minwordingIndx;
              }
       }else{
          if($backinfo["backtobaseArrivelLatitude"]==""){
              $backinfo["backtobaseArrivelTime"]=$casedata[count($casedata)-1][2];
              $backinfo["backtobaseArrivelLatitude"]=$casedata[count($casedata)-1][0];
              $backinfo["backtobaseArrivelLongitude"]=$casedata[count($casedata)-1][1];
               $minwordingIndx=count($casedata)-1;
            //  $backinfo=findIdle($casedata,$forwordingIndx,"backtobase");
          } 
      }

     }
     $backtobaseindx=$minwordingIndx;
     $backinfo["distancTobacktobase"]=round(abs($casedata[$dest3indx][6]-$casedata[$backtobaseindx][6]),2);
     $response=array_merge($sceneInfo,$destInfo1,$destInfo2,$destInfo3,$backinfo);

      
     $response["tripStartTime"]=$casedata[0][2];
     $response["tripStartLatitude"]=$casedata[0][0];
     $response["tripStartLongitude"]=$casedata[0][1];
     $response["tripDistance"]=round($casedata[$backtobaseindx][6],2);
    //saveRequest($accountID,$deviceID,$fromDate,$toDate,$casedistance,$requestTime,'success','distance');
   // $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 '{"status":"success","result": ' . json_encode(utf8ize($response)) .'}';
    }
} else {//fail if
    if($_GET['fromDate']>$_GET['toDate']){
       echo '{"status":"fail","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 '{"status":"fail","result": "' ."Requested Time Range Should be in 4 Hr" .'"}';
       //saveRequest($accountID,$deviceID,$fromDate,$toDate,0,$requestTime,"Requested Time Range Should be in 4 Hr","distance");
    }
}

function getCaseData($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);
   $eventData=array(array());
   $i=0;
   $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));
   $totaldis=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'];
             $eventData[$i][3]=$row['statusCode'];
             $eventData[$i][4]=$row['address'];
             $eventData[$i][5]=$row['deviceID'];
             $eventData[$i][6]=0;
             if($i>0){
                  $eventtoeventdistance=distance1($eventData[$i-1][0],$eventData[$i-1][1], $eventData[$i][0],$eventData[$i][1]);
                  $difftimes=abs(($eventData[$i][2])-($eventData[$i-1][2]));
                  $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;
                       $eventData[$i][6]=$totaldis;
                       $i++;
                  }

             }
             if($i==0){
                $i++;
             }
        }
    }
   mysqli_close($gtsconnect);
   return $eventData;
}


function findSceneOrDestinationLocation($sceneLat,$sceneLng,$indx,$casedata,$key){
    global $forwordingIndx,$tempData,$minwordingIndx;
    $tempminwordingIndx=$minwordingIndx;
    $locationfind=0;
    $res=array();
    $res[$key."ArrivelTime"]="";
    $res[$key."ArrivelLatitude"]="";
    $res[$key."ArrivelLongitude"]=""; 
    $res[$key."DepartTime"]="";
    $res[$key."DepartLatitude"]=""; 
    $res[$key."DepartLongitude"]="";
    $res["distancTo".$key]=0;
    $tempindx=0;
    for($i=$indx;$i<count($casedata);$i++){
        $distance=distance1($sceneLat,$sceneLng,$casedata[$i][0],$casedata[$i][1]);
        $distance=$distance*1000;//distance convertinto meters 
        if($distance<500){
            if($locationfind==0){
               $res[$key."ArrivelTime"]=$casedata[$i][2];
               $res[$key."ArrivelLatitude"]=$casedata[$i][0];
               $res[$key."ArrivelLongitude"]=$casedata[$i][1];
               $res["distancTo".$key]=$casedata[$i][6];
               $locationfind=1;
               $minwordingIndx=$i;
               $tempData[$tempindx]=$casedata[$i];
               $tempData[$tempindx][7]=$i;
                $tempindx++;
               //if($key=="backtobase"){ break;}
            }else if($locationfind==1){
                $tempData[$tempindx]=$casedata[$i];
                $tempData[$tempindx][7]=$i;
                //echo $tempindx."  ".$key."====".$casedata[$i][2]."<br>";
                $tempindx++;
            }
        }else if($locationfind==1){
              $res[$key."DepartTime"]=$casedata[$i][2];
              $res[$key."DepartLatitude"]=$casedata[$i][0];
              $res[$key."DepartLongitude"]=$casedata[$i][1];
              $tempData[$tempindx]=$casedata[$i];
              $tempData[$tempindx][7]=$i;
              $tempindx++;
             // $res["distancTo".$key]=$casedata[$i][6]; 
              $forwordingIndx=$i;
              $locationfind=0;
              break;  
        }
       // if($key=="destination3")
       //    echo "Index:".$i."  ".$casedata[$i][0]."  ".$casedata[$i][1]." ".$sceneLat."-- ".$sceneLng."  ".$casedata[$i][4]." distance ".$distance."<br>";
    }
    if($locationfind==1){
        $res[$key."DepartTime"]=$casedata[count($casedata)-1][2];
        $res[$key."DepartLatitude"]=$casedata[count($casedata)-1][0];
        $res[$key."DepartLongitude"]=$casedata[count($casedata)-1][1];
       // $res["distancTo".$key]=$casedata[count($casedata)-1][6]; 
        $tempData[$tempindx]=$casedata[count($casedata)-1];
        $tempData[$tempindx][7]=count($casedata)-1;
         $tempindx++;
        $forwordingIndx=count($casedata)-1;
        $locationfind=0;
    }


  if($res[$key."ArrivelTime"]=="" || $res[$key."DepartTime"]==""){
      $res[$key."ArrivelTime"]="";
      $res[$key."ArrivelLatitude"]="";
      $res[$key."ArrivelLongitude"]="";
      $res[$key."DepartTime"]="";
      $res[$key."DepartLatitude"]="";
      $res[$key."DepartLongitude"]="";
      $res["distancTo".$key]=0;
      $forwordingIndx=$indx;
      $minwordingIndx=$tempminwordingIndx;
   }



   return $res;
}

function findIdle($casedata,$indx,$key,$searchIdle){
    global $forwordingIndx,$minwordingIndx;
    $tempminwordingIndx=$minwordingIndx;
    $locationfind=0;
    $res=array();
    $res[$key."ArrivelTime"]="";
    $res[$key."ArrivelLatitude"]="";
    $res[$key."ArrivelLongitude"]="";       
    $res[$key."DepartTime"]="";
    $res[$key."DepartLatitude"]="";       
    $res[$key."DepartLongitude"]="";
    $res["distancTo".$key]=0;
  //  echo $minwordingIndx."=============0000000000000********".$forwordingIndx;
    for($i=$indx;$i<count($casedata);$i++){
        if(($casedata[$i][3]=="61718" || $casedata[$i][3]=="61717") && $locationfind==0){
               $res[$key."ArrivelTime"]=$casedata[$i][2];
               $res[$key."ArrivelLatitude"]=$casedata[$i][0];
               $res[$key."ArrivelLongitude"]=$casedata[$i][1];
               $res["distancTo".$key]=$casedata[$i][6];
               $minwordingIndx=$i;
               $locationfind=1;
        }else if(($casedata[$i][3]!="61718" && $casedata[$i][3]!="61717") && $locationfind==1){
              //$res[$key."DepartTime"]=$casedata[$i][2];
              //$res[$key."DepartLatitude"]=$casedata[$i][0];
              //$res[$key."DepartLongitude"]=$casedata[$i][1];
            //   $res["distancTo".$key]=$casedata[$i][6];
              $locationfind=0;
                                
              $timediff=intval(abs($res[$key."ArrivelTime"]-$casedata[$i][2]));
             //echo "Time Diff==================".$timediff."<br>";
              if($timediff>=30){
                  $res[$key."DepartTime"]=$casedata[$i][2];
                  $res[$key."DepartLatitude"]=$casedata[$i][0];
                  $res[$key."DepartLongitude"]=$casedata[$i][1];
                  //   $res["distancTo".$key]=$casedata[$i][6];
                  $locationfind=0;
                  $forwordingIndx=$i;
                  if($searchIdle=="firstIdle"){
                      break;
                   }
              }
        }
    }

    if($locationfind==1){
        $res[$key."DepartTime"]=$casedata[count($casedata)-1][2];
        $res[$key."DepartLatitude"]=$casedata[count($casedata)-1][0];
        $res[$key."DepartLongitude"]=$casedata[count($casedata)-1][1];
        //$res["distancTo".$key]=$casedata[count($casedata)-1][6]; 
        $forwordingIndx=count($casedata)-1;
        $locationfind=0;
    }

   
   if($res[$key."ArrivelTime"]=="" || $res[$key."DepartTime"]==""){
      $res[$key."ArrivelTime"]="";
      $res[$key."ArrivelLatitude"]="";
      $res[$key."ArrivelLongitude"]="";
      $res[$key."DepartTime"]="";
      $res[$key."DepartLatitude"]="";
      $res[$key."DepartLongitude"]="";
      $res["distancTo".$key]=0;
      $forwordingIndx=$indx;
      $minwordingIndx=$tempminwordingIndx;
   }
 
   return $res;
 
}

function findIdleWithInRange($casedata,$indx,$key){
    global $forwordingIndx,$minwordingIndx;
    $tempminwordingIndx=$minwordingIndx;
    $locationfind=0;
    $res=array();
    $res[$key."ArrivelTime"]="";
    $res[$key."ArrivelLatitude"]="";
    $res[$key."ArrivelLongitude"]="";
    $res[$key."DepartTime"]="";
    $res[$key."DepartLatitude"]="";
    $res[$key."DepartLongitude"]="";
    $res["distancTo".$key]=0;
    for($i=$indx;$i<count($casedata);$i++){
        if(($casedata[$i][3]=="61718" || $casedata[$i][3]=="61717") && $locationfind==0){
               $res[$key."ArrivelTime"]=$casedata[$i][2];
               $res[$key."ArrivelLatitude"]=$casedata[$i][0];
               $res[$key."ArrivelLongitude"]=$casedata[$i][1];
               $res["distancTo".$key]=$casedata[$i][6];
               $minwordingIndx=$casedata[$i][7];
               //echo "Index".$i."  Key".$key."<br>";
               $locationfind=1;
        }else if(($casedata[$i][3]!="61718" && $casedata[$i][3]!="61717") && $locationfind==1){

             $locationfind=0;
             $timediff=intval(abs($res[$key."ArrivelTime"]-$casedata[$i][2]));
             //echo $res[$key."ArrivelTime"]." ".$casedata[$i][2];
             //echo "Time====".$timediff." KEY:".$key."<br>";
              if($timediff>=30){ 
                  $res[$key."DepartTime"]=$casedata[$i][2];
                  $res[$key."DepartLatitude"]=$casedata[$i][0];
                  $res[$key."DepartLongitude"]=$casedata[$i][1];
                  //   $res["distancTo".$key]=$casedata[$i][6];
                  $locationfind=0;
                  $forwordingIndx=$casedata[$i][7];
                  break;
              }
        }
    }

     if($locationfind==1){
        $res[$key."DepartTime"]=$casedata[count($casedata)-1][2];
        $res[$key."DepartLatitude"]=$casedata[count($casedata)-1][0];
        $res[$key."DepartLongitude"]=$casedata[count($casedata)-1][1];
        $forwordingIndx=$casedata[count($casedata)-1][7];
        $locationfind=0;
    }




    if($res[$key."ArrivelTime"]=="" || $res[$key."DepartTime"]==""){
      $res[$key."ArrivelTime"]="";
      $res[$key."ArrivelLatitude"]="";
      $res[$key."ArrivelLongitude"]="";
      $res[$key."DepartTime"]="";
      $res[$key."DepartLatitude"]="";
      $res[$key."DepartLongitude"]="";
      $res["distancTo".$key]=0;
      $forwordingIndx=$indx;
      $minwordingIndx=$tempminwordingIndx;
   }  
    return $res;



}
function builArray($key){
    $res=array();
    $res[$key."ArrivelTime"]="";
    $res[$key."ArrivelLatitude"]="";
    $res[$key."ArrivelLongitude"]="";
    $res[$key."DepartTime"]="";
    $res[$key."DepartLatitude"]="";
    $res[$key."DepartLongitude"]="";
    $res["distancTo".$key]=0;
    return $res;
}

function getHospitalList($sourceDistrict){
     global $responcehospitals;
     return $responcehospitals[strtolower($sourceDistrict)];
 }
?>
