<?php
    set_time_limit(0);
    include 'config.php';
    include 'pdfcretor.php';
    date_default_timezone_set('Asia/Kolkata');
    $accountID=$_GET['accountID'];
    $fromDate=$_GET['fromDate'];
    $toDate=$_GET['toDate'];
    //get All Groups

     //Name of our directory

    $old = umask(0000);
mkdir("/ramana", 6640, true);
umask($old);
  
     $dir_name ='/var/www/html/my_directory';
 
   
 
    if (!file_exists($dir_name)) {
     //  mkdir($dir_name, 0777, true);
     //  echo "created";
    }
 
     //Check if the directory with the name already exists
  /*   if (!is_dir($dir_name)) {
         //Create our directory if it does not exist
          mkdir($dir_name);
          echo "Directory created";
     } */

    die();
    $groupList=getGroups($accountID);

    for($gpindx=0;$gpindx<count($groupList);$gpindx++){
         $deviceList=getVehiclePerGroup($accountID,$groupList[$gpindx]);
         for($dindx=0;$dindx<count($deviceList);$dindx++){
             /*
             $deviceID=$deviceList[$dindx];
             $eventData=array(array());
             getEventData($deviceID,$accountID,$fromDate,$toDate);
             $totalDis=0; 
             $previousTime=0;
            for($evntindx=0;$evntindx<count($eventData);$evntindx++){
                 $statusinfo="Stopped";
                 if($eventData[$evntindx][2]=="61714"){
                     $statusinfo="Moving";
                 }else if($eventData[$evntindx][2]=="61718"){
                     $statusinfo="Idle";
                 }else if($eventData[$evntindx][2]=="62467"){
                     $statusinfo="Ignition Off";
                 }else if($eventData[$evntindx][2]=="62465"){
                     $statusinfo="Ignition On";
                 }else if($eventData[$evntindx][2]=="64791"){
                     $statusinfo="Main Power OFF";
                 }else if($eventData[$evntindx][2]=="64793"){
                     $statusinfo="Main Power ON";
                 }else if($eventData[$evntindx][2]=="61968"){
                     $statusinfo="Arrived";
                 }else if($eventData[$evntindx][2]=="62000"){
                     $statusinfo="Departed";
                 }else if($eventData[$evntindx][2]=="63621"){
                     $statusinfo="Tamper";
                 }else if($eventData[$evntindx][2]=="63622"){
                     $statusinfo="Tamper Off";
                 }else if($eventData[$evntindx][2]=="63792"){
                      $statusinfo="Braking";
                 }else if($eventData[$evntindx][2]=="64787"){
                      $statusinfo="Power Fail";
                 }else if($eventData[$evntindx][2]=="64789"){
                      $statusinfo="Power Restored";
                 }else if($eventData[$evntindx][2]=="64817"){
                      $statusinfo="Connect Fail";
                 }else if($eventData[$evntindx][2]=="64818"){
                     $statusinfo="Connect Restore";
                 }

                 $totalDis=$totalDis+$eventData[$evntindx][4];
                 //time diff between event to event 
                 $duration="00:00:00";
                 if($evntindx>0){
                    $duration=TimeFormate(abs($eventData[$evntindx][10]-$previousTime));
                  }
                 $previousTime=$eventData[$evntindx][10];
                 $totalDis=$totalDis+$eventData[$evntindx][4];
                 $eventData[$evntindx][13]=$duration;
                 $eventData[$evntindx][14]=round($totalDis,2);
                 $eventData[$evntindx][15]=$statusinfo;
            }//end event data while
            $newpdf=new PdfGeneretor();
            $newpdf->pdfcreation($eventData,$deviceID,null,"Event Data OF ".$deviceID." At ".date("d-m-Y",$fromDate),"From :".date("d-m-Y",$fromDate)." To:".date("d-m-Y",$toDate));
             unset($eventData);    */
         }//end device loop
      }//end group loop


   function getEventData($vehicleID,$accountID,$fromDate,$toDate){
       global $gtsserver, $gtsusername, $gtspassword,$gtsdb,$eventData;
       $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='$vehicleID'  and timestamp between '$fromDate' and '$toDate' and latitude<>0 and longitude<>0 order by timestamp asc";  //request from web for particular vehicle

       $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error($gtsconnect));
        mysqli_select_db($gtsconnect,$gtsdb);
       $rs =mysqli_query($gtsconnect,$Query) or die ("Query error1: " . mysqli_error($gtsconnect));
       $num_rows = mysqli_num_rows($rs);
       $i=0;
       while($row = mysqli_fetch_assoc($rs)) {
        if($i==0){
               $row['distance']=0;
         }
         $eventData[$i][0]=$row['geozoneID'];
         $eventData[$i][1]=$row['deviceID'];
         $eventData[$i][2]=$row['statusCode'];
         $eventData[$i][3]=$row['time1'];
         $eventData[$i][4]=$row['distance'];
         $eventData[$i][5]=$row['speedKPH'];
         $eventData[$i][6]=$row['address'];
         $eventData[$i][7]=$row['analog0'];
         $eventData[$i][8]=$row['latitude'];
         $eventData[$i][9]=$row['longitude'];
         $eventData[$i][10]=$row['timestamp'];
         $eventData[$i][11]=findDirection($row['heading']);
         $eventData[$i][12]=$row['heading'];
         $endlatlong=round($row['latitude'],5).'-'.round($row['longitude'],5);
         if($i>0 && $row['latitude']!= 0 && $row['longitude']!=0 && $eventData[$i-1][8]!=0 && $eventData[$i-1][9]!=0) {

                 $eventtoeventdistance=distance1($row['latitude'],$row['longitude'], $eventData[$i-1][8], $eventData[$i-1][9]);
                 $difftimes=abs(strtotime($eventData[$i][3])-strtotime($eventData[$i-1][3]));
                 $maxDistanceTravelledperMint=2;//max km travelled per mint
                 $calculatedDistenceTravelledperMint=intval($eventtoeventdistance)/$difftimes;
                 if(is_nan($eventtoeventdistance) || ($eventtoeventdistance/$difftimes>0.025)){//if distnace greater than 2 km with 5 minits then distnace=0 bzc drift point in 
                    $eventData[$i][4]=0;
                 //   $i++;
                }else{
                   $eventData[$i][4]=$eventtoeventdistance;
                   $travelDistance=$travelDistance+$eventtoeventdistance;
                   $i++;
               }

              if(is_nan($eventData[$i][4])){
                 $data[$indx][7]=0;
              }
                }
         if($i==0){$i++;}

        //   $i++;
       }
       mysqli_close($gtsconnect);
}


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 findDirection($degree){
  if($degree>=0 && $degree<10){return 'N';}
  else if($degree>10 && $degree<80){return 'NE';}

  else if($degree>=80 && $degree<100){return 'E';}
  else if($degree>=100 && $degree<170){return 'SE';}
  else if($degree>=170 && $degree<190){return 'S';}
  else if($degree>=190 && $degree<260){return 'SW';}
  else if($degree>=260 && $degree<280){return 'W';}
  else if($degree>=280 && $degree<350){return 'NW';}
  else if($degree>=350 && $degree<360){return 'N';}



}


function TimeFormate($timeDiff){
        $hours=0;
        $min=0;
        $sec=0;
        if ($timeDiff==0) {
            return 0;
        }
        if($timeDiff>=3600){
                $hours=intval($timeDiff/(60*60));
                $tempmin=$timeDiff%(60*60);
                $result=TimeFormate($tempmin);
                return $hours."Hr :".$result;
        }else if($timeDiff>=60){
                 $min=intval($timeDiff/60);
                 $tempsec=$timeDiff%60;

                 return $min." Min :".TimeFormate($tempsec);
        }else{
             return $timeDiff." sec";
        }

}


function getGroups($accounts){
    global $gtsserver, $gtsusername, $gtspassword,$gtsdb;
    $result=array();
    $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error($gtsconnect));
    mysqli_select_db($gtsconnect,$gtsdb);
    $vehicleDetails='';
   $vehicleDetails="select DISTINCT groupID from DeviceGroup where accountID='$accounts'";
   $qry1 = mysqli_query($gtsconnect,$vehicleDetails) or die(mysqli_error($gtsconnect));
   $rowcount=0;
   while($row = mysqli_fetch_assoc($qry1)){
        $result[$rowcount]=$row['groupID'];
        $rowcount++;
   }
   if($rowcount==0){
       $result[$rowcount]='';
   }
   mysqli_close($gtsconnect);
   return $result;

}

function getVehiclePerGroup($accountID,$groupID){
    global $gtsserver, $gtsusername, $gtspassword,$gtsdb;
    $result=array();
    $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error($gtsconnect));
    mysqli_select_db($gtsconnect,$gtsdb);
    $vehicleDetails='';
   $vehicleDetails="select DISTINCT deviceID from DeviceList where accountID='$accountID' and groupID='$groupID' limit 1";
   $qry1 = mysqli_query($gtsconnect,$vehicleDetails) or die(mysqli_error($gtsconnect));
   $rowcount=0;
   while($row = mysqli_fetch_assoc($qry1)){
        $result[$rowcount]=$row['deviceID'];
        $rowcount++;
   }
   if($rowcount==0){
       $result[$rowcount]='';
   }
   mysqli_close($gtsconnect);
   return $result;

}



?>

