<?php
class Archive
{
    var $DB;//Переменная базы данных
    var $ArrayCars;
    var $CarName;
    var $LongitudeMovement;
    var $LatitudeMovement;
    var $AzimythMovement;
    var $AltitudeMovement;
    var $TimeMovement;
    var $SpeedMovement;
    var $CarImageArchive;
    var $CountStops;
    var $MileageArchive;
    var $EventStop;
    var $EventStopTime;
    var $EventStopCoord;
    var $EventStopDuration;
    var $EventStopImage;
    var $EventParking;
    var $EventParkingTime;
    var $EventParkingCoord;
    var $EventParkingDuration;
    var $EventParkingImage;
    var $ObjLogs;
    var $ObjTimeDate;
    
    function Archive()
    {
        include("settings.php");
        require_once("ClassMessageAndLogs.php");
        require_once("ClassLibs/ClassTimeDate.php");
        //require_once("ClassLibs/GetDistance.php");
        $this->ObjLogs=new MessageAndLogs();
        $this->ObjTimeDate=new TimeDate();
        $this->DB = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
        $this->DB->query("SET CHARSET SET utf8");
        $this->DB->query("SET NAMES 'utf8'");
    }
    
    function GetSensors($Imei) {
    	 
    	//$data = array();
    	$i = 0;
    	/* $query = "SELECT ds.`DevicePort` FROM `tms_device_sensor` ds
    	 INNER JOIN `tms_device` d ON d.`ID`= ds.`DeviceId`
    	WHERE d.`Login` = '$Imei'"; */
    	$query = "SELECT ds.`DevicePort`, st.Name, st.measure FROM `tms_device_sensor` ds
    	LEFT JOIN `tms_sensor_type` st ON st.ID = ds.`SensorTypeId`
    	INNER JOIN `tms_device` d ON d.`ID`= ds.`DeviceId`
    	WHERE d.`Login` = '$Imei'";
    	 
    	$stmt = $this->DB->prepare($query);
    	$stmt->execute();
    	$stmt->bind_result($ports, $sensorName, $measure);
    	while ($stmt->fetch()) {
    		$data[$i] = array(
    				'ports' => $ports,
    				'sensorName' => $sensorName,
    				'measure' => $measure,
    		);
    		$i++;
    	}
    	$stmt->close();
    	 
    	 
    	//foreach ($data as $SensorType) {
    	for ($i = 0; $i < count($data); $i++) {
    		$query = "SELECT `sensorValue` FROM `tms_sensordata` WHERE `DeviceLoginName`='$Imei' AND `sensorType` =". $data[$i]['ports']."
    		ORDER BY `time` DESC LIMIT 0,1";
    		$stmt = $this->DB->prepare($query);
    		$stmt->execute();
    		$stmt->bind_result($sensorValue);
    		if ($stmt->fetch()) {
    			$this->SensorValue[$Imei][] = $sensorValue;
    			$this->SensorType[$Imei][] = $data[$i]['sensorName'];
    			$this->SensorMeasure[$Imei][] = $data[$i]['measure'];
    		}
    		$stmt->close();
    	}
    	 
    	/* $Query = "SELECT SensorType, MAX(`time`), sensorValue FROM tms_sensordata
    	 WHERE DeviceLoginName='$Imei' AND TIME > SUBTIME(NOW(), '04:00:00')
    	GROUP BY SensorType";
    	$Stmt = $this->DB->prepare($Query);
    	$Stmt->execute();
    	$Stmt->bind_result($SensorType, $time, $sensorValue); */
    
    	/* while ($Stmt->fetch()) {
    	 
    	  }
    	   */
    	     
    	/* print_r($this->SensorValue);
    	print_r($this->SensorType);
    			exit; */    			 
    	}
    
    //function GetArrCarName($ClientID)
	function GetArrCarName($ClientID,$Role,$User_id)
    {
        $i=0;
        if($Role==1){
				$Query = "SELECT ci.car_name,ci.imei FROM wm_car_info ci  WHERE ci.client_id = ".$ClientID." ORDER BY ci.car_name asc";
        }else{
				$Query = "SELECT ci.car_name,ci.imei FROM wm_car_info ci INNER JOIN `wm_car_group_ref` gr ON gr.`car_id`=ci.`id` INNER JOIN `wm_cargroup_user_ref` gu ON gu.`group_id`=gr.`group_id` AND gu.`user_id`=".$User_id." WHERE ci.client_id =".$ClientID." GROUP BY ci.id ORDER BY ci.car_name ASC;";
		}
		//$Query = "SELECT ci.car_name,ci.imei FROM wm_car_info ci  WHERE ci.client_id = ".$ClientID." ORDER BY ci.car_name asc";
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($car_name,$imei);
        while ($Stmt->fetch()) 
        {
            $Cars[$i]=array('imei'=>$imei,'name_car'=>$car_name);
            $i++;
        } 
        $Stmt->close();
        $this->ArrayCars=$Cars;
    }
    
    function GetCarName($Imei)
    {
         $Query ="SELECT car_name FROM wm_car_info WHERE imei='".$Imei."'";
         $Stmt = $this->DB->prepare($Query);
         $Stmt->execute();       
         $Stmt->bind_result($CarName);
         while ($Stmt->fetch()) 
         {
            $this->CarName=$CarName;
         }
    }
    
    function GetMovementInfo($Imei,$TimeFrom,$TimeTo,$GMT,$Table)
    {
        $i=0;
        $MileageSum=0;
        $Query = "SELECT g.latitude,g.longitude,g.azimuth,ADDTIME(g.time,'0 ".$GMT.":0:0'),g.speed,g.altitude FROM  tmslogistic.".$Table." g WHERE g.time>='".$TimeFrom."' AND g.time<='".$TimeTo."' AND g.DeviceLoginName='".$Imei."'";
        $this->ObjLogs->WriteLogs("Method:GetMovementInfo; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($Latitude,$Longitude,$Azimuth,$TimeMove,$Speed,$Altitude);
        while ($Stmt->fetch()) 
        {
            
        	
        	///______________
        	
        	
        	
        	///____________________
        	$this->LatitudeMovement[]=$Latitude;
            $this->LongitudeMovement[]=$Longitude;
            $this->AzimythMovement[]=$Azimuth;
            $this->TimeMovement[]=$TimeMove;
            $this->SpeedMovement[]=$Speed;
            $this->AltitudeMovement[]=$Altitude;
            
            if (Count($this->MileageArchive)>1) 
            {
                $gps_2['lat']=$this->LatitudeMovement[$i-1];
                $gps_2['lon']=$this->LongitudeMovement[$i-1];
                $gps_2['point_elevation']=$this->AltitudeMovement[$i-1];
                $gps_1['lat']=$Latitude;
                $gps_1['lon']=$Longitude;
                $gps_1['point_elevation']=$Altitude;

                    $Mileage=get_distance_between_2_points($gps_1,$gps_2);//$this->GetMileage($Latitude,$Longitude,$this->LatitudeMovement[$i-1],$this->LongitudeMovement[$i-1]);
                    $MileageSum=$MileageSum+$Mileage;///1000;
                    $this->MileageArchive[]=Round($MileageSum/1000,2);
                 
            }
            else
            {
                $this->MileageArchive[]=0;    
            }
              /* $this->ObjLogs->WriteLogs("Method:GetMovementInfo; Number:".$i."; Coords:".$this->LongitudeMovement[$i-1].','.$this->LatitudeMovement[$i-1].'--'.$Longitude.','.$Latitude.';  Mileage:'.$this->MileageArchive[$i].';  Result:'.$Mileage,'ArchiveLog','../logs');   */
            $i++;
        } 
        $Stmt->close(); 
    }
    
	function GetMovementInfo2($Imei,$TimeFrom,$TimeTo,$GMT,$Table)
    {
        $Result=0;

		$Query = "SELECT g.latitude,g.longitude,g.azimuth,ADDTIME(g.time,'0 ".$GMT.":0:0'),g.speed,g.altitude,g.Distance FROM ".$Table." g WHERE g.time>='".$TimeFrom."' AND g.time<='".$TimeTo."' AND g.DeviceLoginName='".$Imei."'";
        $this->ObjLogs->WriteLogs("Method:GetMovementInfo; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($Latitude,$Longitude,$Azimuth,$TimeMove,$Speed,$Altitude,$Distance);
        while ($Stmt->fetch()) 
        {
			

			$this->LatitudeMovement[]=$Latitude;
            $this->LongitudeMovement[]=$Longitude;
            $this->AzimythMovement[]=$Azimuth;
            $this->TimeMovement[]=$TimeMove;
            $this->SpeedMovement[]=$Speed;
            $this->AltitudeMovement[]=$Altitude;

				$Result =  $Result + $Distance;
				$this->MileageArchive[] = Round($Result/1000,2);
			
        }
		//$this->MileageArchive[] = Round($Result/1000,2);
		
        $Stmt->close();    
    }
	
    function GetImageByAzimuth($Image,$Azimuth)
    {
        $i=0;
        $this->ObjLogs->WriteLogs("CountAzimuth:".count($Azimuth),'ArchiveLog','../logs'); 
        while($i<count($Azimuth))
        {
            $Result=(floor($Azimuth[$i]/10))*10;
            $this->CarImageArchive[]=str_replace('0_',$Result.'_',$Image);
            $i++;
        }  
    }
    
    function GetCountStops($Imei,$TimeFrom,$TimeTo)
    {
        $Query = "SELECT COUNT(e.id) FROM tms_events e WHERE e.date>='".$TimeFrom."' AND e.date<='".$TimeTo."' AND e.DeviceLoginName='".$Imei."' AND e.EventType=7";
        $this->ObjLogs->WriteLogs("Method:GetCountStops; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($CountStops);
        while ($Stmt->fetch()) 
        {
            $this->CountStops=$CountStops;
        } 
        $Stmt->close();            
    }
    
    function GetMileage($LongitudeFrom,$LatitudeFrom,$LongitudeTo,$LatitudeTo)
    {
        
        //$ResLon=$LongitudeTo-$LatitudeFrom;
        //$ResLon=$ResLon*
        /*$X1 = $LongitudeFrom;
        $Y1 = $LatitudeFrom;
        $X2 = $LongitudeTo;
        $Y2 = $LatitudeTo;
        $dLat1InRad = $Y1 * M_PI / 180;
        $dLong1InRad = $X1 * M_PI / 180;
        $dLat2InRad = $Y2 * M_PI / 180;
        $dLong2InRad = $X2 * M_PI / 180;*/
        
        /*$lat1_cos = cos($dLat1InRad);
        $lat2_cos = cos($dLat2InRad);
        $lat1_sin = sin($dLat1InRad);
        $lat2_sin = sin($dLat2InRad);
 
        $sin_delta_long = sin($dLong2InRad-$dLong1InRad);
        $cos_delta_long = cos($dLong2InRad-$dLong1InRad);
        
        $y=sqrt(pow($lat2_cos*$sin_delta_long, 2)+pow($lat1_cos*$lat2_sin-$lat1_sin*$lat2_cos*$cos_delta_long,2));
        $x=$lat1_sin*$lat2_sin+$lat1_cos*$lat2_cos*$cos_delta_long;*/
        
        
        /*$dLongitude = $dLong2InRad - $dLong1InRad;
        $dLatitude = $dLat2InRad - $dLat1InRad;
        $Mult = pow(sin($dLatitude / 2), 2) + cos($dLat1InRad) * cos($dLat2InRad) * pow(sin($dLongitude / 2), 2);
        $C = 2 * atan2(sqrt($Mult), sqrt(1 - $Mult));
        $Mileage = $Mileage+((6356) * $C);*/
        
        
    $lat1 = $LatitudeFrom * M_PI / 180;
    $lat2 = $LatitudeTo * M_PI / 180;
    $long1 = $LongitudeFrom * M_PI / 180;
    $long2 = $LongitudeTo * M_PI / 180;
 
    // косинусы и синусы широт и разницы долгот
    $cl1 = cos($lat1);
    $cl2 = cos($lat2);
    $sl1 = sin($lat1);
    $sl2 = sin($lat2);
    $delta = $long2 - $long1;
    $cdelta = cos($delta);
    $sdelta = sin($delta);
 
    // вычисления длины большого круга
    $y = sqrt(pow($cl2 * $sdelta, 2) + pow($cl1 * $sl2 - $sl1 * $cl2 * $cdelta, 2));
    $x = $sl1 * $sl2 + $cl1 * $cl2 * $cdelta;
 
    //
    $ad = atan2($y, $x);
    $Mileage = $ad * 6371795;
    $Mileage = $Mileage/1000;
    //$Mileage=$Mileage*0.812;
   // return $dist;
        
   //$dist_km = 111.2 * acos( abs(sin($lat2)*sin($lat1) + cos($lat2)*cos($lat1)*cos( abs($long2 - $long1) ) ) );     
        
        /*$Mileage1 = (atan2($y,$x) * 6372795)/1000;
        if ($Mileage1>=0.6 && $Mileage1<=1) {$Mileage=0.49;}
        if ($Mileage1>=0.5) {$Mileage=0.47;}*/
         $this->ObjLogs->WriteLogs("Method:GetMovementInfo; Number:".$i."; Coords:".$LongitudeFrom.','.$LatitudeFrom.'--'.$LongitudeTo.','.$LatitudeTo.';  MileageCheck:'.$Mileage,'ArchiveLog','../logs');
        return Round($Mileage,2);
    }
    
    function GetStops($Imei,$TimeFrom,$TimeTo,$Image,$GMT)
    {
        $i=0;
        $Query = "SELECT e.date,e.EventType FROM tms_events e WHERE e.DeviceLoginName='".$Imei."' AND (e.EventType='7' OR e.EventType='12') AND e.date>='".$TimeFrom."' AND e.date<='".$TimeTo."'";
        $this->ObjLogs->WriteLogs("Method:GetStops; Query:".$Query,'Stop_event','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($DateStop,$Event);
        while ($Stmt->fetch()) 
        {            
        	
        	$this->EventStop[]=$Event;
            $this->EventStopTime[]=$DateStop;
            

            if (($this->EventStop[$i]==12 and $this->EventStop[$i-1]==12) or ($this->EventStop[$i]==7 and $this->EventStop[$i-1]==7)) 
            {
                $i--; 
                array_pop($this->EventStop); 
                array_pop($this->EventStopTime); 
            }
            $i++;
        }
        
        if ($this->EventStop[0]==12) 
        {
            array_shift($this->EventStop); 
            array_shift($this->EventStopTime);
        } 
        //print_r($this->EventStopTime); exit;
        
        $i=0;
        while ($i<Count($this->EventStop))
        {
        	
        	$this->ObjLogs->WriteLogs("Method:GetStops; stop_time".$this->EventStopTime[$i],'Stop_event','../logs');
            $EventTimeFrom=$this->ObjTimeDate->SubtractionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
            $EventTimeTo=$this->ObjTimeDate->AdditionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
            
            $Query = "SELECT latitude,longitude,time FROM `tms_gpsdata_fixed` WHERE TIME>='".$EventTimeFrom."' AND TIME<='".$EventTimeTo."' AND DeviceLoginName='".$Imei."' AND speed=0";
            $this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();
            $Stmt->bind_result($Latitude,$Longitude,$time);
           /* while ($Stmt->fetch()) 
            {            
                $this->EventStopCoord[]=$Latitude;   
                $this->EventStopCoord[]=$Longitude;   
            } */
            while ($Stmt->fetch()) 
            {   if ($time<=$this->EventStopTime[$i])
                {
                    $longitudeFixed = $Longitude;    
                    $latitudeFixed = $Latitude;    
                }         
                   
            }
            
            $this->EventStopCoord[]=$latitudeFixed; 
            $this->EventStopCoord[]=$longitudeFixed;   
            
            if ($this->EventStopTime[$i+1])
            {
                $this->EventStopDuration[]=$this->ObjTimeDate->DifferenceTime($this->EventStopTime[$i+1],$this->EventStopTime[$i]);
            }
            else
            {
                $this->EventStopDuration[]=0;
                $this->EventStopTime[]=0;   
            }
            $this->EventStopImage[]=$Image;
            $i+=2;
        }        
        $Stmt->close();
        
        $i=0;
       while ($i<Count($this->EventStopTime))
       {
           if ($this->EventStopTime[$i] == 0) {
           	$this->EventStopTime[$i] = 'Стоянка не завершена';
           } else {
       		$this->EventStopTime[$i]=$this->ObjTimeDate->AddTimeGMT($this->EventStopTime[$i],$GMT);
           }
           	$i++;
       }
        
                            
    }
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++
    function GetStops2($Imei,$TimeFrom,$TimeTo,$Image,$GMT)
    {
        $i=0;
        $Query = "SELECT ADDTIME(e.date,'0 ".$GMT.":0:0'), e.EventType,e.GeoX,e.GeoY FROM tms_events e WHERE e.DeviceLoginName='".$Imei."' AND (e.EventType='7' OR e.EventType='12') AND e.date>='".$TimeFrom."' AND e.date<='".$TimeTo."'";
        $this->ObjLogs->WriteLogs("Method:GetStops2; Query:".$Query,'Stop_event','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($DateStop,$Event,$GeoX,$GeoY);
        while ($Stmt->fetch()) 
        {            
        	if($Event==7)
            { 
                $this->EventStop[]=$Event;
				$this->EventStopTime[$i]=$DateStop;
				$x = $GeoY;
				$y = $GeoX;
				$this->EventStopImage[]=$Image;
            }
        	if($Event==12 && $PreventEvent==7)
			{ 
				$this->EventStop[]=$Event;
				$this->EventStopTime[$i]=$DateStop;
				
				$this->EventStopCoord[]=$x;
				$this->EventStopCoord[]=$y;
				
				$this->EventStopDuration[] = $this->ObjTimeDate->DifferenceTime($this->EventStopTime[$i],$this->EventStopTime[$i-1]);
				//$this->EventStopImage[]=$Image;
			}
            
			$PreventEvent=$Event;
			$i++;
        }
		if($Event==7 && $PreventEvent==7)
		{ 
			$this->EventStopCoord[]=$x;
			$this->EventStopCoord[]=$y;
			$this->EventStopDuration[] = 'Остановка не завершена';
			//$this->EventStopImage[]=$Image;
		}
		$Stmt->close();		
    }
	function GetParkin2($Imei,$TimeFrom,$TimeTo,$Image,$GMT)
    {
        $i=0;
        $Query = "SELECT ADDTIME(e.date,'0 ".$GMT.":0:0'),e.EventType,e.GeoX,e.GeoY FROM tms_events e WHERE e.DeviceLoginName='".$Imei."' AND (e.EventType='6' OR e.EventType='12') AND e.date>='".$TimeFrom."' AND e.date<='".$TimeTo."'";
        $this->ObjLogs->WriteLogs("Method:GetParking2; Query:".$Query,'Stop_event','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($DateStop,$Event,$GeoX,$GeoY);
        while ($Stmt->fetch()) 
        {            
        	if($Event==6)
            { 
                $this->EventParking[]=$Event;
				$this->EventParkingTime[$i]=$DateStop;
				$x = $GeoY;
				$y = $GeoX;
				$this->EventParkingImage[]=$Image;
            }
        	if($Event==12 && $PreventEvent==6)
			{ 
				$this->EventParking[]=$Event;
				$this->EventParkingTime[$i]=$DateStop;
				
				$this->EventParkingCoord[]=$x;
				$this->EventParkingCoord[]=$y;
				
				$this->EventParkingDuration[] = $this->ObjTimeDate->DifferenceTime($this->EventParkingTime[$i],$this->EventParkingTime[$i-1]);
				//$this->EventParkingImage[]=$Image;
			}
            
			$PreventEvent=$Event;
			$i++;
        }
		if($Event==6 && $PreventEvent==6)
		{ 
			$this->EventParkingCoord[]=$x;
			$this->EventParkingCoord[]=$y;
			$this->EventParkingDuration[] = 'Стоянка не завершена';
			//$this->EventParkingImage[]=$Image;
		}
		$Stmt->close();
    }
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
    function GetParkin($Imei,$TimeFrom,$TimeTo,$Image,$GMT)
    {
        $i=0;
        $Query = "SELECT e.date,e.EventType FROM tms_events e WHERE e.DeviceLoginName='".$Imei."' AND (e.EventType='6' OR e.EventType='12') AND e.date>='".$TimeFrom."' AND e.date<='".$TimeTo."'";
        $this->ObjLogs->WriteLogs("Method:GetStops; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($DateStop,$Event);
        while ($Stmt->fetch()) 
        {            
            $this->EventParking[]=$Event;
            $this->EventParkingTime[]=$DateStop;
            

            if (($this->EventParking[$i]==12 and $this->EventParking[$i-1]==12) or ($this->EventParking[$i]==6 and $this->EventParking[$i-1]==6)) 
            {
                $i--; 
                array_pop($this->EventParking); 
                array_pop($this->EventParkingTime); 
            }
            $i++;
        }
        
        if ($this->EventParking[0]==12) 
        {
            array_shift($this->EventParking); 
            array_shift($this->EventParkingTime);
        } 
        
        
        $i=0;
        while ($i<Count($this->EventParking))
        {
            $EventTimeFrom=$this->ObjTimeDate->SubtractionTimeAndGMT($this->EventParkingTime[$i],0,0,5,0);
            $EventTimeTo=$this->ObjTimeDate->AdditionTimeAndGMT($this->EventParkingTime[$i],0,0,5,0);
            
            $Query = "SELECT latitude,longitude,time FROM `tms_gpsdata_fixed` WHERE TIME>='".$EventTimeFrom."' AND TIME<='".$EventTimeTo."' AND DeviceLoginName='".$Imei."' AND speed=0";
            $this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();
            $Stmt->bind_result($Latitude,$Longitude,$time);
            while ($Stmt->fetch()) 
            {   if ($time<=$this->EventParkingTime[$i])
                {
                    $longitudeFixed = $Longitude;    
                    $latitudeFixed = $Latitude;    
                }         
                   
            }
            
            $this->EventParkingCoord[]=$latitudeFixed;
            $this->EventParkingCoord[]=$longitudeFixed;   
            
            if ($this->EventParkingTime[$i+1])
            {
                $this->EventParkingDuration[]=$this->ObjTimeDate->DifferenceTime($this->EventParkingTime[$i+1],$this->EventParkingTime[$i]);
            }
            else
            {
                $this->EventParkingDuration[]=0;
                $this->EventParkingTime[]=0;   
            }
            $this->EventParkingImage[]=$Image;
            $i+=2;
        }        
        $Stmt->close();
        
        $i=0;
       while ($i<Count($this->EventParkingTime))
       {
	       	if ($this->EventParkingTime[$i] == 0) {
	       		 $this->EventParkingTime[$i] = 'Стоянка не завершена';
	       	} else {
	       		$this->EventParkingTime[$i]=$this->ObjTimeDate->AddTimeGMT($this->EventParkingTime[$i],$GMT);
	       	}   
           $i++;
       }
        
                            
    }
    
    function __destruct()
    {
        $this->DB->close();    
    }
    
}
?>
