<?php
    date_default_timezone_set('Asia/Kolkata');
    include 'Mail.php'; 

   session_start();
   $_SESSION["logintime"]=time();


    $fromDate=strtotime($_GET['fromDate']);
    $toDate=strtotime($_GET['toDate']);



      $offroadlist=[];
    $filename = "../../UP108102DataAnalysis/offroad-".strtolower(date("dmY",$fromDate)).".csv";

    if (!file_exists($filename)) {
        $filename="../../UP108102DataAnalysis/offroad.csv";
    }
    if(($h = fopen($filename, "r")) !== FALSE) {
        while (($data = fgetcsv($h, 1000, ",")) !== FALSE) {
        $offroadlist[] = strtolower($data[0]);
        }
        fclose($h);
    }

    //cron urlhttp://up108west.glovision.co/upmergeddashboard/php/DailyAnalysisReportCron.php?vehicleID=selectall&accountID=gvk-up-102&userID=admin&group=selectall
    /*
        ini_set('display_errors', 1);
        ini_set('log_errors', 1);
        ini_set('error_log', dirname(__FILE__) . '/usr/local/apache/logs/error_log.txt');
        error_reporting(E_ALL);
        error_reporting(0);
    */
    set_time_limit(0);
    include 'config.php';
    require_once('CheckGroupInServer.php');
    $accountID=$_GET['accountID'];
    $group1= $_GET['group'];
    $deviceID=$_GET['vehicleID'];
    $server=$_GET['server'];


  
   $reporttype=$_GET['reporttype'];
    $statusType=$_GET['statusType'];
    $gaptype=$_GET['gaptype'];
    $croneRequest="no";

    $gapstarttime=$_GET['gapstarttime']*60;
    $mintime=$_GET['mintime']*60*60;


    if($reporttype=="excel"){
    header('Cache-control: no-cache,must revalidate');
    header('Content-type: application/json');
    header("Access-Control-Allow-Origin: *");
    header("Content-type: application/vnd.ms-excel");
    header("Content-Disposition: attachment;Filename=GPS Analysis Report".$accountID."_".date('d-m-Y',$fromDate).".xls");
    }


    $table1="<!DOCTYPE HTML>
    <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>
    <link rel='stylesheet' href='style.css' />
    </head>
     <style type='text/css'>
           .myTable { background-color:white;border-collapse:collapse; }
           .myTable th { background-color:#668aa9;color:white; }
           .myTable td, .myTable th { padding:5px;border:1px solid #000; }

         .foo {
  float: left;
  width: 400px;
  height: 20px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}


.pink {
  background: pink;
}

.blue {
  background:#8EBCEE;
}

.lightblue {
  background:#D1EEEE;
}
.lightgreen{
  background: #9CBA7F;
}     

.mediumgreen{
  background: #659D32;
} 
.green{
   background:#1F5927;
}
      </style>
    <body>
    <center><h3> Graphycal Analysis of ".strtoupper($accountID)." ".strtoupper($server)." From ".date('d-m-Y H:i',$fromDate)." To".date('d-m-Y H:i',$toDate)."</h3>
     <div style='text-align: center;'>
   <table > 
    <tr> <td class='foo lightgreen' bgcolor='#9CBA7F'>Data restored in ".$_GET['mintime']." hours vehicle not was moving</td> <td class='foo green' bgcolor='#1F5927'> Dark Green no gap</td> <td class='foo mediumgreen' bgcolor='#659D32'> Data restored more than ".$_GET['mintime']." hours vehicle was not moving</td> <td class='foo lightblue' bgcolor='#D1EEEE'> Data restored in ".$_GET['mintime']." hours vehicle was moving</td> <td class='foo blue' bgcolor='#8EBCEE'> Data restored more than ".$_GET['mintime']." hours vehicle was moving</td> <td class='foo pink' bgcolor='pink'>Data not restored yet</td></tr>
     </table>
<br><br> <br><br>     
    ";

    $table="<table class='myTable'><tr style='background-color:black;color:white' bgcolor='#668aa9' color='white'><th>Account ID</th><th>Group</th><th>Device ID</th><th>SIM Status</th><th>Status</th><th>Alert</th><th>IMEI</th><th>Version</th>";

    $hourlyGapCount=array();
     for($tempTime=$fromDate;$tempTime<$toDate;$tempTime=$tempTime+3600){       
          $table .="<th>".date("H:i/d-m",$tempTime)."</th>";
           $hourlyGapCount[date("Hdm",$tempTime)]=0;
     }    
    $table .="<th>Gaps Count</th><th>Distance</th></tr>";
   $totalDeviceCount=0;


  //$accounts=array();
  if($accountID=="selectall"){
      // $accounts=["gvk-up-108","gvk-up-102","als","uptest","gvk-up-backup"];
   }else{
      $accounts=array();
       $accounts[0]=$accountID;
   }

  $sortarray=array();
    $sortarrayinfo=array();

   for($accindx=0;$accindx<count($accounts);$accindx++){
      $accountID=$accounts[$accindx];


    
    $gtsdb ="up108west";
    $gtsdb2="up108east";
    if($accountID=="gvk-up-102"){
        $gtsdb ="up102west";
        $gtsdb2="up102east";
    }
    if($accountID=="als" || $accountID=="gvk-up-backup"){
        $gtsdb ="gts";
    }if($accountID=="uptest"){
        $gtsdb ="gts";
    }




    $groupList=array();
    if($group1=="selectall"){

        if("allservers"==$server){

             if($accountID=="gvk-up-108" || $accountID=="gvk-up-102" || $accountID=="als" || $accountID=="gvk-up-backup" || $accountID=="uptest"){
                  getGroupList($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID);
            }
            if($accountID=="gvk-up-108" || $accountID=="gvk-up-102"){
                  getGroupList($gtsserver2, $gtsusername, $gtspassword,$gtsdb2,$accountID);
            }
        }else { 
            if(($accountID=="gvk-up-108" || $accountID=="gvk-up-102" || $accountID=="als" || $accountID=="gvk-up-backup" || $accountID=="uptest") && $server=="west"){
	          getGroupList($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID);
            }else if(($accountID=="gvk-up-108" || $accountID=="gvk-up-102") && $server=="east"){
                  getGroupList($gtsserver2, $gtsusername, $gtspassword,$gtsdb2,$accountID);
             }
        }
    }
    else{
        $groupList=[$group1];
    }


    // $fromDate=strtotime(date('d-M-Y',strtotime("-1 days")).' 00:00:00');
  //  $toDate=strtotime(date('d-M-Y',strtotime("-1 days")).' 23:59:59');


    

    for($gpindx=0;$gpindx<count($groupList);$gpindx++){
	$group=$groupList[$gpindx];
        if(!checkGroup($accountID,$group)){
            if($group!="selectall"){
        	if($accountID=="gvk-up-108"){
                    $gtsdb="up108east";
            	    $gtsserver=$gtsserver2;
           	    $tacserver=$tacserver2;
        	}
		else if($accountID=="gvk-up-102"){
                    $gtsdb="up102east";
           	    $gtsserver=$gtsserver2;
           	    $tacserver=$tacserver2;
        	}else{
            	    echo "something went wrong try again";
         	}
       	    }
	    else{
                echo "Please Select Group ";
                exit();
            }
	}


	$deviceArrya=array(array());
        if($deviceID=="selectall"){
            $deviceArrya=device_info($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID,$group,$deviceID);
        }else{
            $deviceArrya=device_info($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID,$group,$deviceID);
        }
    	for($devindx=0;$devindx<count($deviceArrya);$devindx++) {
            // if("up41g2831"!=strtolower($deviceArrya[$devindx][4]))continue;

             $simstatus="Single";
             if($deviceArrya[$devindx][12]!="" && $deviceArrya[$devindx][12]>0){
                 $simstatus="Dual";
              } 
              // $table .="<tr><th style='background-color:white;color:black'>".$group."</th><th style='background-color:white;color:black'>".$deviceArrya[$devindx][4]."</th><th style='background-color:white;color:black'>".$simstatus."</th><th style='background-color:white;color:black'>".$status."</th>";
              $gapcount=0;
              $lateventTime=0;
              $alert="";
              $tabletmp=""; 
              $tatalvehicleeventcount=0;
              $totaldis=0;

         
              $hourlyGapCounttemp=array();
              for($tempTime=$fromDate;$tempTime<$toDate;$tempTime=$tempTime+3600){
                      $hourlyGapCounttemp[date("Hdm",$tempTime)]=0;
              }


              for($tempTime=$fromDate;$tempTime<$toDate;$tempTime=$tempTime+3600){
                if(time()>$tempTime){ 
                 $gpsGap1=findGapsForVehicles($accountID,$deviceArrya[$devindx][4],$tempTime,$tempTime+3600);
                 $gpsGap=$gpsGap1[0];
                 $eventStatus=$gpsGap1[1];
                 $color="";
                 if($gpsGap==="dataloss"){
                       $color="white";
                       $gapcount++;
                  }else if($gpsGap==="nodata"){
                       $color="pink";
                       $gapcount++;
                       $hourlyGapCounttemp[date("Hdm",$tempTime)]=$hourlyGapCounttemp[date("Hdm",$tempTime)]+1;
                  }else if(intval($gpsGap)==0){
                       $color="#1F5927";
                        $gpsGap="";
                  } else if(intval($gpsGap)>$gapstarttime && intval($gpsGap)<$mintime){
                       $hourlyGapCounttemp[date("Hdm",$tempTime)]=$hourlyGapCounttemp[date("Hdm",$tempTime)]+1;
                       if($eventStatus=="61714")
                           $color="#D1EEEE";
                       else
                          $color="#9CBA7F";
                        $gapcount++;
                       $gpsGap=secondsToTimeFormate($gpsGap);
                  } else if(intval($gpsGap)>$mintime){
                       $hourlyGapCounttemp[date("Hdm",$tempTime)]=$hourlyGapCounttemp[date("Hdm",$tempTime)]+1;

                       if($eventStatus=="61714")
                           $color="#8EBCEE";
                       else
                          $color="#659D32";
                       $gapcount++;
                       $gpsGap=secondsToTimeFormate($gpsGap);
                  }


                    if($gpsGap==="nodata"){
                           $tabletmp .="<td style='background-color:".$color."' bgcolor='".$color."' >No data yet</td>";
                    } else{
                          $tabletmp .="<td style='background-color:".$color."' bgcolor='".$color."' >".$gpsGap."</td>";
                     }
                }else{
                    $tabletmp .="<td style='background-color:'white'></td>";
                }
              }


             $colorfont="black";
            $bgcolor="white";
             $status="Offline";
           // $diffeventtime=abs($lateventTime-time());


          /*
            $diffeventtime=abs($deviceArrya[$devindx][6]-time());
            if($diffeventtime<600) $status="Online";
            else if($diffeventtime>=600 && $diffeventtime<86400) $status="Online";
            else{ $status="Offline";$colorfont="red";
               $bgcolor="#D1D4D6"; }


            */
            if($tatalvehicleeventcount==0){
                $status="Offline";$colorfont="red";
               $bgcolor="#D1D4D6";
            }else{
                $status="Online";
           } 
            if(in_array(strtolower($deviceArrya[$devindx][4]),$offroadlist)){
               $status="Offroad";
               $colorfont="red";
               $bgcolor="#D1D4D6";
            }

            if($status=="Online"){
                 $totalDeviceCount++;
               for($tempTime=$fromDate;$tempTime<$toDate;$tempTime=$tempTime+3600){
                         $hourlyGapCount[date("Hdm",$tempTime)]=$hourlyGapCount[date("Hdm",$tempTime)]+$hourlyGapCounttemp[date("Hdm",$tempTime)];
                }
 

            }
  
            if(($statusType==$status || $statusType=="selectall") && $gaptype=="selectall" && $deviceArrya[$devindx][4]!="" ){                           
             //   $table .="<tr><th style='background-color:".$bgcolor.";color:black'>".$group."</th><th style='background-color:".$bgcolor.";color:black'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."'>".$status."</th><th style='background-color:".$bgcolor.";color:black'>".$alert."</th>".$tabletmp."<td>".$gapcount."</td></tr>";
              // $table .="<td>".$gapcount."</td></tr>";     
                 $sortarray[strtolower($deviceArrya[$devindx][4])]=$gapcount;
                 $sortarrayinfo[strtolower($deviceArrya[$devindx][4])]="<tr><th>".$accountID."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$group."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."' bgcolor='".$bgcolor."' color='".$colorfont."'><font color='".$colorfont."'>".$status."</font></th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$alert."</th><td>".$deviceArrya[$devindx][11]."</td><td>".$deviceArrya[$devindx][13]."</td>".$tabletmp."<td>".$gapcount."</td><td>".round($totaldis,2)."</td></tr>";

            }else if(($statusType==$status || $statusType=="selectall") && $gaptype=="nogap"  && $gapcount==0 && $deviceArrya[$devindx][4]!=""){

               //   $table .="<tr><th style='background-color:".$bgcolor.";color:black'>".$group."</th><th style='background-color:white;color:black'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."'>".$status."</th><th style='background-color:".$bgcolor.";color:black'>".$alert."</th>".$tabletmp."<td>".$gapcount."</td></tr>";;
                 // $table .="<td>".$gapcount."</td></tr>";
                   $sortarray[strtolower($deviceArrya[$devindx][4])]=$gapcount;
                 $sortarrayinfo[strtolower($deviceArrya[$devindx][4])]="<tr><th>".$accountID."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$group."</th><th style='background-color:white;color:black' bgcolor='".$bgcolor."'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."' bgcolor='".$bgcolor."' color='".$colorfont."'>".$status."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$alert."</th><td>".$deviceArrya[$devindx][11]."</td><td>".$deviceArrya[$devindx][13]."</td>".$tabletmp."<td>".$gapcount."</td><td>".round($totaldis,2)."</td></tr>";
   
            }else if(($statusType==$status || $statusType=="selectall") && $gaptype=="gap"  && $gapcount>0 && $deviceArrya[$devindx][4]!=""){

                      $sortarray[strtolower($deviceArrya[$devindx][4])]=$gapcount;
                      $sortarrayinfo[strtolower($deviceArrya[$devindx][4])]="<tr><th>".$accountID."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$group."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."' bgcolor='".$bgcolor."' color='".$colorfont."'>".$status."</th><th style='background-color:".$bgcolor.";color:black' bgcolor='".$bgcolor."'>".$alert."</th><td>".$deviceArrya[$devindx][11]."</td><td>".$deviceArrya[$devindx][13]."</td>".$tabletmp."<td>".$gapcount."</td><td>".round($totaldis,2)."</td></tr>";

                 //    $table .="<tr><th style='background-color:".$bgcolor.";color:black'>".$group."</th><th style='background-color:".$bgcolor.";color:black'>".$deviceArrya[$devindx][4]."</th><th style='background-color:".$bgcolor.";color:black'>".$simstatus."</th><th style='background-color:".$bgcolor.";color:".$colorfont."'>".$status."</th><th style='background-color:".$bgcolor.";color:black'>".$alert."</th>".$tabletmp."<td>".$gapcount."</td></tr>";
                  // $table .="<td>".$gapcount."</td></tr>";

           }
        } //end divice loop
   }//end group loop



}//account loop 

   $offliners="";

   $offroadrs="";
   $onliners="";
   $alertsrs=""; 
  asort($sortarray);
    foreach($sortarray as $x=>$x_value)
    {
          
            if(strpos($sortarrayinfo[$x],"Connect Fail")>0 || strpos($sortarrayinfo[$x],"Power Fail")>0 || strpos($sortarrayinfo[$x],"Tamper")>0 || strpos($sortarrayinfo[$x],"Main Power OFF")>0 || strpos($sortarrayinfo[$x],"Low voltage")>0){
                  $alertsrs .=$sortarrayinfo[$x];
             }else if(strpos($sortarrayinfo[$x],"Offline")>0){
                 $offliners .=$sortarrayinfo[$x];
             }else if(strpos($sortarrayinfo[$x],"Offroad")>0){
                  $offroadrs .=$sortarrayinfo[$x];
             }else if(strpos($sortarrayinfo[$x],"Online")>0){
                  $onliners .=$sortarrayinfo[$x];
             }
         //  $table .=$sortarrayinfo[$x];
    }

     $firstrow="<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>";

    for($tempTime=$fromDate;$tempTime<$toDate;$tempTime=$tempTime+3600){
          $firstrow .="<td>".round(($hourlyGapCount[date("Hdm",$tempTime)]/$totalDeviceCount)*100,0)."%</td>";
        //$firstrow .="<td>".$hourlyGapCount[date("Hdm",$tempTime)]."</td>";
     }
     $firstrow .="<td></td><td></td></tr>";
    
  //  $table1 =$table1.$table.$offliners.$offroadrs.$alertsrs.$onliners."</table></center></body></html>";
     $table1 =$table1.$table.$firstrow.$onliners.$alertsrs.$offroadrs.$offliners."</table></center></body></html>";
    echo $table1;


//echo $table;
 $mailperAccount=array();
//$mailperAccount[0]="pavan@glovision.co";
//$mailperAccount[1]="rajuyadati@glovision.co";
// $mailperAccount[0]="ramana@glovision.co";
//mailSendToAccount($mailperAccount,$table1,"Graphycal"," Analysis Report");


function mailSendToAccount($mailperAccount,$totalReport,$accountID,$reportType){
if ($totalReport!=""){
    $from = " Glovision <support@glovision.co>";
    $host ="mail.glovision.co";
    $username = "alerts@glovision.co";
    $password = 'Gl0v1$ion12';

    error_log(count($mailperAccount).' no accounts');
    for ($mailIndx=0;$mailIndx<count($mailperAccount);$mailIndx++){
        $to ="Recipient <".$mailperAccount[$mailIndx].">";
        $headers = array ('MIME-Version' => '1.0rn',
        'Content-Type' => "text/html; charset=ISO-8859-1rn",
        'From' => $from,
        'To' => $to,
        'Subject' =>$accountID.' '.$reportType
        );
        error_log('1');
        $smtp = Mail::factory('smtp',
        array ('host' => $host,
           'auth' => true,
           'username' => $username,
           'password' => $password));

        $mail = $smtp->send($to,$headers,$totalReport);
        error_log('3');
        if (PEAR::isError($mail)) {
           error_log('222222222222222');
           echo("<p>" . $mail->getMessage() . "</p>");
        } else {
          error_log('ddddddddddd');
           echo("<p>Message successfully sent!</p>");
        }
    }
}
}

function findGapsForVehicles($accountID,$deviceID,$fromDate,$toDate){
global $gtsserver, $gtsusername, $gtspassword,$gtsdb,$lateventTime,$alert,$tatalvehicleeventcount,$totaldis,$gapstarttime;
   //find Gap inbet ween ranges
          $sql = "Select batteryVolts,analog3,timestamp,accountID,odometerKM,deviceID,address,from_unixtime( creationTime, '%d-%m-%Y %H:%i:%s' ) as time1,statusCode,latitude,longitude,geozoneID,speedKPH,creationTime from EventData where accountID='$accountID' and deviceID='".$deviceID."'  and timestamp BETWEEN $fromDate AND $toDate and latitude<>0 and longitude<>0 order by timestamp";
      
         $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database1 : " . mysqli_error($gtsconnect));
         mysqli_select_db($gtsconnect, $gtsdb);
        $qry_result = mysqli_query($gtsconnect, $sql) or die(mysqli_error());
        $data=array(array());
         $indx=0;
        
        while($row = mysqli_fetch_assoc($qry_result)) {
          if($row['latitude']!= 0 && $row['longitude']!=0){
               $data[$indx][0]=$row['creationTime'];
               $data[$indx][1]=$row['timestamp'];
               $data[$indx][2]=$row['statusCode'];
               $data[$indx][3]=$row['latitude'];
               $data[$indx][4]=$row['longitude'];

              $data[$indx][5]=$row['odometerKM'];
               //echo date('d-m-Y H:i:s',$row['creationTime'])."<br>";
               $lateventTime=$row['timestamp'];
               $blevel=$row['batteryVolts'];
               if(floatval($blevel)<=3.6 && floatval($blevel)>0){
                   $alert="Low voltage";
                     //echo "LOW  ".$row['timestamp']."  ".$row['batteryVolts'];
               }
              if($alert!="Low voltage"){
                  if($row['statusCode']=="64791"){
                      $alert="Main Power OFF";
                  }else if($row['statusCode']=="63621"){
                      $alert="Tamper";
                  }else if($row['statusCode']=="64787"){
                      $alert="Power Fail";
                  }else if($row['statusCode']=="64817"){
                        $alert="Connect Fail";
                  }
              }
             if($indx>0) {
                   $eventtoeventdistance=distance1($row['latitude'],$row['longitude'], $data[$indx-1][3], $data[$indx-1][4]);
                   $difftimes=abs(($data[$indx][1])-($data[$indx-1][1]));
                   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;
                       $indx++;
                   }
             }else{
                  $indx++;
             }
           }
        }
     $tatalvehicleeventcount=$tatalvehicleeventcount+$indx;
       $findGap="no";
      $totalDiffTime=0;
       $eventstatus=0;
       for($dinx=1;$dinx<count($data);$dinx++){
          $diff=abs($data[$dinx-1][0]-$data[$dinx][0]);
          $diff2=abs($data[$dinx][1]-$data[$dinx][1]);
           if($diff>$gapstarttime && $diff2<$gapstarttime){//30 mints
                 // echo $deviceID." ".$diff."  ".date('d-m-Y H:i:s',$data[$dinx-1][8])." ".date('d-m-Y H:i:s',$data[$dinx][8])."<br>";
                   $findGap="yes";
                   $totalDiffTime=$totalDiffTime+$diff;

                   $odo=calculatedistance($accoutID,$deviceID,$data[$dinx][1],$data[$dinx][0]);
                 echo "Start".$data[$dinx][5]. "ODO:".$odo."<br>";
                  if($odo>0){
                     $eventstatus="61714";
                  }else{
                      $eventstatus=0;
                  }
                   break;
           }else if ( $diff>$gapstarttime && $diff2>($gapstarttime-100)){
               //echo $data[$dinx][1] ."  ".$data[$dinx][0]. "  ".$data[$dinx-1][0]."  ";
               // $odo=calculatedistance($data,$data[$dinx][0]);
                 $odo=calculatedistance($accoutID,$deviceID,$data[$dinx][1],$data[$dinx][0]);
                echo "Start".$data[$dinx][5]."ODO:".$odo."<br>";
               if($odo>0){
                     $eventstatus="61714";
                  }else{
                      $eventstatus=0;
                  }

            //   $eventstatus=$data[$dinx-1][2];
               $totalDiffTime="dataloss";
               break;
          }
       }
   
      if(count($data)>=2){
          if(abs($fromDate-$data[0][0])>$gapstarttime){
              $odo=calculatedistance($accoutID,$deviceID,$data,$fromDate,$data[0][0]);
           //  echo date('d-m-Y H:i:s',$data[0][0])."  ".date('d-m-Y H:i:s',$data[0][1])."<br>";
             echo "Start".$data[0][5]."ODO:".$odo."<br>";
             if($totalDiffTime==0){
                if($odo>0){
                     $eventstatus="61714";
                  }else{
                      $eventstatus=0;
                  }
                $totalDiffTime = $totalDiffTime+abs($fromDate-$data[0][0]);
                $findGap="yes";
            }
          }
           if(abs($toDate-$data[count($data)-1][0])>$gapstarttime){
             if($totalDiffTime==0 && time()>=$toDate){
                $eventstatus=$data[count($data)-1][2];
                $odo=calculatedistance($accoutID,$deviceID,$data,$toDate,$data[count($data)-1][0]);
               // $odo=calculatedistance($data,$data[count($data)-1][0]);
                 if($odo>0){
                     $eventstatus="61714";
                  }else{
                      $eventstatus=0;
                  }

                  echo "Start".$data[$dinx][5]."ODO:".$odo."<br>";
                $totalDiffTime=$totalDiffTime+abs($toDate-$data[count($data)-1][0]);
                $findGap="yes";
             }
          }
      }
 
      if(count($data)<2){
        //  echo "'".$deviceID."',";
          $findGap="nodata";
          $totalDiffTime="nodata";
       }   
 mysqli_close($gtsconnect);
  $res=[$totalDiffTime,$eventstatus];
 return $res;
}

    function calculatedistance($accountID,$deviceID,$fromDate,$toDate){

            global $gtsserver, $gtsusername, $gtspassword,$gtsdb,$lateventTime,$alert,$tatalvehicleeventcount,$totaldis,$gapstarttime;
   //find Gap inbet ween ranges
          $sql = "Select batteryVolts,analog3,timestamp,accountID,odometerKM,deviceID,address,from_unixtime( creationTime, '%d-%m-%Y %H:%i:%s' ) as time1,statusCode,latitude,longitude,geozoneID,speedKPH,creationTime from EventData where accountID='$accountID' and deviceID='".$deviceID."'  and timestamp BETWEEN $fromDate AND $toDate and latitude<>0 and longitude<>0 order by timestamp";

         $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database1 : " . mysqli_error($gtsconnect));
         mysqli_select_db($gtsconnect, $gtsdb);
        $qry_result = mysqli_query($gtsconnect, $sql) or die(mysqli_error());

         $startodo=0;
         $endodo=0;
         $indx=0;
         while($row = mysqli_fetch_assoc($qry_result)) {
             $endodo=$row["odometerKM"];
             if($indx==0){
                $startodo=$row["odometerKM"];
              }     

             $indx++;
           }
          mysqli_close($gtsconnect);
        $diffodo=($endodo-$startodo);
        /*
         for($dinx=1;$dinx<count($data);$dinx++){
            echo date('d-m-Y H:i:s',$data[$dinx][1])."select<br>";
              if($data[$dinx][1]>$time){
                   echo date('d-m-Y H:i:s',$data[$dinx][1])."selectd";
                  return $data[$dinx][5];
                break;
             }
          }
        return $data[count($data)-1][5];
 
         */
       return $diffodo;
    }
    function timeDiff($fromTime,$toTime)
    {
        $toTime=strtotime($toTime);
        //error_log($toTime.'totimee222');
        $fromTime=strtotime($fromTime);
      //  error_log($fromTime.'fromtime2222');
        $seconds  = $toTime - $fromTime;
        //$minutes   = round(($interval / 60) % 60);
        $minutes = $seconds;
     // error_log($minutes . "diff in min");
        return $minutes;

    }
    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 secondsToTimeFormate($TotalAcOnTime){
	$hours=0;
	$min=0;
	//$sec=0;
        if ($TotalAcOnTime==0) {
            return 0;
        }
	if($TotalAcOnTime>=3600){
		$hours=intval($TotalAcOnTime/(60*60));
		$tempmin=$TotalAcOnTime%(60*60);
		$result=secondsToTimeFormate($tempmin);
		return $hours."Hr :".$result;
	}else if($TotalAcOnTime>=60){
		 $min=intval($TotalAcOnTime/60);
		// $tempsec=$TotalAcOnTime%60;
		 return $min." Mins";
		// return $min." Min :".secondsToTimeFormate($tempsec);
	}else{
	     return $TotalAcOnTime." sec";	
	}
	
    }

 



function device_info($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accounts,$userID,$vehicleID){
global $server; 
   $result=array(array());


   $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error());
   mysqli_select_db($gtsconnect,$gtsdb);
  // $vehicleDetails="select vehicleModel,vehicleMake,lastValidLatitude,lastValidLongitude,deviceID from Device where accountID='$accounts'";
/*   $vehicleDetails="select a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,	lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,a.simPhoneNumber as contactPhone,a.description as description  from Device a,DeviceList b where a.accountID='$accounts' and b.groupID='$userID' and b.accountID='$accounts' and a.deviceID=b.deviceID ";
   if($userID=="admin" || $userID=="administrator"  || $userID=="lucknowit" || $userID=="selectall"){
   $vehicleDetails="select a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,	lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,a.simPhoneNumber as contactPhone,a.description as description  from Device a,DeviceList b where a.accountID='$accounts' and b.accountID='$accounts' and a.deviceID=b.deviceID ";
   }
   if($vehicleID!="selectall"){
      $vehicleDetails="select a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,	lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,a.simPhoneNumber as contactPhone,a.description as description from Device a,DeviceList b where a.accountID='$accounts' and b.groupID='$userID' and b.accountID='$accounts' and a.deviceID=b.deviceID and b.deviceID='$vehicleID' and a.deviceID='$vehicleID' ";
   } 
 */
   // if(strpos($accounts,"gvk")>-1 || strpos($accounts,"gog")>-1 ){



      $vehicleDetails="select  a.equipmentType,a.serialNumber,a.uniqueID,a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,c.contactPhone as contactPhone,a.description as description  from Device a,DeviceList b,Driver c where a.accountID='$accounts' and b.groupID='$userID' and b.accountID='$accounts' and a.deviceID=b.deviceID and a.deviceID=c.deviceID and c.accountID=a.accountID and a.isActive='1' order by a.deviceID desc";
   if($userID=="admin" || $userID=="administrator" || $userID=="lucknowit" || $userID=="selectall"){
   $vehicleDetails="select a.equipmentType,a.serialNumber,a.uniqueID,a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,c.contactPhone as contactPhone,a.description as description  from Device a,DeviceList b,Driver c where a.accountID='$accounts' and b.accountID='$accounts' and a.deviceID=b.deviceID and a.deviceID=c.deviceID and c.accountID=a.accountID and a.isActive='1' order by a.deviceID desc";
   }
   if($vehicleID!="selectall"){
      $vehicleDetails="select a.equipmentType,a.serialNumber,a.uniqueID,a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,c.contactPhone as contactPhone,a.description as description from Device a,DeviceList b,Driver c where a.accountID='$accounts' and b.groupID='$userID' and b.accountID='$accounts' and a.deviceID=b.deviceID and b.deviceID='$vehicleID' and a.deviceID='$vehicleID' and a.deviceID=c.deviceID and c.accountID=a.accountID and a.isActive='1' order by a.deviceID desc";
   } 
 


  if($server=="allservers"){
      //   echo $vehicleID."  ====";
       $vehicleID=str_replace(' ', '', $vehicleID);
       $vehicleIDs=explode(",",$vehicleID);
       $vehicleslist="'".implode("','",$vehicleIDs)."'";
          $vehicleDetails="select a.equipmentType,a.serialNumber,a.uniqueID,a.vehicleModel as vehicleModel,a.vehicleMake as vehicleMake,a.lastValidLatitude as lastValidLatitude,a.lastValidLongitude as lastValidLongitude,a.deviceID as deviceID,a.imeiNumber as imeinumber,lastEventTimestamp,a.simPhoneNumber as simPhoneNumber,b.groupID as groupID,c.contactPhone as contactPhone,a.description as description from Device a,DeviceList b,Driver c where a.accountID='$accounts' and b.groupID='$userID' and b.accountID='$accounts' and a.deviceID=b.deviceID and b.deviceID in ($vehicleslist) and a.deviceID=c.deviceID and c.accountID=a.accountID and a.isActive='1' order by a.deviceID desc";


   }
        
   // }
  
 
  //echo $vehicleDetails."<br>"; 
   
  // error_log($vehicleDetails);
   $qry1 = mysqli_query($gtsconnect,$vehicleDetails) or die(mysqli_error());
   $rowcount=0;
   error_log('Devicessssss');
   while($row = mysqli_fetch_assoc($qry1)){
        $result[$rowcount][0]=$row['vehicleMake'];
        $result[$rowcount][1]=$row['vehicleModel'];
        $result[$rowcount][2]=$row['lastValidLatitude'];
        $result[$rowcount][3]=$row['lastValidLongitude'];
        $result[$rowcount][4]=$row['deviceID'];
         $result[$rowcount][5]=$row['imeinumber'];
        $result[$rowcount][6]=$row['lastEventTimestamp'];
        $result[$rowcount][7]=$row['simPhoneNumber'];
        $result[$rowcount][8]=$row['groupID'];
        $result[$rowcount][9]=$row['contactPhone'];
         $result[$rowcount][10]=$row['description'];
        $result[$rowcount][11]=$row['uniqueID'];
        $result[$rowcount][12]=$row['serialNumber'];
        $result[$rowcount][13]=$row['equipmentType'];
      // echo $result[$rowcount][4].'  '. $result[$rowcount][7].'<br>';
        $rowcount++;
        
   }
   mysqli_close($gtsconnect);
   return $result;
}

function getMails($tacserver,$tacusername,$tacpassword,$tacdb,$accountId,$desc,$group){
$tacconnect = mysqli_connect($tacserver, $tacusername, $tacpassword) or die ("Unable to connect to the database: " . mysqli_error());
mysqli_select_db($tacdb, $tacconnect);

$query1 = "SELECT DISTINCT emailaddress FROM email WHERE accountID ='$accountId' and description='$desc' and groupID='$group'";

error_log($query1);
$qry_result = mysqli_query($query1) or die(mysqli_error());

$mails=Array();
$i=0;

 while($row = mysqli_fetch_assoc($qry_result))
  {
  
    $mails[$i++]= $row['emailaddress'];
     //echo  $row['emailaddress'];    
        
                                           
  }
mysqli_close($tacconnect);
return $mails;
}


function saveDistanceIdleReport($tacserver,$tacusername,$tacpassword,$tacdb,$accountID, $deviceID, $groupID, $baseLocation, $crewNumber, $idleLocations, $idleTime, $startTime, $startLocation, $travelledDistance, $timeStamp, $endTime, $endLocation, $route,$District){
$tacconnect = mysqli_connect($tacserver, $tacusername, $tacpassword) or die ("Unable to connect to the database: " . mysqli_error());
mysqli_select_db($tacdb, $tacconnect);
$epochtimestamp=strtotime($timeStamp);
$uniqueID=$epochtimestamp.$deviceID;
$query1 = "INSERT INTO distanceIdleReport (accountID, deviceID, groupID, baseLocation, crewNumber, idleLocations, idleTime, startTime, startLocation, travelledDistance, timeStamp, endTime, endLocation, route,District,uniqueID) VALUES ('$accountID', '$deviceID', '$groupID', '$baseLocation', '$crewNumber', '$idleLocations', '$idleTime', '$startTime', '$startLocation', '$travelledDistance', '$epochtimestamp', '$endTime', '$endLocation','$route','$District','$uniqueID') ON DUPLICATE KEY UPDATE  idleLocations='$idleLocations' , idleTime='$idleTime' , startTime='$startTime' , startLocation='$startLocation' , travelledDistance='$travelledDistance' ,endTime='$endTime' ,endLocation='$endLocation' , route='$route' ";

error_log($query1);
$qry_result = mysqli_query($query1) or die(mysqli_error());

}

function geozoneList(){
 global $gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID,$geozoneList;
$gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error());
    mysqli_select_db($gtsdb, $gtsconnect);
    $query = "SELECT geozoneID,radius,latitude1,longitude1,groupID,description,radians(latitude1) as lat1,radians(longitude1) as long1 FROM Geozone where accountID='$accountID' ";
    $qry_result = mysqli_query($query) or die(mysqli_error());
    $i=0;
    error_log($query);
    while($row = mysqli_fetch_assoc($qry_result))
    {
        $geozoneList[$i][0]= $row['geozoneID'];
        $geozoneList[$i][1]= $row['radius'];
        $geozoneList[$i][2]= $row['latitude1'];
        $geozoneList[$i][3]= $row['longitude1'];
        $geozoneList[$i][4]= $row['groupID'];
        $geozoneList[$i][5]= $row['description'];
        $geozoneList[$i][6]= $row['lat1'];
        $geozoneList[$i][7]= $row['long1'];
       // echo $geozoneList[$i][0].'<br>';
        $i++;
    }
    mysqli_close($gtsconnect);

}


function getGroupList($gtsserver, $gtsusername, $gtspassword,$gtsdb,$accountID){
    global $groupList;
    $gtsconnect = mysqli_connect($gtsserver, $gtsusername, $gtspassword) or die ("Unable to connect to the database: " . mysqli_error());
    mysqli_select_db($gtsconnect,$gtsdb);
    $query ="SELECT distinct groupID FROM DeviceGroup where accountID='$accountID' order by groupID" ;
    $qry_result = mysqli_query($gtsconnect,$query);// or die("die".mysqli_error($gtsconnect));
    $i=0;
    while($row = mysqli_fetch_assoc($qry_result))
    {
        $groupList[count($groupList)]= $row['groupID'];
 //        echo $row['groupID']."<br>";
    }
    mysqli_close($gtsconnect);
}

function zoneID($lat1,$lon1){
  global $geozoneList;
  $R = 6371;// Earth's radius in Km
  $geozoneID="";
  for($i=0;$i<count($geozoneList);$i++){
     //$redus=acos(sin($lat1)*sin($result[$i][2]) + cos($lat1)*cos($result[$i][2]) * cos($result[$i][3]-$lon1)) * $R;
     $redus=zoneDistance($lat1,$lon1,$geozoneList[$i][2],$geozoneList[$i][3]);

     if($redus<=(intval($geozoneList[$i][1]))){
          // echo "distance ".$x."   ".$geozoneList[$i][0]."  ".$geozoneList[$i][5]."  <br>";
        $geozoneID=$geozoneList[$i][5];
        break;
      }else{
        $geozoneID="";
      }
   
  }
  
   
  return $geozoneID;
}


function zoneDistance($lat1, $lon1, $lat2, $lon2) {
  $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 * 1609.344);
}



?>
