<?php
    date_default_timezone_set('Asia/Kolkata');
    include "../config.php";
    //include "../ServerSelection.php";

    $table="<html><head><style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
  </style></head><body><table><tr><th rowspan='2'>Group ID</th> <th rowspan='2' >Device ID</th><th colspan=2>
  Vehicle Location At 6AM</th><th colspan=2 >Vehicle Location At 6AM</th><th  rowspan=2 >Distance</th></tr><tr> <th>Lat</th><th>Lng</th><th>Lat</th><th>Lng</th></tr><tbody>";
    $jsonresponse='';
    $accountID=isset($_GET['accountID'])?$_GET['accountID']:"";
    $fromDate=1609201800;
    $toDate=1609216200;
    if($accountID!=""){
          $deviceList=DeviceList($accountID);
          for($i=0;$i<count($deviceList);$i++){
              $result=getCaseDistance($accountID,$deviceList[$i][0],$fromDate,$toDate);
              $res=explode('*',$result); 

              $table="<tr><td>".$deviceList[$i][0]."</td><td>".$deviceList[$i][0]."</td><td>".$res[1]."</td><td>".$res[2]."</td><td>".$res[3]."</td><td>".$res[4]."</td><td>".$res[0]."</td></tr>";
              if($i==10){
                  break;
               }
          }
            

     }

    $table=$table."</tbody></table></tbody></html>";

   echo $table; 



   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;
   $speedatstart=0;
   $speedatend=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;
    $recordscount=mysqli_num_rows($qry_result);

   $offlinestarttime=0;
   $gapstatus="";

    $requestgaptime=abs(time()-$toDate);
   $eventCheckTotime=time();
   if($requestgaptime>259200){//if request gap greater then 72 hours,than add 72 hours to case colse time (todate) 
        $eventCheckTotime=$toDate+259200;
   }
   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'];
             if($i>0) {


                  $endlat=$row['latitude'];
                  $endlong=$row['longitude'];
                  $etime=$row['timestamp'];
                  $speedatend=$row['speedKPH'];
                  $eventtoeventdistance=distance1($row['latitude'],$row['longitude'], $eventData[$i-1][0], $eventData[$i-1][1]);
                  $difftimes=abs(($eventData[$i][2])-($eventData[$i-1][2]));

                  $gapstatus="completegps";
                  if($difftimes>600){
                   //   echo $eventData[$i-1][3]."  ".$eventData[$i][3];
                    //  echo date('d-m-y H:i:s',$eventData[$i-1][2])."  ".date('d-m-y H:i:s',$eventData[$i][2]);
                      if($eventData[$i-1][3]=="61717" || $eventData[$i][3]=="61717"){//lessthan then 10 mints  is invalid offline between ignition off and ignition on,take morethen 20 mints is valid
                            if($difftimes>1200){
                                $offlineTime +=$difftimes;
                                $offlinestarttime=$eventData[$i][2];
                                //$gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);
                             }

                      }else{
                           $offlineTime +=$difftimes;
                           $offlinestarttime=$eventData[$i][2];
                           //$gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);

                      }

                  }
                  $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){$speedatstart=$row['speedKPH']; $startlat=$row['latitude'];$startlong=$row['longitude'];$stime=$row['timestamp']; $i++;}
        }
    }
   if($recordscount<2){
        $offlineTime=abs($fromDate-$toDate);
        $offlinestarttime=$fromDate;
        //echo date('d-m-y H:i:s',$fromDate);
        //$gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);
   }

   if(count($eventData)>=2){
          if(abs($fromDate-$eventData[0][2])>600){
              $difftimes=abs($fromDate-$eventData[0][2]);
              // echo "Start". date('d-m-y H:i:s',$eventData[0][2]);
               // $offlineTime +=abs($fromDate-$eventData[0][2]);            
              if($eventData[0][3]=="61717"){//lessthan then 10 mints  is invalid offline between ignition off and ignition on,take morethen 20 mints is valid
                   if($difftimes>1200){
                        $offlineTime +=$difftimes;
                        $offlinestarttime=$eventData[0][2];
                       // $gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);
                    }

               }else{
                           $offlineTime +=$difftimes;
                           $offlinestarttime=$eventData[0][2];
                           // $nowtime=$offlinestarttime+86400;;//time();
                          // $gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);

              }


          }
           if(abs($toDate-$eventData[count($eventData)-1][2])>600){
                // $offlineTime +=abs($toDate-$eventData[count($eventData)-1][2]);

                $difftimes=abs($toDate-$eventData[count($eventData)-1][2]);
                //echo "End ".date('d-m-y H:i:s',$eventData[count($eventData)-1][2]);
                // $offlineTime +=abs($fromDate-$eventData[0][2]);            
                if($eventData[count($eventData)-1][3]=="61717"){//lessthan then 10 mints  is invalid offline between ignition off and ignition on,take morethen 20 mints is valid
                      if($difftimes>1200){
                           $offlineTime +=$difftimes;
                           $offlinestarttime=$eventData[count($eventData)-1][2];
                          // $nowtime=$offlinestarttime+86400;;//time();
                          // $gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);
                       }

                 }else{
                           $offlineTime +=$difftimes;
                           $offlinestarttime=$eventData[count($eventData)-1][2];
                           //$nowtime=$offlinestarttime+86400;;//time();
                          // $gapstatus=EventCount($gtsconnect,$accountID,$deviceID,$offlinestarttime,$eventCheckTotime,$gapstatus);

                 }

          }
      }


   $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."*".$gapstatus."*".$speedatstart."*".$speedatend;
   mysqli_close($gtsconnect);
   return $resultdata;
}

   function DeviceList($accountID){
         global $gtsserver,$gtsusername,$gtspassword,$gtsdb,$LiveEventDBserver;
         $gtsconnect = mysqli_connect($LiveEventDBserver,$gtsusername, $gtspassword) or die ("Unable to connect to the database1 : " . mysqli_error($gtsconnect));
         mysqli_select_db($gtsconnect, $gtsdb);
         $sql = "Select deviceID,description from Device where accountID='$accountID' and isActive='1' order by description";
         $qry_result = mysqli_query($gtsconnect, $sql) or die(mysqli_error($gtsconnect));
         $data=array(array());
         $i=0;
         while($row = mysqli_fetch_assoc($qry_result)) {
             $data[$i][0]=$row['deviceID'];
             $data[$i][1]=$row['description'];
             $i++;
         }
         mysqli_close($gtsconnect);
         return $data;
  }

?>
