<?php
//Класс для создания очетов
    class Report
    {
        var $BodyReport;//Таблица отчета.
        var $ModelReport;//Модель данных отчета
        var $StoreReport;//Хранилище данных отчета
        var $MileageReport;//Переменная пробегп
        var $CarNameReport;//Переменная названия автомобиля
        var $CarModelReport;
		var $ConsumptionReport;//Переменная расхода топлива автомобиля
        var $AdressStopReport;//Переменная адреса стоянки автомобиля
        var $DateStartStop;//Переменная времени начала стоянки автомобиля
        var $DateFinishStop;//Переменная времени окончания стоянки автомобиля
        var $TimeStop;//Переменная времени стоянки автомобиля
        var $CountColumns;//Переменная количества колонок в таблице отчета
        var $DB;//Переменная базы данных
		var $DB1;//Переменная базы данных
        var $TableType;
        var $EmploeeReport;
        var $CustomerReport;
        var $RouteReport;
        var $TimeRouteReport;
        var $TravelTime;
        var $DateEventReport;
        var $StopLanLon;
        var $StopLanLonArray;
        var $MaxSpeedReport;
        var $MinSpeedReport;
        var $AvgSpeedReport;
        var $CarConsumtionByKmReport;
        var $LastCordValueReport;
        var $LastCordDateReport;
        var $LastCordDateReportFixed;
        var $LastCordLanLonReport;
        var $DriverNameReport;
        var $ValueOdometr;
        var $DateOdometr;
        var $CheckOdometr;
        var $ValueCharge;
        var $DateCharge;
        //--add from 37
		var $countStop;
        var $countParking;
        var $timeMovement;
        var $zoneInMovement;
        var $zoneOutMovement;
        var $EventStop;
        var $EventStopTime;
        var $EventStopCoord;
        var $EventStopDuration;
        var $EventStopImage;
        var $EventParking;
        var $EventParkingTime;
        var $EventParkingCoord;
        var $EventParkingDuration;
        var $EventParkingImage;
        var $LongitudeMovement;
        var $LatitudeMovement;
        var $AzimythMovement;
        var $AltitudeMovement;
        var $SpeedMovement;
        var $sensorTempChart;
        var $sensorTempValue;
        var $sensorTempDate;
        var $arrZoneEvent;
        var $arrZoneTime;
        var $queryCheck;
		//--end
		var $checkQuery;
        var $countStops;
        var $timeLastCoord; 
        var $OdjDateTime;
        var $ObjLogs;
		var $ChangeStr;
        var $CarMileageCost;
        //add 03_10_2014 for ReportConstructor
        var $GroupField;
		var $CarImagePath;
		
        //Конструктор класса
        //Параметры:1.Тело отчета; 2.Модель данных отчета
        
		
		
		function Report($TableType='tms_gpsdata_fixed',$BodyReport=null,$ModelReport=null)
        {
            define('COORDINATES_FORMAT', 'WGS84');
            define('MAJOR_AXIS', 6378137.0); //meters
            define('MINOR_AXIS', 6356752.3142); //meters
            define('MAJOR_AXIS_POW_2', pow(MAJOR_AXIS, 2)); //meters
            define('MINOR_AXIS_POW_2', pow(MINOR_AXIS, 2)); //meters
            include("settings.php");
            require_once("ClassTimeDate.php");
            require_once("ClassMessageAndLogs.php");
            //include ('../translate.php');
            include ('translate.php');
            //require_once("ClassLibs/GetDistance.php");
            $this->ObjLogs=new MessageAndLogs();
            $this->OdjDateTime=new TimeDate();
            $this->BodyReport=$BodyReport;
            $this->ModelReport=$ModelReport;
            $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'");
            $this->DB1 = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
            $this->DB1->query("SET CHARSET SET utf8");
            $this->DB1->query("SET NAMES 'utf8'");
			$this->TableType = $TableType;
        }
        
        //Функция устанавливает хранилище данных для объекта
        //Параметры:1.Хранилище даннх отчета 
        function GetCarIcon($Imei){
			$Query ="SELECT image_path FROM wm_car_info WHERE imei='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($image_path);
            while ($Stmt->fetch()) 
            {
                $this->CarImagePath[]=$image_path;
            }
			if(!$image_path || $image_path==''){ $image_path = 'images/car_red.png'; }
			
            return $image_path;
		}
		
		function SetStore($StoreReport)
        {
            $StoreReport=substr($StoreReport, 0, strlen($StoreReport)-1);
            $this->StoreReport='['.$StoreReport.']';
        }
        
        //Функция устананавливает тело отчета
        //Параметры:1.Тело отчета
        function SetBody($BodyReport)
        {
            $this->BodyReport=$BodyReport;
        }
        
        //Задание тела отчета по массиву заголовка
        //Параметры:1.Массив заголовка; 2.Время начала создания отчета; 3.Время окончания создания отчета
        function SetBodyByTitle($ArrTitle,$FromTimeReport,$ToTimeReport)
        {
            global $reportFrom;
            global $reportTo;
        	
        	$Table="[{text: '$reportFrom ".$FromTimeReport." $reportTo ".$ToTimeReport."',columns : [";
            $i=0;
            $Column=1;
            while ($ArrTitle[$i])
            {
                $ArrColumn=explode(':[',$ArrTitle[$i]);
                $TableHiddenOption='';
                $widthColumn = 130;
                if ($ArrColumn[1]=='H')
                {
                    $TableHiddenOption="hidden:true,";
                }
                if ($ArrColumn[2])
                {
                    $widthColumn = $ArrColumn[2];    
                }
				
					$Table.="{text: '".$ArrColumn[0]."',dataIndex : 'result_".$Column."',width: ".$widthColumn.",".$TableHiddenOption."sortable: true,hideable: true},";
				
				$i++;
                $Column++;
            }
            $Table=substr($Table, 0, strlen($Table)-1);
            $Table.="]}]";
            $this->BodyReport=$Table;
        }
        
        function SetBodyByTitleLastCoord ($ArrTitle,$FromTimeReport,$ToTimeReport) {
        	global $report;
        	$Table="[{text: '".$report."',columns : [";
        	$i=0;
        	$Column=1;
        	while ($ArrTitle[$i])
        	{
        		$ArrColumn=explode(':[',$ArrTitle[$i]);
        		$TableHiddenOption='';
        		$widthColumn = 130;
        		if ($ArrColumn[1]=='H')
        		{
        			$TableHiddenOption="hidden:true,";
        		}
        		if ($ArrColumn[2])
        		{
        			$widthColumn = $ArrColumn[2];
        		}
        	
        		$Table.="{text: '".$ArrColumn[0]."',dataIndex : 'result_".$Column."',width: ".$widthColumn.",".$TableHiddenOption."sortable: true,hideable: true},";
        	
        		$i++;
        		$Column++;
        	}
        	$Table=substr($Table, 0, strlen($Table)-1);
        	$Table.="]}]";
        	$this->BodyReport=$Table;
        }
//_______________________________
function SetGroupField($field) {
	$this->GroupField = $field;
}
function SetBodyByTitleWidthReport($ArrTitle,$FromTimeReport,$ToTimeReport,$WidthArray, $dataIndexArray)
        {
            $Table="[{text: 'Отчёт с ".$FromTimeReport." по ".$ToTimeReport."',columns : [";
            $i=0;
            $Column=1;
            while ($ArrTitle[$i])
            {
                $ArrColumn=explode(':[',$ArrTitle[$i]);
                $TableHiddenOption='';
                //$widthColumn = 135;
		                
		    if ($ArrColumn[1]=='H')
		                {
		                    $TableHiddenOption="hidden:true,";
		                }
		                if ($ArrColumn[2])
		                {
		                    $widthColumn = $ArrColumn[2];    
		                }
		    
		     $Table.="{text: '".$ArrColumn[0]."',dataIndex : '".$dataIndexArray[$i]."',width: ".$WidthArray[$i].",".$TableHiddenOption."sortable: true,hideable: true},";
		    
		    $i++;
                $Column++;
            }
            $Table=substr($Table, 0, strlen($Table)-1);
            $Table.="]}]";
            $this->BodyReport=$Table;
        }
//____________________		
		
	  function SetBodyByTitleWidth($ArrTitle,$FromTimeReport,$ToTimeReport,$WidthArray)
        {
            global $reportFrom;
            global $reportTo;
        	$Table="[{text: '$reportFrom ".$FromTimeReport." $reportTo ".$ToTimeReport."',columns : [";
            $i=0;
            $Column=1;
            while ($ArrTitle[$i])
            {
                $ArrColumn=explode(':[',$ArrTitle[$i]);
                $TableHiddenOption='';
                //$widthColumn = 135;
                
    if ($ArrColumn[1]=='H')
                {
                    $TableHiddenOption="hidden:true,";
                }
                if ($ArrColumn[2])
                {
                    $widthColumn = $ArrColumn[2];    
                }
    
     $Table.="{text: '".$ArrColumn[0]."',dataIndex : 'result_".$Column."',width: ".$WidthArray[$i].",".$TableHiddenOption."sortable: true,hideable: true},";
    
    $i++;
                $Column++;
            }
            $Table=substr($Table, 0, strlen($Table)-1);
            $Table.="]}]";
            $this->BodyReport=$Table;
        }
  
  //Задание тела отчета по массиву заголовка c сумированием
        //Параметры:1.Массив заголовка; 2.Время начала создания отчета; 3.Время окончания создания отчета; 4.Текст итога; 5.Индекс поля для сумирования; 6. Тип итога - sum, count, average
        function SetBodyByTitleGroupingsummary($ArrTitle,$FromTimeReport,$ToTimeReport,$TextSummary,$ArrayFields,$TypeFunc,$WidthArray)
        {
            global $reportFrom;
            global $reportTo;
        	$Table="[{text: '$reportFrom ".$FromTimeReport." $reportTo ".$ToTimeReport."',columns : [";
            $i=0;
            $Column=1;
            while ($ArrTitle[$i])
            {
                $ArrColumn=explode(':[',$ArrTitle[$i]);
                $TableHiddenOption='';
                $widthColumn = 130;
                if ($ArrColumn[1]=='H')
                {
                    $TableHiddenOption="hidden:true,";
                }
                if ($ArrColumn[2])
                {
                    $widthColumn = $ArrColumn[2];    
                }
    //if(in_array($i, $ArrayFields)){
    if($i==0){
     $Table.="{text: '".$ArrColumn[0]."',tdCls: 'task',flex: 1,dataIndex : 'result_".$Column."',width: ".$WidthArray[$i].",".$TableHiddenOption."sortable: true,hideable: true,summaryRenderer: function(value, summaryData, dataIndex) { return ('".$TextSummary.":');}},";
    }elseif( $key = array_search($i, array_values($ArrayFields)) ){
     $Table.="{text: '".$ArrColumn[0]."',dataIndex : 'result_".$Column."',width: ".$WidthArray[$i].",".$TableHiddenOption."sortable: true, hideable: true, summaryType:'".$TypeFunc[$key-1]."', summaryRenderer: function(value, summaryData, dataIndex) {return value.toFixed(2);}},"; //, xtype: 'numbercolumn'
                }else{
     $Table.="{text: '".$ArrColumn[0]."',dataIndex : 'result_".$Column."',width: ".$WidthArray[$i].",".$TableHiddenOption."sortable: true,hideable: true},";
    }
    
    
    
    $i++;
                $Column++;
            }
            $Table=substr($Table, 0, strlen($Table)-1);
            $Table.="]}]";
            $this->BodyReport=$Table;
        }
		
		
        
        //Функция устанавливает модель данных для отчета
        //Параметры:1.Модель данных отчета
        function SetModel($ModelReport)
        {
            $this->ModelReport=$ModelReport;
        } 
        
        //Функция получения название автомобиля
        //Параметры:1.IMEI автомобиля
        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->CarNameReport=$CarName;
            }
            return $CarName;
        }
        
		//Функция получения себестоимости
        function GetCarMileageCost($Imei)
        {
           
            $Query ="SELECT kmh_kost FROM wm_car_info WHERE imei='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($cost);
            while ($Stmt->fetch()) 
            {
                $this->CarMileageCost=$cost;
            }
            return $cost;
        }
		
		function GetCarModel($Imei)
        {
           
            $Query ="SELECT `model` FROM `wm_car_info` WHERE `imei`='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($CarModel);
            while ($Stmt->fetch()) 
            {
                $this->CarModelReport=$CarModel;
            }
            return $CarModel;
        }
		
        //Функция получеия пробега автомобиля за заданный период времени
        //Параметры:1.IMEI автомобиля; 2.Время начала измерения; 3.Время окончания измерения
        function GetMileage($Imei,$TimeFrom,$TimeTo)
        {
            
            $Mileage=0;
            $Result=0.0;
            $i=0;
            $X1=0;
            $X2=0;
            $Y1=0;
            $Y2=0;
            $Chek=0;
            $Query = "SELECT g.latitude,g.longitude,g.altitude,g.time FROM ".$this->TableType." g WHERE g.time>='".$TimeFrom."' AND g.time<='".$TimeTo."' AND g.DeviceLoginName='".$Imei."'"; 
            //$this->checkQuery = $Query;
			//$this->ObjLogs->WriteLogs("Method:GetMileage; Query:".$Query,'ReportLog','logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Latitude,$Longitude,$Altitude,$time);
            while ($Stmt->fetch()) 
            {
                if ($Chek==1)
                {
                    $gps_2['lat']=$Y2;
                    $gps_2['lon']=$X2;
                    $gps_2['point_elevation']=$Z2;
                    $gps_1['lat']=$Latitude;
                    $gps_1['lon']=$Longitude;
                    $gps_1['point_elevation']=$Altitude;
                    $Mileage=get_distance_between_2_points($gps_1,$gps_2);
                    $Result=$Result+$Mileage;
                    // $this->ObjLogs->WriteLogs("Method:GetMovementInfo; Number:".$i.'; Mileage:'.$Mileage.'; Result:'.$Result.'; LonLat1:('.$Longitude.','.$Latitude.'); LonLat2:('.$X2.','.$Y2.')','ReportLog','../logs');
                   
                    //$this->ObjLogs->WriteLogs("Method:GetMileage; Number:".$i.' Mileage:'.((6378) * $C).' Result:'.$Mileage,'ReportLog','../logs');
                }
                
                $X2=$Longitude;
                $Y2=$Latitude;
                $Z2=$Altitude;
                $i++;
                $Chek=1;
            }
            $this->MileageReport=Round($Result/1000,2);
            return Round($Result/1000,2);
			//$this->MileageReport = number_format($Result, 2, ',', ' ');
			//return number_format($Result, 2, ',', ' ');

        }
        
		function GetMileage2($Imei,$TimeFrom,$TimeTo)
        {
			$Query = "SELECT SUM(`mileage`) FROM `wm_report_run` WHERE `imei`='".$Imei."' AND `date`>=DATE('".$TimeFrom."') AND `date`<=DATE('".$TimeTo."');";
			$Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($sum);
            $Stmt->fetch();
			return $sum;
        }
        
		function GetMileage3($Imei,$TimeFrom,$TimeTo)
        {
			$Query = "SELECT SUM(`Distance`) FROM `tms_gpsdata_fixed` WHERE `time`>= '".$TimeFrom."' AND `time`<= '".$TimeTo."' AND `DeviceLoginName`='".$Imei."';";
			//$Query = "SELECT SUM(t.D) FROM (SELECT DISTINCT(`time`) AS T, `Distance` AS D FROM `tms_gpsdata_fixed` WHERE `DeviceLoginName`='".$Imei."' AND `time`>= '".$TimeFrom."' AND `time`<= '".$TimeTo."') AS t;";
			//$Query = "SELECT SUM(t.D) FROM (SELECT Distance AS D FROM `tms_gpsdata_fixed` WHERE `DeviceLoginName`='".$Imei."' AND `time`>= '".$TimeFrom."' AND `time`<= '".$TimeTo."' GROUP BY `time`) AS t;";
			$Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($sum);
            $Stmt->fetch();
			return Round($sum/1000,2);
        }
		
        function CalculateMileage($LongitudeFrom,$LatitudeFrom,$LongitudeTo,$LatitudeTo)
        {
             $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);
             $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=((6378) * $C);
             return Round($Mileage,2);     
        }
        
        //Функция получения расхода топлива без получения данных от датчиков
        //Параметры:1.IMEI автомобиля; 2.Пробег автомобиля
        function GetConsumptionNotSensors($Imei,$Distance)
        {
            $Query ="SELECT fuel_consumption FROM wm_car_info WHERE imei='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($FuelConsumption);
            while ($Stmt->fetch()) 
            {
                $FuelConsumption=$FuelConsumption;
            }
            $this->ConsumptionReport=Round(($Distance / 100)*$FuelConsumption,2);
        }
        
        //Функция получения адреса по геокординатам
        //Параметры 1.Геокординаты
        function GetGeolocation($LatLng)
        {
            $DetailsUrl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".$LatLng."&sensor=true&language=ru";
            $CH = curl_init();
            curl_setopt($CH, CURLOPT_URL, $DetailsUrl);
            curl_setopt($CH, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($CH, CURLOPT_HEADER,0); //Change this to a 1 to return headers
            curl_setopt($CH, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
            curl_setopt($CH, CURLOPT_FOLLOWLOCATION, 1);
            $Response = json_decode(curl_exec($CH), true);
            $this->AdressStopReport=$Response['results'][0]['formatted_address'];
        }
        function GetGeolocationYandex($LatLng)
        {
            $coordYandex = explode(',',$LatLng);
            $LatLng = '+'.$coordYandex[0].',+'.$coordYandex[1];
            $DetailsUrl = "http://geocode-maps.yandex.ru/1.x/?=".$LatLng;
            $this->ObjLogs->WriteLogs("Method:GetLastCoordFixed; Query:".$DetailsUrl,'YandexLog','../logs');
			//$DetailsUrl = "http://geocode-maps.yandex.ru/1.x/?geocode=".$LatLng;
            $CH = curl_init();
            curl_setopt($CH, CURLOPT_URL, $DetailsUrl);
            curl_setopt($CH, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($CH, CURLOPT_HEADER,0); //Change this to a 1 to return headers
            curl_setopt($CH, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
            curl_setopt($CH, CURLOPT_FOLLOWLOCATION, 1);
            $Response = json_decode(curl_exec($CH), true);
           // $this->AdressStopReport=$Response['results'][0]['formatted_address'];
             $this->AdressStopReport = $Response;
        }
        
		function GetGeolocationYandexJSON($LatLng)
        {
			$DetailsUrl = 'http://geocode-maps.yandex.ru/1.x/?format=json&geocode='.$LatLng;
			$CH = curl_init();
            curl_setopt($CH, CURLOPT_URL, $DetailsUrl);
            curl_setopt($CH, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($CH, CURLOPT_HEADER,0); //Change this to a 1 to return headers
            curl_setopt($CH, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
            curl_setopt($CH, CURLOPT_FOLLOWLOCATION, 1);
            $Response = json_decode(curl_exec($CH), true);
            //$Response = curl_exec($CH);
            //$this->AdressStopReport = $Response;
			return $Response["response"]["GeoObjectCollection"]["featureMember"][0]["GeoObject"]["metaDataProperty"]["GeocoderMetaData"]["text"];
			
		}
		
		
		
        //Функция получения информации о начале стоянки
        //Параметры:1.Поправка GMT для времени; 2.IMEI автомобиля; 3.Время начала измерения; 4.Время окончания измерения; 5.Время начала стоянки
        var $simei;
		function GetStandartStartStop($GMT,$Imei,$FromTime,$ToTime,$Date)
        {
            $i=0;
            $BufTime=50000;
            $Residual=0;
            $Query="SELECT gp.latitude, gp.longitude,ADDTIME(gp.time,'0 ".$GMT.":0:0') FROM ".$this->TableType." gp WHERE  gp.deviceloginname='".$Imei."' AND gp.time>='".$FromTime."' AND gp.time<='".$ToTime."' ORDER BY gp.deviceloginname,gp.time";   
            
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();
            $Stmt->bind_result($Latitude,$Longitude,$Time);
            while ($Stmt->fetch()) 
            {            
                $MassLat[$i]=$Latitude;
                $MassLon[$i]=$Longitude;
                $MassEventTime[$i]=$Time;
                $Date1=strtotime($Date);
                $Date2=strtotime($Time);
                $Residual=abs($date1-$date2);
                if ($Residual<$BufTime)
                {
                    $BufTime=$Residual;
                    $BufDotStop=$i;
                } 
                $i++;  
            }
            $this->checkQuery = $i;  
            //$this->GetGeolocation($MassLat[$BufDotStop].','. $MassLon[$BufDotStop]);
            $this->StopLanLon=$MassLat[$BufDotStop].','. $MassLon[$BufDotStop];
            $this->StopLanLonArray[] = $MassLat[$BufDotStop].','. $MassLon[$BufDotStop];
            if($this->simei != $Imei){ $this->DateStartStop = null; }
			$this->DateStartStop=$Date;
			$this->simei = $Imei;
        }
        
        //Функция получения информации о конце стоянки
        //Параметры:1.Дата окончания стоянки
        function GetStandartFinishStop($Date)
        {
            //$this->DateFinishStop = [];
			$this->DateFinishStop=$Date;
            $this->TimeStop=$this->OdjDateTime->DifferenceTime($Date,$this->DateStartStop);
        }
        
        //Функция получения количества колонок в отчете
        //Параметры:1.Модель данных отчета
        function GetCountColumns($Model)
        {
          $Count=explode(",",$Model);
          $this->CountColumns=count($Count);  
        }
        
        //Функция экспортирует данные в Excel
        //Параметры:1.Массив названий полей отчета; 2.Заголовок отчета; 3.Массив данных для отчета
        function ExportExcelStr ($Fields,$Title,$ArrayOfData)
        {
            require_once '../classes/PHPExcel.php';
            include_once '../classes/PHPExcel/IOFactory.php';
            $BoldFont = array
            (
                'font'=>array
                (
                    'name'=>'Arial Cyr',
                    'size'=>'10',
                    'bold'=>true
                )
            );
            
            $Center = array
            (
                'alignment'=>array
                (
                    'horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP
                )
            ); 
            $ObjPHPExcel = new PHPExcel();
       
            $Column='A';
            $i=0;    
            $Sheet = $ObjPHPExcel->getActiveSheet();
            $Sheet->setTitle($Title);
            while ($Fields[$i])
            {
                $Sheet->getColumnDimension($Column)->setWidth(25);
                $i++;
                $Column++;
            }
            $i=1; 
            while ($i<=count($Fields))
            {
                $Sheet->setCellValueByColumnAndRow($i-1,1,$Fields[$i-1]);
                $i++;
            }
            
            $i=0;
            $RowNumber=2;
            while ($ArrayOfData[$i])
            {         
                $j=0;
                $ArrayOfData[$i]=substr($ArrayOfData[$i], 0, strlen($ArrayOfData[$i])-2);
                $DataColumns=explode('/n',$ArrayOfData[$i]);
                while ($j<count($DataColumns))
                {
                    $Sheet->setCellValueByColumnAndRow($j,$RowNumber,"'".$DataColumns[$j]."'");
                    $j++;
                }               
                $RowNumber++;
                $i++;  
            }  
            $ObjWriter = PHPExcel_IOFactory::createWriter($ObjPHPExcel, 'Excel2007');
            header('Content-Type: application/vnd.ms-excel Content-Type: text/html; charset=utf-8');
            if(file_exists("../report/Cars_report.xlsx"))
            {
                unlink("../report/Cars_report.xlsx");
            }
            $ObjWriter->save('../report/Cars_report.xlsx');
        }
        
                function ExportExcel ($Fields,$Title,$ArrayOfData)
        {
            require_once '../classes/PHPExcel.php';
            include_once '../classes/PHPExcel/IOFactory.php';
            $BoldFont = array
            (
                'font'=>array
                (
                    'name'=>'Arial Cyr',
                    'size'=>'10',
                    'bold'=>true
                )
            );
            
            $Center = array
            (
                'alignment'=>array
                (
                    'horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP
                )
            ); 
            $ObjPHPExcel = new PHPExcel();
       
            $Column='A';
            $i=0;    
            $Sheet = $ObjPHPExcel->getActiveSheet();
            $Sheet->setTitle($Title);
            while ($Fields[$i])
            {
                $Sheet->getColumnDimension($Column)->setWidth(25);
                $i++;
                $Column++;
            }
            $i=1; 
            while ($i<=count($Fields))
            {
                $Sheet->setCellValueByColumnAndRow($i-1,1,$Fields[$i-1]);
                $i++;
            }
            
            $i=0;
            $RowNumber=2;
            while ($ArrayOfData[$i])
            {         
                $j=0;
                $ArrayOfData[$i]=substr($ArrayOfData[$i], 0, strlen($ArrayOfData[$i])-2);
                $DataColumns=explode('/n',$ArrayOfData[$i]);
                while ($j<count($DataColumns))
                {
                    $Sheet->setCellValueByColumnAndRow($j,$RowNumber,"".$DataColumns[$j]."");
                    $j++;
                }               
                $RowNumber++;
                $i++;  
            }  
            $ObjWriter = PHPExcel_IOFactory::createWriter($ObjPHPExcel, 'Excel2007');
            header('Content-Type: application/vnd.ms-excel Content-Type: text/html; charset=utf-8');
            if(file_exists("../report/Cars_report.xlsx"))
            {
                unlink("../report/Cars_report.xlsx");
            }
            $ObjWriter->save('../report/Cars_report.xlsx');
        }
        
        //Функция передачи Excel файла в поток
        function SaveExcel()
        {
            $File = ('../report/Cars_report.xlsx');
            if (file_exists($File)) 
            {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.basename($File));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($File));
                ob_clean();
                flush();
                readfile($File);
                exit;
            }
        }
        
        //Функция экспортирует данные в CSV
        //Параметры:1.Массив названий полей отчета; 2.Заголовок отчета; 3.Массив данных для отчета
        function ExportCSV($Fields,$Title,$ArrayOfData)
        {
            $i=0; 
            while ($Fields[$i])
            {
                $Str .= $Fields[$i].",   ";
                $i++;
            }
            $Result[0]=$Str;
            $i=0;
            while ($ArrayOfData[$i])
            {       
                $j=0;
                $Row='';
                $ArrayOfData[$i]=substr($ArrayOfData[$i], 0, strlen($ArrayOfData[$i])-2);
                $DataColumns=explode('/n',$ArrayOfData[$i]);
                while ($j<count($DataColumns))
                {
                    $Row .= "  ".$DataColumns[$j]." ,";
                    $j++;
                }
                $Row=substr($Row, 0, strlen($Row)-1); 
                $Result[] = $Row;
                $i++;
            }     
            $fp = fopen('../report/Cars_report.csv', 'w');
            foreach ($Result as $line) 
            {
                fputcsv($fp, split(",", $line));
            }
            fclose($fp);
        }
        
		//цветной експорт в xls -------------------------------------------------------------------------------------------------------
		function ExportExcelColored ($Fields,$Title,$ArrayOfData,$colorHead,$colorBody,$colorBody2,$textHead,$sumarry)
        {
            require_once '../classes/PHPExcel.php';
            include_once '../classes/PHPExcel/IOFactory.php';
            
			$BoldFont = array('font'=>array
                (
                    'name'=>'Arial Cyr',
                    'size'=>'11',
                    'bold'=>true
                )
            );
            
            $Center = array('alignment'=>array
                (
                    'horizontal'=>PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                    'vertical'=>PHPExcel_Style_Alignment::VERTICAL_TOP
                )
            ); 
            $ObjPHPExcel = new PHPExcel();
			
			
			$styleArray = array('borders' => array
			(
				'allborders' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN
				)
			)
			);
       
            $Column='A';
            $i=0;    
            $Sheet = $ObjPHPExcel->getActiveSheet();
            $Sheet->setTitle($Title);
            
			$Sheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
			$Sheet->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);         
            
            while ($Fields[$i])
            {
                $Sheet->getStyle($Column.'2')->applyFromArray(
                    array(
                            'fill' => array(
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array('rgb' => $colorHead)
                            )
                    )
                    );
                $Sheet->getColumnDimension($Column)->setWidth(25);
				
				$Sheet->getStyle($Column.'2')->getAlignment()->setWrapText(true);
				$Sheet->getStyle($Column.'2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
				
                $i++;
                $Column++;
            }
            
			$i=1; 
            while ($i<=count($Fields))
            {
                $Sheet->setCellValueByColumnAndRow($i-1,2,$Fields[$i-1]);
                $i++;
            }
			$Sheet->setCellValueByColumnAndRow(0,1,date('d.m.Y'));
			$Sheet->setCellValueByColumnAndRow(1,1,$textHead);
            $Sheet->getStyle('A1:B1')->applyFromArray(array('font'=>array('bold'=>true)));
			
            $i=0;
            $RowNumber=3;
			$cIf="";
			$sum = 0.00;
			$sum2 = 0.00;;
			$R;
			
            while ($ArrayOfData[$i])
            {         
                $j=0;
                $Column='A';
                $ArrayOfData[$i]=substr($ArrayOfData[$i], 0, strlen($ArrayOfData[$i])-2);
                
				$DataColumns=explode('/n',$ArrayOfData[$i]);
                //$this->ChangeStr .= $ArrayOfData[$i].'------';
				
				
				
				if( $sumarry ){
					if($RowNumber==3){ $cIf = $DataColumns[5]; $Sheet->setCellValueByColumnAndRow(0,$RowNumber,"Идентификатор устройства:".$DataColumns[5]); $RowNumber++; };
					//$this->ChangeStr .= $cIf.' - '.$DataColumns[5].'------';
					if( $cIf != $DataColumns[5] ){
						//$RowNumber++;
						$Sheet->setCellValueByColumnAndRow(0,$RowNumber,"Итого:");
						//$Sheet->setCellValueByColumnAndRow(1,$RowNumber,$DataColumns[1]);
						$Sheet->setCellValueByColumnAndRow(2,$RowNumber,$sum);
						$Sheet->setCellValueByColumnAndRow(3,$RowNumber,$sum2);
						//$Sheet->setCellValueByColumnAndRow(3,$RowNumber,$RowNumber);
						$Sheet->getStyle('A'.$RowNumber.':E'.$RowNumber)->applyFromArray(array(
                            'fill' => array(
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array('rgb' => $colorHead)
                            )
						));
						$sum = (float)$DataColumns[2]; $sum2 = (float)$DataColumns[3];
						//$sum = 0.00; $sum2 = 0.00;
						$RowNumber++;
						$Sheet->setCellValueByColumnAndRow(0,$RowNumber,"Идентификатор устройства:".$DataColumns[5]);
						$RowNumber++;
					}else{
						$sum = $sum + (float)$DataColumns[2];
						$sum2 = $sum2 + (float)$DataColumns[3];
					}
					
				}
				
				if( $sumarry ){ $count = count($DataColumns)-1; }else{ $count = count($DataColumns); }
				while ($j<$count)
                {
                    
					//$this->ChangeStr .= $Column.$RowNumber.'------';
					
                    if($i % 2 == 0){
						$Sheet->getStyle($Column.$RowNumber)->applyFromArray(array(
                            'fill' => array(
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array('rgb' => $colorBody)
                            )
						));
					}else{
						$Sheet->getStyle($Column.$RowNumber)->applyFromArray(array(
                            'fill' => array(
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array('rgb' => $colorBody2)
                            )
						));
					}
                    
					$Sheet->setCellValueByColumnAndRow($j,$RowNumber,"".$DataColumns[$j]."");
					
					
                    
					$j++;
                    $Column++;
                }
                
				
				
				$RowNumber++;
                $i++;
				$cIf = $DataColumns[5];
            }
			
			if( $sumarry ){
					$Sheet->setCellValueByColumnAndRow(0,$RowNumber,"Итого:");
					$Sheet->setCellValueByColumnAndRow(2,$RowNumber,$sum);
					$Sheet->setCellValueByColumnAndRow(3,$RowNumber,$sum2);
					$Sheet->getStyle('A'.$RowNumber.':E'.$RowNumber)->applyFromArray(array(
                            'fill' => array(
                                'type' => PHPExcel_Style_Fill::FILL_SOLID,
                                'color' => array('rgb' => $colorHead)
                            )
					));
			}
            
			$Sheet->getStyle('A1:'.$Sheet->getHighestColumn().$Sheet->getHighestRow())->applyFromArray($styleArray);
			
			$ObjWriter = PHPExcel_IOFactory::createWriter($ObjPHPExcel, 'Excel2007');
            header('Content-Type: application/vnd.ms-excel Content-Type: text/html; charset=utf-8');
            if(file_exists("../report/Cars_report.xlsx"))
            {
                unlink("../report/Cars_report.xlsx");
            }
            $ObjWriter->save('../report/Cars_report.xlsx');
        }
		
		
		
        //Функция передачи CSV файла в поток 
        function SaveCSV()
        {
            $File = ('../report/Cars_report.csv');
            if (file_exists($File)) 
            {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.basename($File));
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($File));
                ob_clean();
                flush();
                readfile($File);
                exit;
            }
        }
        
        //Функция отправляет данные на печать
        //Параметры:1.Массив названий полей отчета; 2.Заголовок отчета; 3.Массив данных для отчета
        function ExportPrint($Fields,$Title,$ArrayOfData)
        {
            $i=0;
            //count($Fields);
            $Result = "<table border='2' cellpadding='5' cellspacing='0'><tr><td colspan='".count($Fields)."' align='middle'><b>".$Title."</b></td></tr><tr>";
            while ($Fields[$i])
            {
                $Result .= "<td>".$Fields[$i]."</td>";
                $i++;
            }
            $Result .="</tr>";
            $i=0;
            while ($ArrayOfData[$i])
            {       
                $j=0;
                $Row='';
                $ArrayOfData[$i]=substr($ArrayOfData[$i], 0, strlen($ArrayOfData[$i])-2);
                $DataColumns=explode('/n',$ArrayOfData[$i]);
                $Result .= "<tr>";
                while ($j<count($DataColumns))
                {
                    $Result .= "<td>".$DataColumns[$j]."</td>";
                    $j++;
                }
                $Result .="</tr>";
                $i++;
            }
            $Result.="</table>";
            $_SESSION[Result]=$Result; 
           // echo $Result;        
        }
        
        //Функция отправляет данные на печать в поток
        function SavePrint()
        {
            print $_SESSION[Result];
        }
        
        function GetEmploee($Imei,$Time,$Date)
        {
            $Query ="SELECT emploee FROM tms_tasks WHERE imei='".$Imei."' AND time_from<='".$Time."' AND time_to>='".$Time."' AND DATE='".$Date."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Emploee);
            while ($Stmt->fetch()) 
            {
                $Emploee=$Emploee;
            }
            $this->EmploeeReport=$Emploee;
        }
        
        function GetCustomer($Imei,$Time,$Date)
        {
            $Query ="SELECT customer FROM tms_tasks WHERE imei='".$Imei."' AND time_from<='".$Time."' AND time_to>='".$Time."' AND DATE='".$Date."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Customer);
            while ($Stmt->fetch()) 
            {
                $Customer=$Customer;
            }
            $this->CustomerReport=$Customer;   
        }
        
        function GetRoute($Imei,$Time,$Date)
        {
            $Query ="SELECT adress_from,adress_to FROM tms_tasks WHERE imei='".$Imei."' AND time_from<='".$Time."' AND time_to>='".$Time."' AND DATE='".$Date."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($AdressFrom,$AdressTo);
            while ($Stmt->fetch()) 
            {
                $AdressFrom=$AdressFrom;
                $AdressTo=$AdressTo;
            }
            $Route=$AdressFrom.'-'.$AdressTo;
            $this->RouteReport=$Route;    
        }
        
        function GetTimeRoute($Imei,$Time,$Date)
        {
            $Query ="SELECT time_from,time_to FROM tms_tasks WHERE imei='".$Imei."' AND time_from<='".$Time."' AND time_to>='".$Time."' AND DATE='".$Date."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($TimeRouteFrom,$TimeRouteTo);
            while ($Stmt->fetch()) 
            {
                $TimeRouteFrom=$TimeRouteFrom;
                $TimeRouteTo=$TimeRouteTo;
            }
            $TimeRoute=$TimeRouteFrom.'-'.$TimeRouteTo;
            $this->TimeRouteReport=$TimeRoute;    
        }
        
        function GetTravelTime($TimeFrom,$TimeTo)
        {
            $this->TravelTime=$this->OdjDateTime->DifferenceTime($TimeTo,$TimeFrom);   
        }
        
        function GetMaxSpeed($Imei,$FromTime,$ToTime)
        {
            $Query ="SELECT MAX(Speed) FROM ".$this->TableType." WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."' AND TIME<='".$ToTime."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($MaxSpeed);
            while ($Stmt->fetch()) 
            {
                $this->MaxSpeedReport=$MaxSpeed;   
            }       
        }
        
        function GetMinSpeed($Imei,$FromTime,$ToTime)
        {
            $Query ="SELECT MIN(Speed) FROM ".$this->TableType." WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."' AND TIME<='".$ToTime."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($MinSpeed);
            while ($Stmt->fetch()) 
            {
                $this->MinSpeedReport=$MinSpeed;   
            }       
        }
        
        function GetAvgSpeed($Imei,$FromTime,$ToTime)
        {
            $Query ="SELECT AVG(Speed) FROM ".$this->TableType." WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."' AND TIME<='".$ToTime."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($AvgSpeed);
            while ($Stmt->fetch()) 
            {
                $this->AvgSpeedReport=round($AvgSpeed,2);   
            }       
        }
        
        function GetConsumtionByKm($Imei)
        {
            $Query ="SELECT fuel_consumption FROM wm_car_info WHERE imei='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($FuelConsumption);
            while ($Stmt->fetch()) 
            {
                $this->CarConsumtionByKmReport=$FuelConsumption;
            }  
        }
        
        function GetCoordStop($Imei,$GMT)
        {
            $this->LastCordDateReport='';
            
            $FromTime=$ObjTimeDate->SubtractionTimeAndGMT(time(),$GMT,4);
            $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0') FROM tms_gpsdata WHERE DeviceLoginName='".$Imei."'  AND TIME>='".$FromTime."' ORDER BY TIME DESC LIMIT 1";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Time);
            while ($Stmt->fetch()) 
            {
                $this->LastCordDateReport=$Time;   
            }   
        }
        
        function GetLastCoordFixed($Imei,$GMT)
        {
            $this->LastCordDateReportFixed='';
            $FromTime=date('Y-m-d H:i:s',time());   
            $FromTime=$this->OdjDateTime->SubtractionTimeAndGMT($FromTime,$GMT,4);
            $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata_fixed WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."'  ORDER BY TIME DESC LIMIT 1";
            $this->ObjLogs->WriteLogs("Method:GetLastCoordFixed; Query:".$Query,'ReportLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Time,$Latitude,$Longitude);
            $Stmt->fetch();
            if (!$Time)
            {
                $FromTime=date('Y-m-d H:i:s',time());   
                $FromTime=$this->OdjDateTime->SubtractionTimeAndGMT($FromTime,$GMT,720);
                $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata_fixed WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."'  ORDER BY TIME DESC LIMIT 1";
                $this->ObjLogs->WriteLogs("Method:GetLastCoordFixedWeek; Query:".$Query,'ReportLog','../logs');
                $Stmt = $this->DB->prepare($Query);
                $Stmt->execute();       
                $Stmt->bind_result($Time,$Latitude,$Longitude);
                $Stmt->fetch();
                if (!$Time)
                {
                    $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata_fixed WHERE DeviceLoginName='".$Imei."'  ORDER BY TIME DESC LIMIT 1";
                    $this->ObjLogs->WriteLogs("Method:GetLastCoordFixedAll; Query:".$Query,'ReportLog','../logs');
                    $Stmt = $this->DB->prepare($Query);
                    $Stmt->execute();       
                    $Stmt->bind_result($Time,$Latitude,$Longitude);
                    $Stmt->fetch();    
                }    
            }
            
            $this->LastCordLanLonReport=$Latitude.','. $Longitude;   
            $this->LastCordDateReportFixed=$Time;   
               
        }
        
        function GetLastCoord($Imei,$GMT)
        {
            $this->LastCordLanLonReport='';
            $this->LastCordDateReport='';
            $FromTime=date('Y-m-d H:i:s',time()); 
            $FromTime=$this->OdjDateTime->SubtractionTimeAndGMT($FromTime,$GMT,4);
            $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."'  ORDER BY TIME DESC LIMIT 1";
            $this->ObjLogs->WriteLogs("Method:GetLastCoord; Query:".$Query,'ReportLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Time,$Latitude,$Longitude);
            $Stmt->fetch(); 
            if (!$Time)
            {
                $FromTime=date('Y-m-d H:i:s',time());   
                $FromTime=$this->OdjDateTime->SubtractionTimeAndGMT($FromTime,$GMT,720);
                $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata WHERE DeviceLoginName='".$Imei."' AND TIME>='".$FromTime."'  ORDER BY TIME DESC LIMIT 1";
                $this->ObjLogs->WriteLogs("Method:GetLastCoordWeek; Query:".$Query,'ReportLog','../logs');
                $Stmt = $this->DB->prepare($Query);
                $Stmt->execute();       
                $Stmt->bind_result($Time,$Latitude,$Longitude);
                $Stmt->fetch();
                if (!$Time)
                {
                     $Query ="SELECT ADDTIME(time,'0 ".$GMT.":0:0'),latitude,longitude FROM tms_gpsdata WHERE DeviceLoginName='".$Imei."'   ORDER BY TIME DESC LIMIT 1";
                     $this->ObjLogs->WriteLogs("Method:GetLastCoordAll; Query:".$Query,'ReportLog','../logs');
                     $Stmt = $this->DB->prepare($Query);
                     $Stmt->execute();       
                     $Stmt->bind_result($Time,$Latitude,$Longitude);
                     $Stmt->fetch();    
                }        
            } 
            $this->LastCordDateReport=$Time;  
            $this->LastCordLanLonReport=$Latitude.','. $Longitude;   
                   
        }
        
        function GetDriverName($Imei)
        {
            $Query ="SELECT d.name,d.patronymic,d.surname FROM wm_drivers d LEFT JOIN wm_car_info c ON d.id = c.driver_id WHERE c.imei='".$Imei."'";
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();       
            $Stmt->bind_result($Name,$Patronymic,$Surname);
            $Stmt->fetch();
            
            $this->DriverNameReport =$Surname.' '.$Name.' '.$Patronymic;  
            return $Surname.' '.$Name.' '.$Patronymic;
        }
        
        
        function GetOdometrData($Imei,$TimeFrom,$TimeTo)
        {
              $Query ="SELECT od.value_odometer,od.date_odometer FROM wm_odometer od LEFT JOIN wm_car_info ci ON od.car_id = ci.id WHERE od.date_odometer >= '".$TimeFrom."' AND od.date_odometer <= '".$TimeTo."' AND ci.imei = '".$Imei."' ORDER BY od.date_odometer DESC LIMIT 1";
              
              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($Value,$Date);
              $Stmt->fetch();
              $this->CheckOdometr = 1;
            
            if (!$Date)
            { 
                $Query ="SELECT od.value_odometer,od.date_odometer FROM wm_odometer od LEFT JOIN wm_car_info ci ON od.car_id = ci.id WHERE od.date_odometer < '".$TimeFrom."' AND ci.imei = '".$Imei."' ORDER BY od.date_odometer DESC LIMIT 1";
                $Stmt = $this->DB->prepare($Query);
                $Stmt->execute();       
                $Stmt->bind_result($Value,$Date);
                $Stmt->fetch();
                $this->CheckOdometr = 0;
            } 
            $this->ValueOdometr = $Value;
            $this->DateOdometr = $Date;     
        }
        
        
         function GetChargeData($Imei,$TimeFrom,$TimeTo)
        {
              global $accumulator;
              global $battery;
        	  $Check = 0; 
              $i = 0; 
              $Query ="SELECT time,charge FROM ".$this->TableType." WHERE DeviceLoginName='".$Imei."' AND TIME>='".$TimeFrom."' AND TIME<='".$TimeTo."'";
              $this->ObjLogs->WriteLogs("SELECt ; Query:".$Query,'Charg','../logs');
               //$this->ValueCharge[] = $Query;
              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($Date,$Charge);
              while ($Stmt->fetch())
              {
                 if ($i == 1) {
                 	if ($Charge > 0){$Check = 1;}
                 }
                if (($Charge == 0) && ($Check == 0))    
                {
                    $this->ValueCharge[] = $accumulator;
                    $this->DateCharge[] = $Date;
                    $Check = 1;        
                }
                
                if (($Charge > 0) && ($Check == 1))
                {
                     $this->ValueCharge[] = $battery;
                     $this->DateCharge[] = $Date;
                     $Check = 0;    
                }
                $i++;
              }
             
       
        }
        
        function GetLastCordByTime($Imei,$FromTime,$ToTime)
        {
              $Query ="SELECT gp.time FROM tms_gpsdata gp WHERE  gp.deviceloginname='".$Imei."' AND gp.time>='".$FromTime."' AND gp.time<='".$ToTime."' ORDER BY gp.time DESC LIMIT 1";
              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($time);
              while ($Stmt->fetch())
              {
                $this->timeLastCoord = $time; 
              }    
        }
		
		function ChangeStrToStrIN($str){
			$cstr = str_replace(array("\n","\r\n","\r"," "), '', trim($str));
			$cstr = str_replace(",","','",$str);
			return $this->ChangeStr = "'".$cstr."'"; 
		}
		
		
		
		
		
		
		
		
		
		
//-------------------- add from 37
		
		function GetCountStart($Imei,$TimeFrom,$TimeTo)
        {
              $Query ="select COUNT(id) FROM tms_events ev WHERE ev.deviceloginname = ".$Imei." AND ev.date>='".$TimeFrom."' AND ev.date<='".$TimeTo."' AND ev.eventtype = 12 ORDER BY ev.date";
               //$this->ValueCharge[] = $Query;
              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($count);
              $Stmt->fetch();
              $this->countStart = $count;
        }
        
        function GetCountStopParking($Imei,$TimeFrom,$TimeTo)
        {
              $i = 0; 
              $oldEvent = 0;
              $countStop = 0;
              $countParking = 0;
              $Query ="select ev.eventtype FROM tms_events ev WHERE ev.deviceloginname = ".$Imei." AND ev.date>='".$TimeFrom."' AND ev.date<='".$TimeTo."' AND ev.eventtype IN(7,6) ORDER BY ev.date,ev.eventtype";
               //$this->ValueCharge[] = $Query;
              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($event);
              while ($Stmt->fetch())
              {
                if ($event == 7) {$countStop++;}
                if ($oldEvent == 6 && $event == 6) {$countParking++;}
                $oldEvent = $event;   
              }
              $this->countParking = $countParking;
              $this->countStop = $countStop;
        }
        
        function GetTimeMovement($Imei,$TimeFrom,$TimeTo)
        {
              $oldSpeed = 0;
              $oldTime = 0;
              $timeMovement = 0;
              $oldTimeMovement = 0;

              $Query ="SELECT f.speed,f.time FROM tms_gpsdata_fixed f WHERE f.time >='".$TimeFrom."' AND f.time<='".$TimeTo."' AND f.deviceloginname = '".$Imei."' ORDER BY f.time;";

              $Stmt = $this->DB->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($speed,$time);
              while ($Stmt->fetch())
              {
                if (($oldSpeed != 0 && $speed != 0) || ($oldSpeed != 0 && $speed == 0))
                {
                    $timeMovement += $this->OdjDateTime->DifferenceTimeMilesecond($time,$oldTime);
                }
                $oldSpeed = $speed;
                $oldTime = $time;   
                
              }
              $convertDite = $this->OdjDateTime->ConvertMilesecondTime($timeMovement);
              $this->timeMovement = $convertDite;
        }
        
        function GetMovementZone($Imei,$TimeFrom,$TimeTo)
        {
              $i = 0;
              $zoneOut = 0;
              $zoneIn = 0;
              $oldEvent = 0;
              $oldTime = 0;
              
               // $this->GetMileage(357804048666626,'2013-09-30 22:00:00','2013-10-01 05:43:55');   
              $Query = "SELECT  date,eventType  FROM `tms_events` WHERE  DeviceLoginName='".$Imei."'  AND DATE>='".$TimeFrom."' AND DATE<='".$TimeTo."' AND eventtype IN (1,2) AND paramInt IN (64,65,66,69,70,71,72) ORDER BY DATE";

              $Stmt = $this->DB1->prepare($Query);
              $Stmt->execute();       
              $Stmt->bind_result($time,$eventType);
              while ($Stmt->fetch())
              {
              
                if ($eventType == 1 && $i == 0) {$zoneOut += $this->GetMileage($Imei,$TimeFrom,$time);}
                if ($eventType == 2 && $i == 0) {$zoneIn += $this->GetMileage($Imei,$TimeFrom,$time);}
                if ($oldEvent != 0)
                {
                    if ($eventType == 1) { $zoneOut += $this->GetMileage($Imei,$oldTime,$time);}    
                    if ($eventType == 2) { $zoneIn += $this->GetMileage($Imei,$oldTime,$time);}    
                }
                $oldEvent = $eventType;
                $oldTime = $time;
                $i++;    
              }
              if ($eventType == 1) { $zoneOut += $this->GetMileage($Imei,$oldTime,$TimeTo);}    
              if ($eventType == 2) { $zoneIn += $this->GetMileage($Imei,$oldTime,$TimeTo);}    
              
              $this->zoneInMovement =  $zoneIn;
              $this->zoneOutMovement = $zoneOut;
              
        }
        
        
            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,'ArchiveLog','../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);
        } 
        
        
        $i=0;
        while ($i<Count($this->EventStop))
        {
            $EventTimeFrom=$this->OdjDateTime->SubtractionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
            $EventTimeTo=$this->OdjDateTime->AdditionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
            
            $Query = "SELECT latitude,longitude FROM `tms_gpsdata` WHERE TIME>='".$EventTimeFrom."' AND TIME<='".$EventTimeTo."' AND DeviceLoginName='".$Imei."' AND speed=0 LIMIT 1";
            $this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();
            $Stmt->bind_result($Latitude,$Longitude);
            while ($Stmt->fetch()) 
            {            
                $this->EventStopCoord[]=$Latitude;   
                $this->EventStopCoord[]=$Longitude;   
            }
            if ($this->EventStopTime[$i+1])
            {
                $this->EventStopDuration[]=$this->OdjDateTime->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->OdjDateTime->AddTimeGMT($this->EventStopTime[$i],$GMT);
	       	}	
            $i++;
       }
        
                            
    }
    
    
    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->OdjDateTime->SubtractionTimeAndGMT($this->EventParkingTime[$i],0,0,5,0);
            $EventTimeTo=$this->OdjDateTime->AdditionTimeAndGMT($this->EventParkingTime[$i],0,0,5,0);
            
            $Query = "SELECT latitude,longitude FROM `tms_gpsdata` WHERE TIME>='".$EventTimeFrom."' AND TIME<='".$EventTimeTo."' AND DeviceLoginName='".$Imei."' AND speed=0 LIMIT 1";
            $this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
            $Stmt = $this->DB->prepare($Query);
            $Stmt->execute();
            $Stmt->bind_result($Latitude,$Longitude);
            while ($Stmt->fetch()) 
            {            
                $this->EventParkingCoord[]=$Latitude;   
                $this->EventParkingCoord[]=$Longitude;   
            }
            if ($this->EventParkingTime[$i+1])
            {
                $this->EventParkingDuration[]=$this->OdjDateTime->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->OdjDateTime->AddTimeGMT($this->EventParkingTime[$i],$GMT);
	       	} 
       		
           $i++;
       }
        
                            
    }
    
    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 GetTemperature($Imei,$TimeFrom,$TimeTo,$GMT)
    {
        //$tempTimeFrom=$this->OdjDateTime->SubtractionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
        //$tempTimeTo=$this->OdjDateTime->AdditionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
        $GMT = $GMT * 2;    
        $Query = "SELECT sensorValue,ADDTIME(time,'0 ".$GMT.":0:0') FROM tms_sensordata WHERE time>='".$TimeFrom."' AND time<='".$TimeTo."' AND DeviceLoginName='".$Imei."' AND sensorType = 106 AND sensorValue >= -20 AND sensorValue <= 20";
            //$this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($sensorTempValue,$time);
        while ($Stmt->fetch()) 
        {  
            $timeFix= strtotime($time);
            $time = date("Y/m/d H:i:s",$timeFix);            
            $this->sensorTempChart[] = array($time,$sensorTempValue);
        } 
        return  $this->sensorTempChart ;
       // return $Query;
    }
    
        
    function GetTemperatureTable($Imei,$TimeFrom,$TimeTo,$GMT,$step)
    {
        //$tempTimeFrom=$this->OdjDateTime->SubtractionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
        //$tempTimeTo=$this->OdjDateTime->AdditionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
        $Query = "SELECT sensorValue,ADDTIME(time,'0 ".$GMT.":0:0') FROM tms_sensordata WHERE time>='".$TimeFrom."' AND time<='".$TimeTo."' AND DeviceLoginName='".$Imei."' AND sensorType = 106 AND sensorValue >= -20 AND sensorValue <= 20";
            //$this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($sensorTempValue,$time);
        $i = 0;
        $differenceSeconds = 0;
        while ($Stmt->fetch()) 
        {
           if ($i != 0)
           {
                $differenceSeconds = $this->OdjDateTime->DifferenceTimeSecond($time,$this->sensorTempDate[$i-1]); 
           }
           if ($i == 0 || $differenceSeconds >= $step*60)
           {   
            $this->sensorTempValue[$i] = $sensorTempValue;
            $this->sensorTempDate[$i] = $time;
            $i++;
           }
           
        } 
        $this->queryCheck = $differenceSeconds.'----'.$this->sensorTempDate[$i-1].'----'.$time;
    }

    function GetTemperatureTableAllCars($Imei,$TimeFrom,$TimeTo,$GMT,$step, $DevicePortID)
    {
    	//$tempTimeFrom=$this->OdjDateTime->SubtractionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
    	//$tempTimeTo=$this->OdjDateTime->AdditionTimeAndGMT($this->EventStopTime[$i],0,0,5,0);
    	$Query = "SELECT sensorValue,ADDTIME(time,'0 ".$GMT.":0:0') FROM tms_sensordata WHERE time>='".$TimeFrom."' AND time<='".$TimeTo."' AND DeviceLoginName='".$Imei."' AND sensorType IN ($DevicePortID) AND sensorValue >= -20 AND sensorValue <= 20";
    	//$this->ObjLogs->WriteLogs("Method:GetStopsCoord; Query:".$Query,'ArchiveLog','../logs');
    	$Stmt = $this->DB->prepare($Query);
    	$Stmt->execute();
    	$Stmt->bind_result($sensorTempValue,$time);
    	$i = 0;
    	$differenceSeconds = 0;
    	while ($Stmt->fetch())
    	{
    		if ($i != 0)
    		{
    			$differenceSeconds = $this->OdjDateTime->DifferenceTimeSecond($time,$this->sensorTempDate[$i-1]);
    		}
    		if ($i == 0 || $differenceSeconds >= $step*60)
    		{
    			$this->sensorTempValue[$i] = $sensorTempValue;
    			$this->sensorTempDate[$i] = $time;
    			$i++;
    		}
    		 
    	}
    	$this->queryCheck = $differenceSeconds.'----'.$this->sensorTempDate[$i-1].'----'.$time;
    }
    
    
    function GetZonesRuting($Imei,$TimeFrom,$TimeTo,$GMT,$strZone)
    {
        $zoneOut = 0;
        $zoneIn = 0;
        $oldEvent = 0;
        $oldTime = 0;
        
        $Query = "SELECT e.date,e.EventType FROM tms_events e WHERE e.EventType IN (1,2) AND e.date >= '".$TimeFrom."' AND e.date <= '".$TimeTo."' AND e.DeviceLoginName = '".$Imei."' AND e.ParamInt in (".$strZone.") ORDER BY e.date";
        
        $Stmt = $this->DB->prepare($Query);
        $Stmt->execute();
        $Stmt->bind_result($time,$event);
        $i = 0;
        $differenceSeconds = 0;
        while ($Stmt->fetch()) 
        {  
                if ($i == 0 && $event == 1) 
                {
                    $this->arrZoneEvent[$i] = $event;
                    $this->arrZoneTime[$i] = $time;
                }
                else
                {
                    $this->arrZoneEvent[$i] = $event;
                    $this->arrZoneTime[$i] = $time;
                }
                $i++;       
        } 
        //$this->queryCheck = $differenceSeconds.'----'.$this->sensorTempDate[$i-1].'----'.$time;
        $this->queryCheck = $Query;
        
        if ($eventType == 1) { $zoneOut += $this->GetMileage($Imei,$oldTime,$TimeTo);}    
        if ($eventType == 2) { $zoneIn += $this->GetMileage($Imei,$oldTime,$TimeTo);}    
              
        $this->zoneInMovement =  $zoneIn;
        $this->zoneOutMovement = $zoneOut; 
    }
			
//-----end add from 37
		
		
		
		
    }
    
    
    
    
    
function get_distance_between_2_points($gps_1, $gps_2, $decart=false)
{
    if(!$decart)
    {
        $true_angle_1 = get_true_angle($gps_1);
        $true_angle_2 = get_true_angle($gps_2);
        
        $point_radius_1 = get_point_radius($gps_1, $true_angle_1);
        $point_radius_2 = get_point_radius($gps_2, $true_angle_2);
        
        $earth_point_1_x = $point_radius_1 * cos(deg2rad($true_angle_1));
        $earth_point_1_y = $point_radius_1 * sin(deg2rad($true_angle_1));
        
        $earth_point_2_x = $point_radius_2 * cos(deg2rad($true_angle_2));
        $earth_point_2_y = $point_radius_2 * sin(deg2rad($true_angle_2));
        
        $x = get_distance_between_2_points(array('lat'=>$earth_point_1_x, 'lon'=>$earth_point_1_y), array('lat'=>$earth_point_2_x, 'lon'=>$earth_point_2_y), true);
        $y = pi() *  (  ($earth_point_1_x + $earth_point_2_x) / 360 ) * ( $gps_1['lon'] - $gps_2['lon'] );

        return sqrt( pow($x,2) + pow($y,2) );
    }
    else
    {
        return sqrt(pow(($gps_1['lat'] - $gps_2['lat']), 2) + pow(($gps_1['lon'] - $gps_2['lon']), 2));
    }
}

//returns degree's decimal measure, getting degree, minute and second
function get_decimal_degree($deg=0, $min=0, $sec=0)
{
    return ($deg<0) ? (-1*(abs($deg) + (abs($min)/60) + (abs($sec)/3600))) : (abs($deg) + (abs($min)/60) + (abs($sec)/3600));
}

// get point, returns true angle
function get_true_angle($gps)
{
    return atan(    (  (MINOR_AXIS_POW_2 / MAJOR_AXIS_POW_2) * tan(deg2rad( $gps['lat']))    )  ) * 180/pi(); 
}

//get point and true angle, returns radius of small circle (radius between meridians) 
function get_point_radius($gps, $true_angle)
{
    return (1 / sqrt((pow(cos(deg2rad($true_angle)), 2) / MAJOR_AXIS_POW_2) + (pow(sin(deg2rad($true_angle)), 2) / MINOR_AXIS_POW_2))) + $gps['point_elevation']; 
}



function check_lat($lat)
{
    if($lat>=0 && $lat<=90)
    {
        return 'north';
    }
    else
    if($lat>=-90 && $lat<=0)
    {
        return 'south';
    }

    return false;
}

function check_lon($lon)
{
    if($lon>=0 && $lon<=180)
    {
        return 'east';
    }
    else
    if($lon>=-180 && $lon<=0)
    {
        return 'west';
    }

    return false;

}


/*function GetGeolocationInnotech($geox,$geoy){
	ob_clean();
	ob_implicit_flush();
	
	//global $server;
	//global $port;
	include("settings.php");
	
	$smes = '{"P":{"X":'.$geox.',"Y":'.$geoy.'},"T":1}';
	
	$ObjReportRun= new Report();
	$ObjReportRun->ObjLogs->WriteLogs("GetGeolocationInnotech: ".$smes,'ReportLog','../logs');
	
	$reply='';
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("ConnectError");
    $connection = socket_connect($socket, $server, $port) or die("ConnectError");
	if (socket_write($socket, $smes) === false) fclose($socket);
	$reply = socket_read($socket,1024);
	socket_shutdown($socket,2);
	return $reply;
	socket_close($socket);
	ob_end_flush();
	ob_clean();
}*/






?>
