<?php
	header('Content-Type: text/html; charset=utf-8');
	include "settings.php";
	
	error_reporting(0);
	
	ob_start("ob_gzhandler");
	ini_set('zlib.output_compression', 'On');
	
	
	set_time_limit(600);
  
	function writeToLogFile($msg){
     $today = date("Y_m_d");
     $logfile = $today."_log_Zip.txt";
     $dir = 'logs';
     $saveLocation=$dir . '/' . $logfile;
     if  (!$handle = @fopen($saveLocation, "a")) {
          exit;
     } else {
          if (@fwrite($handle,"$msg\r\n") === FALSE) {
               exit;
          }
   
          @fclose($handle);
     }
	}
  
	$db = new mysqli($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
	$db->query("SET CHARSET SET utf8");
	$db->query("SET NAMES 'utf8'");
	if (mysqli_connect_errno()) {
		echo "Error connecting to DB";
		exit;
	}
  
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro <> '.$_POST['data'] );

	$data = $_POST['data'];
	$data = stripslashes($data);
	$arraydata = (array)json_decode($data,true);
  
	function getGMT($id_user){
		global $db;
				$query = "SELECT s.`gmt` FROM tms_device td INNER JOIN `wm_settings` s ON s.`client_id` = td.`Client_id` WHERE td.id = ".$id_user.";";
				writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> getGMT <> '.$query);
				if($stmt = $db->prepare($query)){
				if($stmt->execute()){
				$stmt->bind_result($gmt);
				$stmt->fetch();
				$stmt->close(); 
				}else{ $gmt=0; }
				}else{ $gmt=0; }
		
		date_default_timezone_set("UTC");
		$date = time() + $gmt*60*60;
		//if($gmt < 0){
		//	$date = time() - abs($gmt)*60*60;
		//}else{
		//	$date = time() + $gmt*60*60;
		//}
		
		return $date;
	}
  
  
  
  
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  if ($arraydata['func']=='tms_facttrip')
  {
	//$startLine = $arraydata["startLine"];
	$lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
	
	$time = getGMT($iduser);
	$dateFrom = date('Y-m-d',$time)." 00:00:00";
	$dateTo = date('Y-m-d',$time)." 23:59:59";

	//$where = "AND tt.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	$where = "AND tt.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."'";
	//$where = "AND tt.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."' AND (tt.`Closed` = 2 OR tt.`Closed` = 0)";
	
	
	$i=0;
	
	/*if($lastsynch){
		$where = " AND tt.`Last_modification_time`>'".$lastsynch."'";
	}else{
		$where = "AND tt.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	}*/
	/*if($lastsynch){
		$where = "AND tt.`StartTime` BETWEEN '".$lastsynch." 00:00:00' AND '".date('Y-m-d')." 23:59:59' AND tp.`Executing`=1";
	}else{
		$mn = strtotime(date('Y-m-d',mktime(1,1,1,date('m'),date('d')-3,date('Y'))));
		$nmn = date('Y-m-d',$mn);
		$where = "AND tt.`StartTime` BETWEEN '".$nmn." 00:00:00' AND '".date('Y-m-d')." 23:59:59' AND tp.`Executing`=1";
	}*/
	//$where = "AND tt.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59' AND tp.`Executing`=1";


	$query = "SELECT tt.`ID`, tt.`Closed`, tt.`Project_Id`, tt.`Car_ID`, tt.`Name`, tt.`WalkerNum`, tt.`TripPrice`, tt.`Distance`, tt.`Time`, tt.`Comments`, tt.`StartTime`, tt.`EndTime`, td.`ID`, tt.`TripId` FROM `tms_facttrip` tt LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID` WHERE td.`ID`=".$iduser." ".$where.";";
	//$query = "SELECT tt.`ID`, tt.`Closed`, tt.`Project_Id`, tt.`Car_ID`, tt.`Name`, tt.`WalkerNum`, tt.`TripPrice`, tt.`Distance`, tt.`Time`, tt.`Comments`, tt.`StartTime`, tt.`EndTime`, td.`ID`,tt.`Last_modification_time` FROM `tms_facttrip` tt LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID` WHERE td.`ID`=".$iduser." ".$where.";";
  
  //$query = "SELECT tt.`ID`, tt.`Closed`, tt.`Project_Id`, tt.`Car_ID`, tt.`Name`, tt.`WalkerNum`, tt.`TripPrice`, tt.`Distance`, tt.`Time`, tt.`Comments`, tt.`StartTime`, tt.`EndTime`, td.`ID` FROM `tms_facttrip` tt LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID` WHERE td.`ID`=(SELECT t_cr.`Device_id` FROM tms_driver t_dr LEFT JOIN tms_car t_cr ON t_dr.`Driver_ID`=t_cr.`Driver_id` WHERE t_cr.`DeletedRecord`=0 AND t_dr.`DeletedRecord`=0 AND t_dr.`Device_id`=".$iduser." LIMIT 1) ".$where;
	//$query = "SELECT tt.`ID`, tt.`Closed`, tt.`Project_Id`, tt.`Car_ID`, tt.`Name`, tt.`WalkerNum`, tt.`TripPrice`, tt.`Distance`, tt.`Time`, tt.`Comments`, tt.`StartTime`, tt.`EndTime`, td.`ID` FROM `tms_facttrip` tt LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` WHERE td.`ID`=".$iduser." ";
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip <> '.$query );
	if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $stmt->bind_result($TripId,$Closed,$Project_Id,$Car_ID,$Name,$WalkerNum,$TripPrice,$Distance,$Time,$Comments,$StartTime,$EndTime,$User_ID,$PlanTripID);
      //$stmt->bind_result($TripId,$Closed,$Project_Id,$Car_ID,$Name,$WalkerNum,$TripPrice,$Distance,$Time,$Comments,$StartTime,$EndTime,$User_ID,$Last_modification_time);
      $Model = array();
	  while ($stmt->fetch()) {
        $Model[$i]= 
        array(
		'TID'=>$TripId,
		'CL'=>$Closed,
		'PID'=>$Project_Id,
		'CID'=>$Car_ID,
		'N'=>addslashes($Name),
		'WN'=>$WalkerNum,
		'PR'=>$TripPrice,
		'D'=>$Distance,
		'T'=>$Time,
		'C'=>addslashes($Comments),
		'ST'=>$StartTime,
		'ET'=>$EndTime,
		'UID'=>$User_ID,
		'PTID'=>$PlanTripID
		//'LM'=>addslashes($Last_modification_time)
        );
        $i++;
      }
	  
	/*if($i < 1000){
      $arrayEndModel = array('EndModel'=>'true');
      array_push($Model,$arrayEndModel);
    }*/
	
      $stmt->close();
      $db->close();
    }
    echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip <> '.json_encode($Model) );
	exit;
  }
  
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
  if ($arraydata['func']=='tms_checkpoint')
  {
	//$startLine = $arraydata["startLine"];
	
	$lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
	
	$time = getGMT($iduser);
	$dateFrom = date('Y-m-d',$time)." 00:00:00";
	$dateTo = date('Y-m-d',$time)." 23:59:59";
	
	//$where = "AND ft.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	$where = "AND ft.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."'";
	//$where = "AND ft.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."' AND (ft.`Closed` = 2 OR ft.`Closed` = 0)";
	
	$i=0;
	
	/*if($lastsynch){
		$where = " AND fc.`Last_modification_time`>'".$lastsynch."'";
	}else{
		$where = "AND ft.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	}*/
	
	/*if($lastsynch){ $where = " AND ft.`StartTime` BETWEEN '".$lastsynch." 00:00:00' AND '".date('Y-m-d')." 23:59:59'"; }else{
		$mn = strtotime(date('Y-m-d',mktime(1,1,1,date('m'),date('d')-3,date('Y'))));
		$nmn = date('Y-m-d',$mn);
		$where = "AND ft.`StartTime` BETWEEN '".$nmn." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	}*/
	

$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,ROUND(fc.`DurationInPoint`),fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName`
,wh.`ContactPerson`, o.CustomStr3, o.CustomStr4, TIME(o.`StartTime`), TIME(o.`EndTime`), wh.`Code`,o.`Priority`, o.`CustomStr2`, o.`CustomDouble`
FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
LEFT JOIN tms_order o ON (o.`Code`= fc.`Code` AND o.`Project_ID` = ft.`Project_Id`)
LEFT JOIN tms_warehouse wh ON (o.`Warehouse_ID` = wh.`Warehouse_ID` AND wh.DeletedRecord = 0)
WHERE td.`ID`=".$iduser." ".$where." ORDER BY fc.`EstimateTime` ASC;";
    
  //$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,fc.`DurationInPoint`,fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName` FROM `tms_facttrip` ft INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID` LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` WHERE td.`ID`=".$iduser." ".$where." ORDER BY fc.`EstimateTime` ASC;";
  
  //$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,fc.`DurationInPoint`,fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName`,fc.`Last_modification_time` FROM `tms_facttrip` ft INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID` LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` WHERE td.`ID`=".$iduser." ".$where." ORDER BY fc.`EstimateTime` ASC;";
  
  //$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,fc.`DurationInPoint`,fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName` FROM `tms_facttrip` ft INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID` LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` WHERE td.`ID`=(SELECT t_cr.`Device_id` FROM tms_driver t_dr LEFT JOIN tms_car t_cr ON t_dr.`Driver_ID`=t_cr.`Driver_id` WHERE t_cr.`DeletedRecord`=0 AND t_dr.`DeletedRecord`=0 AND t_dr.`Device_id`=".$iduser." LIMIT 1) ".$where." ORDER BY fc.`EstimateTime` ASC";
	//$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,fc.`DurationInPoint`,fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName` FROM `tms_facttrip` ft INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID` LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID` LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID` WHERE td.`ID`=".$iduser." ORDER BY fc.`EstimateTime` ASC";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_checkpoint <> '.$query );
	if($stmt = $db->prepare($query)){
      $stmt->execute();
      $stmt->bind_result($TripId,$Id,$StartCheckTime,$EndCheckTime,$Description,$Necessary,$Name,$GeoX,$GeoY,$PointState,$Date,$OrderInTrip,$Distance,$Time,$WaitTime,$LateTime,$Route,$EstimateTime,$Address,$DurationInPoint,$Type,$StartWorkTime,$EndWorkTime,$Code,$ClientName,$phone,$CustomStr3,$CustomStr4,$StartTime,$EndTime,$wCode,$Priority,$CustomStr2,$CustomDouble);
	  //$stmt->bind_result($TripId,$Id,$StartCheckTime,$EndCheckTime,$Description,$Necessary,$Name,$GeoX,$GeoY,$PointState,$Date,$OrderInTrip,$Distance,$Time,$WaitTime,$LateTime,$Route,$EstimateTime,$Address,$DurationInPoint,$Type,$StartWorkTime,$EndWorkTime,$Code,$ClientName,$Last_modification_time);
      $Model = array();
	  while ($stmt->fetch()){
        $Model[$i]=array(
		'TID'=>$TripId,
		'ID'=>$Id,
        'SCT'=>$StartCheckTime,
		'ECT'=>$EndCheckTime,
		'D'=>addslashes($Description),
		'NSS'=>$Necessary,
		'N'=>addslashes($Name),
		'GX'=>$GeoX,
		'GY'=>$GeoY,
		'PS'=>$PointState,
		'DT'=>$Date,
		'OIT'=>$OrderInTrip,
		'DS'=>$Distance,
		'T'=>$Time,
		'WT'=>$WaitTime,
		'LT'=>$LateTime,
		'R'=>$Route,
		'ET'=>$EstimateTime,
		'A'=>addslashes($Address),
		'DIP'=>$DurationInPoint,
		'TY'=>$Type,
		'SW'=>$StartWorkTime,
		'EW'=>$EndWorkTime,
		'CD'=>$Code,
		'CN'=>addslashes($ClientName),
		'PH'=>addslashes($phone),
		'C3'=>addslashes($CustomStr3),
		'C4'=>addslashes($CustomStr4),
		'STT'=>addslashes($StartTime),
		'ENT'=>addslashes($EndTime),
		'WCD'=>$wCode,
		'P'=>$Priority,
		'C2'=>addslashes($CustomStr2),
		'CDB'=>addslashes($CustomDouble)
		//'LM'=>addslashes($Last_modification_time)
		
        );
        $i++;
      }
	
      $stmt->close();
      $db->close();
    }
    echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_trippoint <> '.json_encode($Model) );
	exit;
  }
 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 if ($arraydata['func']=='tms_checkpointcargo')
 {
	$lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
	/*if($lastsynch){ $where = " AND ft.`StartTime` BETWEEN '".$lastsynch." 00:00:00' AND '".date('Y-m-d')." 23:59:59'"; }else{
		$mn = strtotime(date('Y-m-d',mktime(1,1,1,date('m'),date('d')-3,date('Y'))));
		$nmn = date('Y-m-d',$mn);
		$where = "AND ft.`StartTime` BETWEEN '".$nmn." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	}*/
	
	$time = getGMT($iduser);
	$dateFrom = date('Y-m-d',$time)." 00:00:00";
	$dateTo = date('Y-m-d',$time)." 23:59:59";
	
	//$where = "AND ft.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
	$where = "AND ft.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."'";
	//$where = "AND ft.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."' AND (ft.`Closed` = 2 OR ft.`Closed` = 0)";
	
	$i=0;
/*$query = "SELECT fcc.`ID`,ft.`TripId`,fcc.`CheckPoint_ID`,fcc.`Name`,du.`Name`,fcc.`CargoValueVolume`,fcc.`CargoValueWeight`,fcc.`Comments`,fcc.`State`,fcc.`RealCargoValue`,fcc.`CargoValueCount`,fcc.`Cost` FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
INNER JOIN `tms_checkpointcargo` fcc ON fc.`Id`=fcc.`CheckPoint_ID`
INNER JOIN `tms_dimensionunit` du ON du.`Id`=fcc.`DimensionUnitWeight_ID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
WHERE td.`ID`=".$iduser." ".$where." ORDER BY fc.`EstimateTime` ASC;";*/

/*$query = "SELECT fcc.`ID`,ft.`ID`,fcc.`CheckPoint_ID`,fcc.`Name`,du.`Name`,fcc.`CargoValueVolume`,fcc.`CargoValueWeight`,fcc.`Comments`,fcc.`State`,fcc.`RealCargoValue`,fcc.`CargoValueCount`,fcc.`Cost` FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
INNER JOIN `tms_checkpointcargo` fcc ON fc.`Id`=fcc.`CheckPoint_ID`
INNER JOIN `tms_dimensionunit` du ON du.`Id`=fcc.`DimensionUnitWeight_ID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
WHERE td.`ID`=(SELECT t_cr.`Device_id` FROM tms_driver t_dr LEFT JOIN tms_car t_cr ON t_dr.`Driver_ID`=t_cr.`Driver_id` WHERE t_cr.`DeletedRecord`=0 AND t_dr.`DeletedRecord`=0 AND t_dr.`Device_id`=".$iduser." LIMIT 1)
".$where." ORDER BY fc.`EstimateTime` ASC ";*/

$query = "SELECT fcc.`ID`,ft.`ID`,fcc.`CheckPoint_ID`,fcc.`Name`,du.`Name`,du2.`Name`,fcc.`CargoValueVolume`,fcc.`CargoValueWeight`,fcc.`Comments`,fcc.`State`,fcc.`RealCargoValue`,fcc.`CargoValueCount`,fcc.`Cost` FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
INNER JOIN `tms_checkpointcargo` fcc ON fc.`Id`=fcc.`CheckPoint_ID`
INNER JOIN `tms_dimensionunit` du ON du.`Id`=fcc.`DimensionUnitWeight_ID`
INNER JOIN `tms_dimensionunit` du2 ON du2.`Id`=fcc.`DimensionUnitCount_ID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
WHERE td.`ID`=".$iduser." ".$where.";";

	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_checkpointcargo <> '.$query );
	
	if($stmt = $db->prepare($query)){
      $stmt->execute();
      $stmt->bind_result($ID,$TripId,$CheckPoint_ID,$Name,$DimensionUnit,$DimensionCount,$CargoValueVolume,$CargoValueWeight,$Comments,$State,$RealCargoValue,$CargoValueCount,$Cost);
      $Model = array();
	  while ($stmt->fetch()){
        $Name = str_replace('###','',$Name);
		$Model[$i]=array(
		'ID'=>$ID,
		'TID'=>$TripId,
        'CID'=>$CheckPoint_ID,
		'N'=>addslashes($Name),
		'DU'=>$DimensionUnit,
		'CVV'=>$CargoValueVolume,
		'CVW'=>$CargoValueWeight,
		'CO'=>addslashes($Comments),
		'ST'=>$State,
		'RCV'=>$RealCargoValue,
		'CVC'=>$CargoValueCount,
		'CT'=>$Cost,
		'DC'=>addslashes($DimensionCount),
        );
        $i++;
      }
	
      $stmt->close();
      $db->close();
    }
	echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_checkpointcargo <> '.json_encode($Model) );
	exit;
 }
 
  
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  
  
 if ($arraydata['func']=='wm_mobile_settings')
 {
	$iduser = $arraydata["iduser"];
	$i=0;
/*$query = "SELECT stg.`id`, stg.`setting_name`, stg.`description`, ustg.`state`  FROM `wm_mobile_settings` stg INNER JOIN `wm_user_mobile_settings` ustg ON ustg.`setting_id` = stg.`id` WHERE ustg.`client_id` = (SELECT client_id FROM tms_device WHERE  id = '".$iduser."')
UNION 
SELECT id,`setting_name`, description, 0 FROM `wm_mobile_settings` WHERE id NOT IN (SELECT `setting_id` FROM `wm_user_mobile_settings` WHERE `client_id` = (SELECT client_id FROM tms_device WHERE id = '".$iduser."'))";*/
$query = "SELECT stg.`id`, stg.`setting_name`, stg.`description`, ustg.`state`
FROM `wm_mobile_settings` stg INNER JOIN `wm_user_mobile_settings` ustg ON ustg.`setting_id` = stg.`id`
WHERE (ustg.`client_id` = (SELECT client_id FROM tms_device WHERE  id = '".$iduser."') OR 
ustg.`client_id` = -1)
UNION 
SELECT id,`setting_name`, description, 0
FROM `wm_mobile_settings`
WHERE id NOT IN (SELECT `setting_id` FROM `wm_user_mobile_settings` WHERE `client_id` = (SELECT client_id FROM tms_device WHERE id = '".$iduser."') OR `client_id` = -1);";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_mobile_settings <> '.$query );
	if($stmt = $db->prepare($query)){
    if($stmt->execute()){
      $stmt->bind_result($id,$setting_name,$description,$state);
      $Model = array();
	  while ($stmt->fetch()){
		$Model[$i]=array(
		'id'=>$id,
		'setting_name'=>addslashes($setting_name),
        'description'=>addslashes($description),
		'state'=>$state
        );
        $i++;
      }
	
      $stmt->close();
      $db->close();
    }
	}
	echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_mobile_settings <> '.json_encode($Model) );
	exit;
	
 }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  if ($arraydata['func']=='tms_mob_task')
  {
    $lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
    
	$time = getGMT($iduser);
	$dateFrom = date('Y-m-d',$time)." 00:00:00";
	$dateTo = date('Y-m-d',$time)." 23:59:59";
	
	if($lastsynch){
		//$lastsynch = strtotime($lastsynch) - $gmt*60*60; 
		//$lastsynch = date('Y-m-d H:i:s',$lastsynch);
		
		$where = " AND mt.`Last_modification_time`>'".$lastsynch."'";
	}else{
		//$where = "AND mt.`Date` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
		//$where = "AND ft.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59'";
		$where = "AND ft.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."'";
	}
	
	
    $i=0;
    //$query = "SELECT ID,Name,Address,Contact_person,Description,State,CancelComments,Date,TabletId,TripId FROM tms_mob_task ".$where." ORDER BY Date DESC;";
    
	$query = "SELECT mt.ID,mt.Name,mt.Address,mt.Contact_person,mt.Description,mt.State,mt.CancelComments,mt.Date,mt.TabletId,mt.TripId,mt.`Last_modification_time` FROM tms_mob_task mt INNER JOIN `tms_facttrip` ft ON mt.`TripId` = ft.`ID` WHERE mt.`TabletId`=".$iduser." ".$where.";";
	//$query = "SELECT mt.ID,mt.Name,mt.Address,mt.Contact_person,mt.Description,mt.State,mt.CancelComments,mt.Date,mt.TabletId,mt.TripId FROM tms_mob_task mt INNER JOIN `tms_facttrip` ft ON mt.`TripId` = ft.`ID` WHERE mt.`TabletId`=(SELECT t_d.`Device_id` FROM tms_car t_c LEFT JOIN tms_driver t_d ON t_c.`Driver_id` = t_d.`Driver_ID` WHERE t_c.`Device_id`= ".$iduser." AND t_c.`DeletedRecord`=0) ".$where.";";
	
	
    //writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_mob_task <> '.$query );
         
    if($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($ID, $Name, $Address, $Contact_person, $Description, $State, $CancelComments, $Date, $TabletId, $TripId, $Last_modification_time);
      $Model = array();
	  while ($stmt->fetch())
      {
        $Model[$i]=array(
                        'ID'=>$ID,
                        'Name'=>addslashes($Name),
                        'Address'=>addslashes($Address),
                        'Contact_person'=>addslashes($Contact_person),
						'Description'=>addslashes($Description),
						'State'=>$State,
						'CancelComments'=>addslashes($CancelComments),
						'Date'=>$Date,
						'TabletId'=>$TabletId,
						'TripId'=>$TripId,
						'Last_modification_time'=>$Last_modification_time
                        );
        $i++;
      }
    
      $stmt->close();
      $db->close();
    }
    
    echo json_encode($Model);
	
	//echo '[{"ID":1,"Name":"Name","Address":"Address","Contact_person":"","Description":"","State":0,"CancelComments":"","Date":"2015-10-16 12:31:33","TabletId":2549,"TripId":1210,"Last_modification_time":"2015-10-16 12:33:35"}]';
	
    //writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_mob_task <> '.json_encode($Model) );
	exit;
  }
  
  
	if ($arraydata['func']=='LastSynch')
	{
		
		if(!isset($arraydata["iduser"]) || $arraydata["iduser"]=="" ){
			$time = time();
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro LastSynch iduser empty<> ' );
		}else{
			$iduser = $arraydata["iduser"];
			$time = getGMT($iduser);
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro LastSynch iduser <> '.$iduser );
		}
		
		$date = date('Y-m-d H:i:s',$time);
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro LastSynch date <> '.$date );
		
		//echo json_encode($Model[0] = array('lastsynch'=>date('Y-m-d H:i:s')));
		echo json_encode($Model[0] = array('lastsynch'=>$date));
		exit;
	}
	
	
	
	
	// ----- Avtozvuk speedometer value load ------------------
	if ($arraydata['func']=='tms_speedometer_value')
	{
    $lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
    
	$time = getGMT($iduser);
	$date = date('Y-m-d',$time);
	
    $i=0;
	$query = "SELECT `Date`,`Start`,`End` FROM `tms_speedometer_value` WHERE `DeviceId`=".$iduser." AND DATE(`Date`) = '".$date."';";
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_speedometer_value <> '.$query );  
    if($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($Date, $Start, $End);
      $Model = array();
	  while ($stmt->fetch())
      {
        $Model[$i]=array(
                        'Date'=>$Date,
                        'Start'=>$Start,
                        'End'=>$End
                        );
        $i++;
      }
    
      $stmt->close();
      $db->close();
    }
    
    echo json_encode($Model);
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_speedometer_value <> '.json_encode($Model) );
	exit;
	}
	// ----- Avtozvuk speedometer value load ------------------
	
	// Причины отказа


  if ($arraydata['func']=='wm_reasons')
  {
    
	$iduser = $arraydata["iduser"];
	$i=0;
    
	//$query = "SELECT id, name FROM wm_reasons WHERE instance_id = (SELECT `Client_id` FROM `tms_device` WHERE `ID` = ".$iduser.");";
$query = "SELECT id, NAME FROM wm_reasons WHERE
(SELECT
IF( (SELECT `Client_id` FROM `tms_device` WHERE `ID` = ".$iduser."), instance_id = (SELECT `Client_id` FROM `tms_device` WHERE `ID` = ".$iduser."), 0=0 )
FROM wm_reasons LIMIT 1
);";

	
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_reasons <> '.$query );
         
    if($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($id, $name);
      $Model = array();
	  while ($stmt->fetch())
      {
        $Model[$i]=array(
			'id'=>$id,
			'name'=>$name
		);
        $i++;
      }
    
      $stmt->close();
      $db->close();
    }
    
    echo json_encode($Model);
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_reasons <> '.json_encode($Model) );
	exit;
  }
  
  
  
// Фоновая синхронизация рейса

	if ($arraydata['func']=='tms_facttrip_checkpoint')
	{
	$FactTripID = $arraydata["FactTripID"];
	$Model = array();
	$countOriginal = $arraydata["count"];
	$TripID = $arraydata["TripID"];
	
	//
	$count = -1;
	if($countOriginal>0){
	$query = "SELECT COUNT(ID) as count FROM `tms_checkpoint` WHERE `FactTripID`=".$FactTripID.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint <> '.$query );
	if ($stmt = $db->prepare($query)){
    if ($stmt->execute()){
		$stmt->bind_result($count);
		while ($stmt->fetch()) {
			
		}
	}
	}
	}
	
	if($countOriginal == 0){
	$query = "SELECT ID FROM `tms_facttrip` WHERE `TripId` = ".$TripID." AND ID <> ".$FactTripID.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint <> '.$query );
	if ($stmt = $db->prepare($query)){
    if ($stmt->execute()){
		$stmt->bind_result($ID);
		while ($stmt->fetch()) {
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint ID <> '.$ID );
			$FactTripID = $ID;
			$count = 0;
		}
	}
	}
	}
	
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint TripID<> '.$TripID );
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint FactTripID<> '.$FactTripID );
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint count <> '.$count );
	
	//$count = 5;
	if( $count > $countOriginal || $count == 0 ){
	
	$query = "SELECT tt.`ID`, tt.`Closed`, tt.`Project_Id`, tt.`Car_ID`, tt.`Name`, tt.`WalkerNum`, tt.`TripPrice`, tt.`Distance`, tt.`Time`, tt.`Comments`, tt.`StartTime`, tt.`EndTime`, td.`ID`, tt.`TripId`
FROM `tms_facttrip` tt
LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID`
WHERE tt.`ID` = ".$FactTripID.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint <> '.$query );
	$Model1 = array();
	$i=0;
	if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $stmt->bind_result($TripId,$Closed,$Project_Id,$Car_ID,$Name,$WalkerNum,$TripPrice,$Distance,$Time,$Comments,$StartTime,$EndTime,$User_ID,$PlanTripID);
	  while ($stmt->fetch()) {
        $Model1[$i]= 
        array(
		'TID'=>$TripId,
		'CL'=>$Closed,
		'PID'=>$Project_Id,
		'CID'=>$Car_ID,
		'N'=>addslashes($Name),
		'WN'=>$WalkerNum,
		'PR'=>$TripPrice,
		'D'=>$Distance,
		'T'=>$Time,
		'C'=>addslashes($Comments),
		'ST'=>$StartTime,
		'ET'=>$EndTime,
		'UID'=>$User_ID,
		'PTID'=>$PlanTripID
		//'LM'=>addslashes($Last_modification_time)
        );
        $i++;
      }
      $stmt->close();
	}
	
	$query = "SELECT ft.`ID`,fc.`Id`,fc.`StartCheckTime`,fc.`EndCheckTime`,fc.`Description`,fc.`Necessary`,fc.`Name`,fc.`GeoX`,fc.`GeoY`,fc.`PointState`,fc.`Date`,fc.`OrderInTrip`,fc.`Distance`,fc.`Time`,fc.`WaitTime`,fc.`LateTime`,ASTEXT(fc.`Route`),fc.`EstimateTime`,fc.`Address`,ROUND(fc.`DurationInPoint`),fc.`IsOrderPoint`,fc.`StartWorkTime`,fc.`EndWorkTime`,fc.`Code`,fc.`ClientName`
,wh.`ContactPerson`, o.CustomStr3, o.CustomStr4, TIME(o.`StartTime`), TIME(o.`EndTime`), wh.`Code`, o.`Priority`, o.`CustomStr2`, o.`CustomDouble`
FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
LEFT JOIN tms_order o ON (o.`Code`= fc.`Code` AND o.`Project_ID` = ft.`Project_Id`)
LEFT JOIN tms_warehouse wh ON (o.`Warehouse_ID` = wh.`Warehouse_ID` AND wh.DeletedRecord = 0)
WHERE ft.`ID` = ".$FactTripID." ORDER BY fc.`EstimateTime` ASC;";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint <> '.$query );
	$Model2 = array();
	$i=0;
	if($stmt = $db->prepare($query)){
      $stmt->execute();
      $stmt->bind_result($TripId,$Id,$StartCheckTime,$EndCheckTime,$Description,$Necessary,$Name,$GeoX,$GeoY,$PointState,$Date,$OrderInTrip,$Distance,$Time,$WaitTime,$LateTime,$Route,$EstimateTime,$Address,$DurationInPoint,$Type,$StartWorkTime,$EndWorkTime,$Code,$ClientName,$phone,$CustomStr3,$CustomStr4,$StartTime,$EndTime,$wCode,$Priority,$CustomStr2,$CustomDouble);
	  while ($stmt->fetch()){
        $Model2[$i]=array(
		'TID'=>$TripId,
		'ID'=>$Id,
        'SCT'=>$StartCheckTime,
		'ECT'=>$EndCheckTime,
		'D'=>addslashes($Description),
		'NSS'=>$Necessary,
		'N'=>addslashes($Name),
		'GX'=>$GeoX,
		'GY'=>$GeoY,
		'PS'=>$PointState,
		'DT'=>$Date,
		'OIT'=>$OrderInTrip,
		'DS'=>$Distance,
		'T'=>$Time,
		'WT'=>$WaitTime,
		'LT'=>$LateTime,
		'R'=>$Route,
		'ET'=>$EstimateTime,
		'A'=>addslashes($Address),
		'DIP'=>$DurationInPoint,
		'TY'=>$Type,
		'SW'=>$StartWorkTime,
		'EW'=>$EndWorkTime,
		'CD'=>$Code,
		'CN'=>addslashes($ClientName),
		'PH'=>addslashes($phone),
		'C3'=>addslashes($CustomStr3),
		'C4'=>addslashes($CustomStr4),
		'STT'=>addslashes($StartTime),
		'ENT'=>addslashes($EndTime),
		'WCD'=>$wCode,
		'P'=>$Priority,
		'C2'=>addslashes($CustomStr2),
		'CDB'=>addslashes($CustomDouble)
		//'LM'=>addslashes($Last_modification_time)
        );
        $i++;
      }
	
      $stmt->close();
    }
	
	
	
	$query = "SELECT fcc.`ID`,ft.`ID`,fcc.`CheckPoint_ID`,fcc.`Name`,du.`Name`,du2.`Name`,fcc.`CargoValueVolume`,fcc.`CargoValueWeight`,fcc.`Comments`,fcc.`State`,fcc.`RealCargoValue`,fcc.`CargoValueCount`,fcc.`Cost` FROM `tms_facttrip` ft
INNER JOIN `tms_checkpoint` fc ON ft.`ID`=fc.`FactTripID`
INNER JOIN `tms_checkpointcargo` fcc ON fc.`Id`=fcc.`CheckPoint_ID`
INNER JOIN `tms_dimensionunit` du ON du.`Id`=fcc.`DimensionUnitWeight_ID`
INNER JOIN `tms_dimensionunit` du2 ON du2.`Id`=fcc.`DimensionUnitCount_ID`
LEFT JOIN `tms_car` tc ON ft.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
WHERE ft.`ID` = ".$FactTripID.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint <> '.$query );
	$Model3 = array();
	$i=0;
	if($stmt = $db->prepare($query)){
      $stmt->execute();
      $stmt->bind_result($ID,$TripId,$CheckPoint_ID,$Name,$DimensionUnit,$DimensionCount,$CargoValueVolume,$CargoValueWeight,$Comments,$State,$RealCargoValue,$CargoValueCount,$Cost);
	  while ($stmt->fetch()){
        $Name = str_replace('###','',$Name);
		$Model3[$i]=array(
		'ID'=>$ID,
		'TID'=>$TripId,
        'CID'=>$CheckPoint_ID,
		'N'=>addslashes($Name),
		'DU'=>$DimensionUnit,
		'CVV'=>$CargoValueVolume,
		'CVW'=>$CargoValueWeight,
		'CO'=>addslashes($Comments),
		'ST'=>$State,
		'RCV'=>$RealCargoValue,
		'CVC'=>$CargoValueCount,
		'CT'=>$Cost,
		'DC'=>addslashes($DimensionCount),
        );
        $i++;
      }
	
      $stmt->close();
    }
	
	
	
	/*$query = "SELECT tt.`ID`,db.`ID`,db.`OrderCode`,
db.`Debet_plan_subsection`,db.`Debet_plan_order`,db.`Debet_plan_cost`,db.`Debet_fact_subsection`,db.`Debet_fact_order`,db.`Debet_fact_cost`,
db.`Conteiner_plan_name`,db.`Conteiner_plan_count`,db.`Conteiner_fact_name`,db.`Conteiner_fact_count`,
db.`Tro_plan_type`,db.`Tro_plan_count`,db.`Tro_fact_type`,db.`Tro_fact_count`,db.`Project_ID`
FROM `tms_facttrip` tt
INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID`
INNER JOIN `tms_debts_ordersource` db ON tt.`Project_Id`=db.`Project_ID`
AND db.`Debet_fact_subsection` IN (SELECT NAME FROM tms_checkpoint WHERE FacttripID =tt.ID AND IsOrderPoint = 1)
AND (db.`Debet_plan_subsection` IS NOT NULL OR db.`Conteiner_plan_name` IS NOT NULL OR db.`Tro_plan_type` IS NOT NULL)
WHERE tt.`ID` = ".$FactTripID." GROUP BY db.`ID`;";*/

	$query = "SELECT 
".$FactTripID.",db.`ID`,db.`OrderCode`,
db.`Debet_plan_subsection`,db.`Debet_plan_order`,db.`Debet_plan_cost`,db.`Debet_fact_subsection`,db.`Debet_fact_order`,db.`Debet_fact_cost`,
db.`Conteiner_plan_name`,db.`Conteiner_plan_count`,db.`Conteiner_fact_name`,db.`Conteiner_fact_count`,
db.`Tro_plan_type`,db.`Tro_plan_count`,db.`Tro_fact_type`,db.`Tro_fact_count`,db.`Project_ID`
FROM `tms_debts_ordersource` db 
WHERE db.`Project_ID` = (SELECT `Project_Id` FROM `tms_facttrip` WHERE `ID` = ".$FactTripID.")
AND (SELECT COUNT(*) FROM tms_checkpoint WHERE FacttripID = ".$FactTripID."
 AND IsOrderPoint = 1 AND NAME LIKE CONCAT('%', db.`Debet_fact_subsection` ,'%'))>0 
 AND (db.`Debet_plan_subsection` IS NOT NULL OR db.`Conteiner_plan_name` IS NOT NULL OR db.`Tro_plan_type` IS NOT NULL)
GROUP BY db.`Debet_plan_order`, `Debet_fact_subsection`, `Debet_plan_cost`;";

	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_debts_ordersource <> '.$query );
	$Model4 = array();
	$i=0;
	if ($stmt = $db->prepare($query)){
    if ($stmt->execute()){
	  $stmt->bind_result($tID,$ID,$OrderCode,$Debet_plan_subsection,$Debet_plan_order,$Debet_plan_cost,$Debet_fact_subsection,$Debet_fact_order,$Debet_fact_cost,$Conteiner_plan_name,$Conteiner_plan_count,$Conteiner_fact_name,$Conteiner_fact_count,$Tro_plan_type,$Tro_plan_count,$Tro_fact_type,$Tro_fact_count,$Project_ID);
	  while ($stmt->fetch()) {
        $Model4[$i]= 
        array(
		'TID'=>$tID,
		'ID'=>$ID,
		'OC'=>$OrderCode,
		'DPS'=>addslashes($Debet_plan_subsection),
		'DPO'=>$Debet_plan_order,
		'DPC'=>$Debet_plan_cost,
		'DFC'=>$Debet_fact_subsection,
		'DFO'=>$Debet_fact_order,
		'DFCO'=>$Debet_fact_cost,
		'CPN'=>addslashes($Conteiner_plan_name),
		'CPC'=>$Conteiner_plan_count,
		'CFN'=>$Conteiner_fact_name,
		'CFC'=>$Conteiner_fact_count,
		'TPT'=>$Tro_plan_type,
		'TPC'=>$Tro_plan_count,
		'TFT'=>addslashes($Tro_fact_type),
		'TFC'=>$Tro_fact_count,
		'PID'=>$Project_ID
        );
        $i++;
      }
	
      $stmt->close();
    }
	}
	
	
	
	
	
	
		if(!isset($arraydata["iduser"]) || $arraydata["iduser"]=="" ){
			$time = time();
		}else{
			$iduser = $arraydata["iduser"];
			$time = getGMT($iduser);
		}
		
		$date = date('Y-m-d H:i:s',$time);
	
	
	
	
	/*array_push($Model,$Model1);
	array_push($Model,$Model2);
	array_push($Model,$Model3);*/
	
	$Model = array('facttrip'=>$Model1,'checkpoint'=>$Model2,'checkpointcargo'=>$Model3,'ordersource'=>$Model4,'lastsynch'=>$date);
	
	echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint Model <> '.json_encode($Model) );
	
	}
	
	$db->close();
	exit;
		
}

 


// --- Синхронизация Тара Дебет ТРО ----------

if ($arraydata['func']=='tms_debts_ordersource')
{
	$lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
	
	$time = getGMT($iduser);
	$dateFrom = date('Y-m-d',$time)." 00:00:00";
	$dateTo = date('Y-m-d',$time)." 23:59:59";

	$where = "AND tt.`StartTime` BETWEEN '".$dateFrom."' AND '".$dateTo."'";
	
	
	
	
	$array_trip = array();
	
	$query = "SELECT 
tt.`ID`, tt.`Project_Id`
FROM `tms_facttrip` tt
LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
LEFT JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID`
WHERE td.`ID` = ".$iduser." ".$where.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_debts_ordersource <> '.$query );
	if ($stmt = $db->prepare($query)){
    if ($stmt->execute()){
	  $stmt->bind_result($tID,$Project_Id);
	  while ($stmt->fetch()) {
        $array_trip[]=array(
		'TID'=>$tID,
		'PID'=>$Project_Id
		);
	  }
	}}
	
	$i=0;
	$Model = array();
	foreach($array_trip as $key=>$value){
	
	
	$query = "SELECT 
".$array_trip[$key]['TID'].",db.`ID`,db.`OrderCode`,
db.`Debet_plan_subsection`,db.`Debet_plan_order`,db.`Debet_plan_cost`,db.`Debet_fact_subsection`,db.`Debet_fact_order`,db.`Debet_fact_cost`,
db.`Conteiner_plan_name`,db.`Conteiner_plan_count`,db.`Conteiner_fact_name`,db.`Conteiner_fact_count`,
db.`Tro_plan_type`,db.`Tro_plan_count`,db.`Tro_fact_type`,db.`Tro_fact_count`,db.`Project_ID`
FROM `tms_debts_ordersource` db 
WHERE db.`Project_ID` = ".$array_trip[$key]['PID']."
AND (SELECT COUNT(*) FROM tms_checkpoint WHERE FacttripID = ".$array_trip[$key]['TID']."
 AND IsOrderPoint = 1 AND NAME LIKE CONCAT('%', db.`Debet_fact_subsection` ,'%'))>0 
 AND (db.`Debet_plan_subsection` IS NOT NULL OR db.`Conteiner_plan_name` IS NOT NULL OR db.`Tro_plan_type` IS NOT NULL)
GROUP BY db.`Debet_plan_order`, `Debet_fact_subsection`, `Debet_plan_cost`;";
	
	
	
	/*$query = "SELECT tt.`ID`,db.`ID`,db.`OrderCode`,
db.`Debet_plan_subsection`,db.`Debet_plan_order`,db.`Debet_plan_cost`,db.`Debet_fact_subsection`,db.`Debet_fact_order`,db.`Debet_fact_cost`,
db.`Conteiner_plan_name`,db.`Conteiner_plan_count`,db.`Conteiner_fact_name`,db.`Conteiner_fact_count`,
db.`Tro_plan_type`,db.`Tro_plan_count`,db.`Tro_fact_type`,db.`Tro_fact_count`,db.`Project_ID`
FROM `tms_facttrip` tt
LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID`
INNER JOIN `tms_debts_ordersource` db ON tt.`Project_Id`=db.`Project_ID`
AND db.`Debet_fact_subsection` IN (SELECT NAME FROM tms_checkpoint WHERE FacttripID =tt.ID AND IsOrderPoint = 1)
AND (db.`Debet_plan_subsection` IS NOT NULL OR db.`Conteiner_plan_name` IS NOT NULL OR db.`Tro_plan_type` IS NOT NULL)
WHERE td.`ID` = ".$iduser." ".$where." GROUP BY db.`ID`";
	*/
	
	/*$query = "SELECT 
tt.`ID`,db.`ID`,w.`Code`,
db.`Debet_plan_subsection`,db.`Debet_plan_order`,db.`Debet_plan_cost`,
db.`Debet_fact_subsection`,db.`Debet_fact_order`,db.`Debet_fact_cost`,
db.`Conteiner_plan_name`,db.`Conteiner_plan_count`,db.`Conteiner_fact_name`,
db.`Conteiner_fact_count`,
db.`Tro_plan_type`,db.`Tro_plan_count`,db.`Tro_fact_type`,db.`Tro_fact_count`
FROM `tms_facttrip` tt
LEFT JOIN `tms_car` tc ON tt.`Car_ID`=tc.`Car_ID`
LEFT JOIN `tms_device` td ON tc.`Device_id`=td.`ID`
INNER JOIN `tms_project` tp ON tt.`Project_Id`=tp.`Project_ID`
INNER JOIN `tms_debts_ordersource` db ON tt.`Project_Id`=db.`Project_ID`
LEFT JOIN tms_order o ON o.`Code` = db.`OrderCode`
LEFT JOIN tms_warehouse w ON w.Warehouse_ID = o.`Warehouse_ID`
WHERE td.`ID` = ".$iduser." ".$where." GROUP BY db.`ID`";*/
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_debts_ordersource <> '.$query );
	if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $stmt->bind_result($tID,$ID,$OrderCode,$Debet_plan_subsection,$Debet_plan_order,$Debet_plan_cost,$Debet_fact_subsection,$Debet_fact_order,$Debet_fact_cost,$Conteiner_plan_name,$Conteiner_plan_count,$Conteiner_fact_name,$Conteiner_fact_count,$Tro_plan_type,$Tro_plan_count,$Tro_fact_type,$Tro_fact_count,$Project_ID);
	  while ($stmt->fetch()) {
        $Model[$i]= 
        array(
		'TID'=>$tID,
		'ID'=>$ID,
		'OC'=>$OrderCode,
		'DPS'=>addslashes($Debet_plan_subsection),
		'DPO'=>addslashes($Debet_plan_order),
		'DPC'=>$Debet_plan_cost,
		'DFC'=>addslashes($Debet_fact_subsection),
		'DFO'=>$Debet_fact_order,
		'DFCO'=>$Debet_fact_cost,
		'CPN'=>addslashes($Conteiner_plan_name),
		'CPC'=>$Conteiner_plan_count,
		'CFN'=>$Conteiner_fact_name,
		'CFC'=>$Conteiner_fact_count,
		'TPT'=>$Tro_plan_type,
		'TPC'=>$Tro_plan_count,
		'TFT'=>addslashes($Tro_fact_type),
		'TFC'=>$Tro_fact_count,
		'PID'=>$Project_ID
        );
        $i++;
      }
	
      $stmt->close();
      
    }
	
	
	}
	
    echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_debts_ordersource <> '.json_encode($Model) );
	$db->close();
	exit;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////


// ----- Fuel value ------------------
	if ($arraydata['func']=='tms_fuel_value')
	{
    $lastsynch = $arraydata["lastsynch"];
	$iduser = $arraydata["iduser"];
	$iduserGlob = $iduser;
	$Device_id;
	
		$query = "SELECT f.Device_id FROM tms_forwarder f 
LEFT JOIN tms_facttrip ft ON ft.`Forwarder_ID`= f.`Forwarder_ID`
LEFT JOIN tms_car cr ON ft.`Car_ID` = cr.`Car_ID`
WHERE cr.Device_ID = ".$iduser." AND 
(ft.`StartTime` BETWEEN '".date('Y-m-d')." 00:00:00' AND '".date('Y-m-d')." 23:59:59') LIMIT 1;";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> tms_fuel_value <> '.$query );
		if ($stmt = $db->prepare($query)){
		if ($stmt->execute()){
		$stmt->bind_result($Device_id);
		$r = $stmt->fetch();
		if( !empty( $r ))
		{
			$Device_id = $Device_id;
		}
		$stmt->close();
		}}
	
	if( !empty( $Device_id ) ){
		$iduser = $Device_id;
	}
	
    $i=0;
	$query = "SELECT `DeviceId`,`Date`,`fuel`,`value` FROM `tms_fuel_value` WHERE `DeviceId` = ".$iduser.";";
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_fuel_value <> '.$query );  
    if($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($DeviceId, $Date, $fuel, $value);
      $Model = array();
	  while ($stmt->fetch())
      {
        $Model[$i]=array(
                        'DeviceId'=>$iduserGlob,
                        'Date'=>$Date,
                        'fuel'=>$fuel,
						'value'=>$value
                        );
        $i++;
      }
    
      $stmt->close();
      $db->close();
    }
    
    echo json_encode($Model);
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_fuel_value <> '.json_encode($Model) );
	exit;
	}



	
?>