<?php
 //  header("Content-Type: application/json");
//http://up108westapi.glovision.co/API/DeviceDistanceAPI/index-distancein4ways.php?accountID=gvk-up-108&deviceID=UP32BG9441&fromDate=24-03-2020%2000:00:00&toDate=24-03-2020%2023:00:00	
//   include '../config.php';



   //include "../ServerSelection1.php";
   date_default_timezone_set('Asia/Kolkata');
   require_once('encodeurl.php');
   require_once 'PolylineEncoder.php';


   $accountID=$_GET['accountID'];
   $fromDate = strtotime($_GET['fromDate']);
    $groupID = $_GET['groupID'];
   $toDate = strtotime($_GET['toDate']);
   $table="<table><tr><th>GroupID</th><th>DeviceID</th><th><Linear Distance/th><th>Odometer Distance</th></tr>";
   if(isset($_GET['accountID'])){

      $gtsserver="localhost";
      $gtsusername="gts";
      $gtspassword="opengts";
      $gtsdb="gts";

      $tacserver = "localhost";
      $tacusername = "root";
      $tacpassword = "gl0v1s10n";
      $tacdb = "autocare_gts";
      $LiveEventDBserver="up108westlocal";   //live server for east,west 
      $apiusername="gvkemri";
      $apipassword="glovision";
      $accountID=isset($_GET['accountID'])?$_GET['accountID']:"";
      $groupID=isset($_GET['groupID'])?$_GET['groupID']:"";
      if($accountID=="gvk-up-108"){
       if(!getGroupServer($accountID,$groupID)){ //check vehicle is in present server or not
          $tacserver="up108eastapilocal";
          $gtsserver="up108eastapilocal";
          $LiveEventDBserver="up108eastlocal";
       }
      }

     $deviceList =getDeviceList($accountID,$groupID);


     for($vindx=0;$vindx<count($deviceList);$vindx++){
          $deviceID=$deviceList[$vindx];
         $caseDist=getCaseDistance($accountID,$deviceID,$fromDate,$toDate);
   
          break; 
     }
     $table =$table."</table>";
     $fromDate=date("d-m-Y H:i:s",$fromDate);
    $toDate=date("d-m-Y H:i:s",$toDate);
  }else{
        $fromDate=date("d-m-Y H:i:s");
    $toDate=date("d-m-Y H:i:s");

   }
  


function getGroupServer($accountID,$groupID) {
    global $gtsserver, $gtsusername, $gtspassword, $gtsdb, $LiveEventDBserver;
    $gtsconnect = mysqli_connect($LiveEventDBserver,$gtsusername,$gtspassword) or die ($gtsserver." Unable to connect to the tacdb : " . mysqli_error($gtsconnect));
    mysqli_select_db($gtsconnect, $gtsdb);
    $request_time_query="Select groupID from DeviceGroup where groupID='$groupID'";
   // error_log($request_time_query."  ".$gtsserver);
    $qry_result=mysqli_query($gtsconnect,$request_time_query) or die(mysqli_error($gtsconnect));
   // error_log("completed");
    $deviceFound=false;
    while($row=mysqli_fetch_array($qry_result)) {
       $deviceFound=true;
    }
   // error_log($deviceFound);
    mysqli_close($gtsconnect);
    return $deviceFound;

}



function getDeviceList($accountID,$groupID) {
    global $gtsserver, $gtsusername, $gtspassword, $gtsdb, $LiveEventDBserver;
    $gtsconnect = mysqli_connect($LiveEventDBserver,$gtsusername,$gtspassword) or die ($gtsserver." Unable to connect to the tacdb : " . mysqli_error($gtsconnect));
    mysqli_select_db($gtsconnect, $gtsdb);
    $request_time_query="Select deviceID from DeviceList where accountID='$accountID' and  groupID='$groupID'";
   // error_log($request_time_query."  ".$gtsserver);
    $qry_result=mysqli_query($gtsconnect,$request_time_query) or die(mysqli_error($gtsconnect));
   // error_log("completed");

   $deviceList=array();
    while($row=mysqli_fetch_array($qry_result)) {
      $deviceList[count($deviceList)]=$row["deviceID"];
    }
   // error_log($deviceFound);
    mysqli_close($gtsconnect);
    return $deviceList;

}



function getCaseDistance($accountID,$deviceID,$fromDate,$toDate) {
    global $gtsusername, $gtspassword, $gtsdb, $gtsserver,$table,$LiveEventDBserver,$groupID;
    $gtsconnect = mysqli_connect($LiveEventDBserver,$gtsusername, $gtspassword) or die ("Unable to connect to gtsdb: " . mysqli_error($gtsconnect));
    mysqli_select_db($gtsconnect, $gtsdb);
    $sql = "Select odometerKM,odometerOffsetKM,accountID,deviceID,address,from_unixtime( timestamp, '%d-%m-%Y %H:%i:%s' ) as time1,statusCode,latitude,longitude,geozoneID,speedKPH,timestamp as unixtime from EventData where accountID='$accountID' and deviceID='".$deviceID."' and  timestamp BETWEEN $fromDate AND $toDate and latitude!=0 and longitude!=0";
   $qry_result = mysqli_query($gtsconnect, $sql) or die(mysqli_error($gtsconnect));

   $inmotionnum_rows = mysqli_num_rows($qry_result);
   $indx=0;
   $eventIncreament="yes";
   $TotalLeanerDis=0;
   $TotalTvsSDis=0;
   $daya=array(array());
   $TotalAvgDis=0;
   $TotalGoogleDistance=0;
   $OdometerDis=0;
    $mapindialat="";
   $mapindialng="";
   $maptime=0;
   $snaplnglat="";
   $times="";
   $radius="";
   while($row = mysqli_fetch_assoc($qry_result)) {
        $data[$indx][0]=$row['accountID'];
        $data[$indx][1]=$row['deviceID'];
        $data[$indx][2]=$row['address'];
        $data[$indx][3]=$row['time1'];
        $data[$indx][4]=$row['statusCode'];
        $data[$indx][5]=$row['latitude'];
        $data[$indx][6]=$row['longitude'];
        $data[$indx][8]=$row['speedKPH'];
        $data[$indx][10]=$row['unixtime'];
        $data[$indx][11]=$row['odometerKM'];
        $TvsS=0;
        $googledis=0;

   
        
        if($indx>0 && $row['latitude']!= 0 && $row['longitude']!=0 && $data[$indx-1][5]!=0 && $data[$indx-1][6]!=0) {
            $TvsS=($data[$indx][8]/3600)*($data[$indx][10]-$data[$indx-1][10]);
           $data[$indx][7]=distance1($row['latitude'],$row['longitude'], $data[$indx-1][5], $data[$indx-1][6]);
           $difftimes=abs(strtotime($data[$indx][3])-strtotime($data[$indx-1][3]));
           //$googledis=GetDrivingDistance($data[$indx-1][5],$row['latitude'],$data[$indx-1][6],$row['longitude']);//google distance
           if(is_nan($data[$indx][7]) || ($data[$indx][7]/$difftimes)>0.025){//if distnace greater than 2 km with 5 minits then distnace=0 bzc drift point  
                $eventIncreament="no";
                $data[$indx][7]=0;//$data[$indx][7];
                 $TvsS=0;
                 $googledis=0;
           }

        } else {
                $data[$indx][7]=0;
                 $TvsS=0;
                 $googledis=0;
        }


   //   $snaplnglat .=$row['longitude'].",".$row['latitude'].";";
    //  $times .=strtotime($row['time1']).";";
    //  $radius .="30;";
 
       
        //echo $data[$indx][3]." = ".$data[$indx][7]."<br>";
        if(is_nan($data[$indx][7])){
             $data[$indx][7]=0;
        }
        if($indx>0 && $indx%3==0){
              $speedavg= ($data[$indx-3][8]+$data[$indx-2][8]+$data[$indx-1][8]+$data[$indx][8])/4;
              $difftimetotal=(($data[$indx][10]-$data[$indx-1][10])+($data[$indx-1][10]-$data[$indx-2][10])+($data[$indx-2][10]-$data[$indx-3][10]));
             //  echo $indx." ".($indx-1)." ".($indx-2)."  ".($indx-3)."   Speed:".$speedavg." Time:".$difftimetotal." Distnace".$TotalAvgDis."<br>";
           
           $TotalAvgDis=$TotalAvgDis+(($speedavg/3.6)*$difftimetotal);
 /*
             if($indx>=3){
                $speedavg= $data[$indx-3][8];
                $difftimetotal=($data[$indx-3][10]-$data[$indx-4][10]);
                $TotalAvgDis=$TotalAvgDis+(($speedavg/3.6)*$difftimetotal);
              }
 */
        }
         //5 events range
         if($indx%30==0){
              if(round($data[$indx-30][5],5)!=round($row['latitude'],5)){  
                 $mapindialat=$row['latitude'];
                 $mapindialng=$row['longitude'];
                 $maptime=strtotime($row["time1"]);
                 $snaplnglat .=$row['longitude'].",".$row['latitude'].";";
                 $times .=strtotime($row['time1']).";";
                $radius .="60;";
               //  $googledis=getDriveingDistanceMapMyIndia($data[$indx-30][5],$row['latitude'],$data[$indx-30][6],$row['longitude']);//google distance
                // echo  round($data[$indx-5][5],5)." $indx ".round($row['latitude'],5)." Dis:".$googledis."<br>";
             }
         }
         $TotalGoogleDistance=$TotalGoogleDistance+$googledis;      
         $TotalLeanerDis= $TotalLeanerDis+$data[$indx][7];
         $TotalTvsSDis=$TotalTvsSDis+$TvsS;
         
        if($eventIncreament=="yes"){
           $indx++;
        }else{
           $eventIncreament="yes";
        }
   } //end while
  mysqli_close($gtsconnect);

  
  $snaplnglat .=$data[count($data)-1][6].",".$data[count($data)-1][5].";";
   $times .=strtotime($data[count($data)-1][3]).";";
    $radius .="60;"; 
  //$googledis=getDriveingDistanceMapMyIndia($mapindialat,$data[count($data)-1][5],$mapindialng,$data[count($data)-1][6]);//google distance
$TotalGoogleDistance=$TotalGoogleDistance+$googledis;

  //$snapdistance=getDriveingDistanceMapMyIndiaSnap($snaplnglat,$times,$radius);//google distance

  $OdometerDis=$data[count($data)-2][11]-$data[0][11];


//  $TotalGoogleDistance=$TotalGoogleDistance+ getDriveingDistanceMapMyIndia($data[0][5],$data[count($data)-2][5],$data[0][6],$data[count($data)-2][6]);

  $array=array();
  $array["linearDistance"]=$TotalLeanerDis;
  //$array["d=s*t"]=round($TotalTvsSDis,2);
 // $array["avgd=s*t"]=(round($TotalAvgDis,2))/1000;
//  $array["mapmyindia"]=round($TotalGoogleDistance,2);
  $array["odometer"]=$OdometerDis;
//$array["snapdistance"]=$snapdistance;

//  echo  json_encode($array);

    $table =$table."<tr><td>".$groupID."</td><td>".$deviceID."</td><td>".$TotalLeanerDis."</td><td>".$OdometerDis."</td></tr>";; 
//  $table ="Linear Distance :".$TotalLeanerDis." Kms<br>Odometer Distance:".$OdometerDis." Kms<br>MapMyIndia Distance: ".$TotalGoogleDistance." Kms<br><a href='http://up108west.glovision.co/upmergeddashboard/php/CaseRoute.php?accountID=".$accountID."&vehicleID=".$deviceID."&platEntryTime=$fromDate&departTime=$toDate' target='_blank'>Linear VS MapMyIndia Route</a>";

//echo $table;
//  echo "Linear Distance:".$TotalLeanerDis." Kms <br> Time Vs Speed Distance :".round($TotalTvsSDis,2)." Kms<br>Avg of Time Vs Speed Distance: ". round($TotalAvgDis,2)." Kms<br> Google Distance: ".round($TotalGoogleDistance,2)."<br> Odemoter Dis:".$OdometerDis;
}

function getDriveingDistanceMapMyIndia($lat1, $lat2, $long1, $long2){


       $geocodeFromLatLong = file_get_contents("https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/distance_matrix/driving/$long1,$lat1;$long2,$lat2");
    // $geocodeFromLatLong = file_get_contents("https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/snapToRoad?pts=".$waypoints."&tamps=".$times."&radius=".$radius);

  // echo "https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/snapToRoad?pts=".$waypoints."&tamps=".$times."&radius=".$radius;
     $output = json_decode($geocodeFromLatLong);

     $res=$output->results->distances[0][1];
     return $res/1000;

}


function distance1($lat1, $lon1, $lat2, $lon2) {
        if($lat1 == $lat2 && $lon1 == $lon2){
            return 0;

        }else{$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;
            return $miles* 1.609344;
        }
 }

function getDriveingDistanceMapMyIndiaSnap($waypoints,$times,$radius){

    $waypoints=trim($waypoints,";");
     $times=trim($times,";");
      $radius=trim($radius,";");
//       $geocodeFromLatLong = file_get_contents("https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/distance_matrix/driving/$long1,$lat1;$long2,$lat2");
   $geocodeFromLatLong = file_get_contents("https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/snapToRoad?pts=".$waypoints."&timestamps=".$times."&radiuses=".$radius);
//echo "https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/snapToRoad?pts=".$waypoints."&timestamps=".$times."&radiuses=".$radius;
  //	 echo "https://apis.mapmyindia.com/advancedmaps/v1/m3unnnii63d3nfobljamtk4ss5n8x1gj/snapToRoad?pts=".$waypoints."&tampstamps=".$times."&radiuses=".$radius;
     $output = json_decode($geocodeFromLatLong);

//     var_dump($output);
     $res=$output->results->snappedPoints;
   $distance=0;
   for($indx=0;$indx<count($res);$indx++){

    $distance +=$res[$indx]->distance;
  // echo $res[$indx]->distance."<br>";
    }
 //  echo $distance;
     return $distance;

}

function GetDrivingDistance($lat1, $lat2, $long1, $long2)
{

     $encodedaddress=signUrl("https://maps.googleapis.com/maps/api/distancematrix/json?client=gme-gvkemergencymanagement3&origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL", 'd1CkkvZsTH1jgTgvsZvvYRaSDSc=');
       $geocodeFromLatLong = file_get_contents($encodedaddress);
     //var_dump($geocodeFromLatLong);
     $output = json_decode($geocodeFromLatLong);
     $res=$output->rows[0]->elements[0]->distance->value;
     return $res/1000;
/*

    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?client=gme-gvkemergencymanagement3&origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=pl-PL";
    echo $url;
    $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);
   //  echo $response;
    $response_a = json_decode($response, true);
    $dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
    $time = $response_a['rows'][0]['elements'][0]['duration']['text'];

    return  $dist;*/
}

?>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> -->
<!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -->
<!-- <html xmlns='http://www.w3.org/1999/xhtml' xmlns:v='urn:schemas-microsoft-com:vml'>-->
<!-- custom/loginSession_cbanner.jsp: E2.5.3-B03 [default] page=login
  =======================================================================================
  Copyright(C) 2007-2013 Glovision Techno Services, All rights reserved
  Centered image banner
  =======================================================================================
-->
<!-- meta -->
<html>
   <head>
       <meta name="author" content="Glovision Techno Services"/>
       <meta http-equiv="content-type" content='text/html; charset=UTF-8'/>
       <link rel="shortcut icon" href="../../../images/glovision.ico"/>
       <title>Glovision Techno Services</title>
<!--
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>       -->
<!--      <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=drawing"></script>  -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css"  crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"  crossorigin=""></script>


   <script type="hacker/JavaScript" hacker="enabled"></script>

<script src="jquery-1.11.1.min.js"></script>
<script src="datePicker1.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="jquery.datetimepicker.css"/>

<script src="jquery.datetimepicker.js" type="text/javascript"></script>
 <style>
.labels {
      color:  black ;
           background-color:white;
                     font-size: 10px;
                    font-weight: bold;
                               text-align: center;
                                border-radius:10px;
                                   /* width: 70px;
                                    height:20px;*/
                                         border: 1px solid  red;
                                             /*word-break: break-all;*/
                                              white-space: nowrap;
                                                 }

.leaflet-pane {
    z-index: 0;
}

 </style>
<!-- <script type="text/javascript" src="../js/googlehistory.js"></script> -->
   <style type='text/css'>
       .tablecss {
        text-align:center;
        width:100%;
        color:#232539;
        font-family:Arial,Verdana,sans-serif;
        font-size:13;
        }
    table tr:nth-child(even) {
    background-color: #e0b7b7;
}
table tr:nth-child(odd) {
   background-color:#fff;
}
table th {
    background-color: #1c1147;
    color: white;
}

   </style>
   <style>
          html { height: 100% } body { height: 100%; margin: 0; padding: 0 }

        .button {
    border: 2px solid #118cbe;
    border-radius: 5px;
    height: 22px;
    background: #118cbe;
    color: white;
    width: 230px;
    font-family: Arial,Verdana,sans-serif;
    font-size: 13;}

   </style>
   <script>
      function getCaseData(){
        var fromdate = document.getElementById('fromdate').value;
          var todate = document.getElementById('todate').value;
        var groupID = document.getElementById('groupID').value;
          var accountID = document.getElementById('accountID').value;

            window.location.href ='?fromDate='+fromdate+'&toDate='+todate+'&groupID='+groupID+"&accountID="+accountID;
  
      }

   </script>
   </head>
   <body onload="">
          <table align="center" class="BaseTable" background="#E6E6E6" class='tablecss'>
          <thead>
              <tr>
                 <td>AccountID </td>
                  <td>
                          <input type="text" id="accountID" style="width:160px"  class="button-error pure-button" value="<?php echo $accountID;?>"/>
                 </td>
                  <td>Group ID</td>
                  <td>
                          <input type="text" id="groupID" style="width:160px"  class="button-error pure-button" value="<?php echo $groupID;?>"/>
                 </td>

                   <td>From Date :</td>
                  <td><input type="text" id="fromdate" style="width:160px" class="button-error pure-button"  value="<?php echo $fromDate;?>"/></td>
                  <td>To Date :</td>
                  <td><input type="text" id="todate" style="width:160px"  class="button-error pure-button" value="<?php echo $toDate;?>"/></td>
                  <td ><input type="button" id="allZone" style="width:150px"  onclick="getCaseData()" value="SUBMIT" class="button"/><br></td>
              </tr>
         </table>
          <br>
          <center> 
        <?php echo $table;?>
         </center>
    </body>
</html>

