<?php 
  include "settings.php";
  include "logger.php";
  
  error_reporting(0);
  
  $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 <> '.$_REQUEST['data'] );

  $data = $_REQUEST['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."'";
	
	
	$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."'";
	
	$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`
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);
	  //$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
		//'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."'";
	
	$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']=='tms_device')
  {
    $i=0;
      
    $query = "SELECT ID, Login, Pwd, Name, deviceSettings FROM tms_device";
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_checkpoint <> '.$query );
    if($stmt = $db->prepare($query)){
        $stmt->execute();
        $stmt->bind_result($ID, $Login, $Pwd, $Name, $deviceSettings);
        while ($stmt->fetch()){
          $Model[$i]=array(
      'ID'=>$ID,
      'Login'=>$Login,
      'Pwd'=>$Pwd,
      'Name'=>$Name,
      'deviceSettings'=>$deviceSettings
          );
          $i++;
        }
    
        $stmt->close();
        $db->close();
      }
      echo json_encode($Model);
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_trippoint <> '.json_encode($Model) );
  }*/
  
  if ($arraydata['func']=='ms_user')
  {
    //$userId = $arraydata["id"];
    //$lastSynch = $arraydata["lastSynch"];
    $startLine = $arraydata["startLine"];
    $endLine = $startLine + 999;
    
    $i=0;
    $query = "SELECT ID, Login, Pwd, Name, deviceSettings FROM tms_device";
    
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_device <> '.$query );
         
    if($stmt = $db->prepare($query))
    {
      $stmt->execute();
      $stmt->bind_result($ID, $Login, $Pwd, $Name, $deviceSettings);
      $Model = array();
	  while ($stmt->fetch())
      {
        $Model[$i]=array(
                        'id'=>$ID,
                        'login'=>$Login,
                        'password'=>$Pwd,
                        'name'=>addslashes($Name)
                        );
        $i++;
      }
    
      $stmt->close();
      $db->close();
    }
    
    if ($i < 999)
    {
      $arrayEndModel = array('EndModel'=>'true');
      array_push($Model,$arrayEndModel);
    }
    
    echo json_encode($Model);
    writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_device <> '.json_encode($Model) );
  }
  
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  
  
 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."'))";
	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 ------------------
	
	
	
	
	
	
	
	// ----- Modoza load data for stock ------------------
	if ($arraydata['func']=='tms_virtual_stock')
	{
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		
		$i=0;
		//$query = "SELECT cc.`Name`,`CargoValueCount`,`Cost` FROM `tms_checkpointcargo` cc INNER JOIN `tms_checkpoint` ch ON cc.`CheckPoint_ID` = ch.`Id` INNER JOIN `tms_facttrip` f ON ch.`FactTripID` = f.`ID` INNER JOIN `tms_car` c ON c.`Car_ID` = f.`Car_ID` WHERE c.`Name` = '44444' AND DATE(f.`StartTime`) = CURDATE();";
		$query = "SELECT vs.`id`, f.`ID`,cc.id, cc.`Name`,cc.`CargoValueCount`,cc.`Cost`,vs.`cargocount` FROM `tms_checkpointcargo` cc
INNER JOIN `wm_virtual_stock` vs ON vs.`checkpointcargo_id` = cc.`ID`
INNER JOIN `tms_facttrip` f ON vs.`facttrip_id` = f.`ID`
INNER JOIN `tms_car` c ON c.`Car_ID` = f.`Car_ID`
WHERE c.`Name` = '".$iduser."' AND vs.imei = '".$iduser."' AND DATE(f.`StartTime`) = CURDATE();";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock <> '.$query );  
		$Model = array();
		if($stmt = $db->prepare($query))
		{
		if($stmt->execute()){
		$stmt->bind_result($id, $FactTripID, $checkpointcargo_id, $Name, $CargoValueCount, $Cost, $cargocount);
		while ($stmt->fetch())
		{
			$Model[$i]=array(
                        'id'=>$id,
						'FactTripID'=>$FactTripID,
						'checkpointcargo_id'=>$checkpointcargo_id,
						'Name'=>$Name,
                        'CargoValueCount'=>$CargoValueCount,
                        'Cost'=>$Cost,
						'cargocount'=>$cargocount
            );
			$i++;
		}
    
		$stmt->close();
		}
		}
		
		$imeiarray = array();
		if(count($Model) != 0){
		$query = "SELECT imei FROM wm_car_info WHERE client_id = (SELECT client_id FROM wm_car_info WHERE imei = '".$iduser."')";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock <> '.$query );
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
		$stmt->bind_result($imei);
		while ($stmt->fetch())
		{
			array_push($imeiarray,$imei);
		}
		}
		$stmt->close();
		}
		}
		
		//echo json_encode($Model);
		echo json_encode( array('data' => $Model, 'imei' => $imeiarray ) );
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock <> '.json_encode( array('data' => $Model, 'imei' => $imeiarray ) ));
		$db->close();
		exit;
	}
	// ----- Modoza load data for stock ------------------
	
	// ----- Modoza add product in stock ------------------
	if ($arraydata['func']=='tms_virtual_stock_add'){
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		$data = $arraydata["data"];
		$id_trip = $arraydata["id_trip"];
		
		$datastr = explode(',',$data);
		$values = "";
		foreach ($datastr as $key => $value){
			//writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add key '.$key.' value '.$value );
			$values .= "(".$id_trip.",".$value.",'".$iduser."'),";
		}
			$values = substr($values,0,strlen($values)-1);
			
			$query = "DELETE FROM `wm_virtual_stock` WHERE `checkpointcargo_id` IN (".$data.")";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add <> '.$query );
			if($stmt = $db->prepare($query)){
			if($stmt->execute()){
			$query = "INSERT INTO `wm_virtual_stock` (`facttrip_id`,`checkpointcargo_id`,`imei`) VALUES ".$values.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add <> '.$query );  
			if($stmt = $db->prepare($query)){
			if($stmt->execute()){
			$stmt->close();
			echo 'success';
			}else{ echo 'error'; }
			}else{ echo 'error'; }
			}else{ echo 'error'; }
			}else{ echo 'error'; }
			exit;
	}
	// ----- Modoza add product in stock ------------------
	
	// ----- Modoza product stock transaction insert ------------------
	if ($arraydata['func']=='wm_virtual_stock_transaction_add'){
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		$data = $arraydata["data"];
		$oldstock_id = $arraydata["oldstock_id"];
		$newstock_id = $arraydata["newstock_id"];
		$id_trip = $arraydata["id_trip"];
		
		$datastr = explode(',',$data);
		$values = "";
		foreach ($datastr as $key => $value){
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add key '.$key.' value '.$value );
			$values .= "(".$id_trip.",'".$newstock_id."','".$oldstock_id."',".$value.",'".$iduser."'),";
			
			$query = "UPDATE `wm_virtual_stock` SET `imei` = ".$newstock_id." WHERE `checkpointcargo_id` = ".$value.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add <> '.$query );
			if($stmt = $db->prepare($query)){
			$stmt->execute();
			$stmt->close();
			}
				
		}
			$values = substr($values,0,strlen($values)-1);
			$query = "INSERT INTO `wm_virtual_stock_transaction` (`facttrip_id`,`newstock_id`,`oldstock_id`,`checkpointcargo_id`,`imei`) VALUES ".$values.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_virtual_stock_add <> '.$query );
			if($stmt = $db->prepare($query)){
			if($stmt->execute()){
			$stmt->close();
			echo 'success';
			}else{ echo 'error'; }
			}else{ echo 'error'; }
			exit;
	}
	// ----- Modoza product stock transaction insert ------------------
	
	// ----- Modoza cash for user load ------------------
	if ($arraydata['func']=='wm_virtual_cash'){
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		
		$i=0;
		$Model = array();
		$query = "SELECT `cash` FROM `wm_virtual_cash` WHERE `imei` = '".$iduser."';";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash <> '.$query );  
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
			$stmt->bind_result($cash);
			$stmt->store_result();
			if($stmt->num_rows()>0){
			$stmt->fetch();
			$Model[0]=array('success'=>true,'cash'=>$cash);
			$stmt->close();
			}else{
			
				$query = "INSERT INTO `wm_virtual_cash` (`imei`) VALUES ('".$iduser."');";
				writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash <> '.$query );
				if($stmt = $db->prepare($query)){
				if($stmt->execute()){
				$stmt->close();
					$Model[0]=array('success'=>true,'cash'=>0.00);
				}else{ $Model[0]=array('success'=>false); }
				}else{ $Model[0]=array('success'=>false); }
			}
		}else{ $Model[0]=array('success'=>false); }
		}else{ $Model[0]=array('success'=>false); }
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash Model <> '.json_encode($Model) );
		$db->close();
		exit;
		
	}
	// ----- Modoza cash for user load ------------------
	
	// ----- Modoza cash transaction load ------------------
	if ($arraydata['func']=='wm_virtual_cash_transaction'){
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		
		$time = getGMT($iduser);
		$date = date('Y-m-d',$time);
		
		$i=0;
		$Model = array();
		$query = "SELECT ct.`facttrip_id`,ct.`time`,ct.`cash`,ctt.`name` FROM `wm_virtual_cash_transaction` ct INNER JOIN `wm_virtual_cash_costs_type` ctt ON ctt.`id`=ct.`type` WHERE ct.`imei` = '".$iduser."' AND DATE(`time`) = '".$date."'";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_transaction <> '.$query );  
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
		$stmt->bind_result($facttrip_id, $time, $cash, $name);
		while ($stmt->fetch())
		{
			$Model[$i]=array(
                        'facttrip_id'=>$facttrip_id,
						'time'=>$time,
						'cash'=>$cash,
						'name'=>$name
            );
			$i++;
		}
    
		$stmt->close();
		}
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash Model <> '.json_encode($Model) );
		$db->close();
		exit;
		
	}
	// ----- Modoza cash transaction load ------------------
	
	// ----- Modoza cash transaction add sub ------------------
	if ($arraydata['func']=='wm_virtual_cash_addsub'){
		$lastsynch = $arraydata["lastsynch"];
		$iduser = $arraydata["iduser"];
		$id_trip = $arraydata["id_trip"];
		$type = $arraydata["type"];
		$type2 = $arraydata["type2"];
		$cash = $arraydata["cash"];
		$comment = $arraydata["comment"];
		
		if((int)$type==0){
			$query = "INSERT INTO `wm_virtual_cash_costs_type` (`name`) VALUES ('".$type2."');";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_addsub <> '.$query );
			if($stmt = $db->prepare($query)){
			if($stmt->execute()){
			$type = $db->insert_id;
			$stmt->close();
			}
			}
		}
		
		if( $type == 2 ){
			$query = "UPDATE `wm_virtual_cash` SET `cash`=`cash` - ".$cash." WHERE imei = '".$iduser."';";
		}else{
			$query = "UPDATE `wm_virtual_cash` SET `cash`=`cash` + ".$cash." WHERE imei = '".$iduser."';";
		}
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_addsub <> '.$query );
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
		$stmt->close();
		
		$query = "INSERT INTO `wm_virtual_cash_transaction` (`type`,`imei`,`facttrip_id`,`cash`,`comment`) VALUES (".$type.",'".$iduser."',".$id_trip.",".$cash.",'".$comment."');";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_addsub <> '.$query );
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
			$stmt->close();
		}
		}
		
		echo 'success';
		
		}else{ echo 'error'; $db->close(); exit; }
		}else{ echo 'error'; $db->close(); exit; }
		
		
		
		$db->close();
		exit;
	}
	// ----- Modoza cash transaction add sub ------------------
	
	// ----- Modoza cash type load ------------------
	if ($arraydata['func']=='wm_virtual_cash_costs_type'){
		$iduser = $arraydata["iduser"];
		
		$i=0;
		$Model = array();
		$query = "SELECT `id`,`name` FROM `wm_virtual_cash_costs_type` WHERE id NOT IN (6,7);";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_costs_type <> '.$query );  
		if($stmt = $db->prepare($query)){
		if($stmt->execute()){
		$stmt->bind_result($id, $name);
		while ($stmt->fetch())
		{
			$Model[$i]=array(
                'id'=>$id,
				'name'=>$name
            );
			$i++;
		}
    
		$stmt->close();
		}
		}
		
		echo json_encode($Model);
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro wm_virtual_cash_costs_type Model <> '.json_encode($Model) );
		$db->close();
		exit;
	}
	// ----- Modoza cash type 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"];
	
	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 countOriginal <> '.$countOriginal );
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint TripID <> '.$TripID );
	
	$count = -1;
	$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($count == 0){
	$query = "SELECT ID FROM `tms_facttrip` WHERE `TripId` = ".$TripID.";";
	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()) {
			$FactTripID = $ID;
		}
	}
	}
	}
	
	
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint count <> '.$count );
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_facttrip_checkpoint FactTripID<> '.$FactTripID );
	
	//$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`
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);
	  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
		//'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`
WHERE tt.`ID` = ".$FactTripID." GROUP BY db.`ID`;";
	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."'";
	
	$i=0;
	
	$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`
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);
      $Model = array();
	  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();
      $db->close();
    }
    echo json_encode($Model);
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchro tms_debts_ordersource <> '.json_encode($Model) );
	exit;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////



if ($arraydata['func']=='ChangeStateOrder')
{
	$id = $arraydata["code"];
	$mcstate = $arraydata["mcstate"];
	$id_user = $arraydata["id_user"];
	
	if($mcstate == 7){
		$query = "UPDATE mc_orders SET `State` = ".$mcstate." WHERE `id` = ".$id." AND `id_prev_order` IS NOT NULL;";
	}else{
		$query = "UPDATE mc_orders SET `State` = ".$mcstate." WHERE `id` = ".$id.";";
	}
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> ChangeStateOrder <> '.$query );
	if($stmt = $db->prepare($query)){
	$stmt->execute();
		$stmt->close();
		echo 'ok';
	}
	
	if($mcstate == 4){
		require_once('../LogistMobile_CRM_function.php');
		
		$query1 = "SELECT c.`ContactPerson`, c.`ContactBoss`, c.Email, c.Phone, c.`EmailBoss`, c.`PhoneBoss`, DATE(o.`Time`) FROM mc_orders o INNER JOIN `mc_client` c ON c.`id`=o.`client_id` WHERE o.id = ".$id.";";
		if ($stmt1 = $db->prepare($query1)){
        if ($stmt1->execute()){
        $stmt1->bind_result($ContactPerson, $ContactBoss, $Email, $Phone, $EmailBoss, $PhoneBoss, $Time);
        $stmt1->fetch();
        $stmt1->close();
			
		}
		}
		
		//____________Отправка SMS Клиника_____________ 
			$textSms = "Ув. $ContactPerson, ожидайте курьера $Time. Всегда с Вами, лаборатория «Микрон» т. +380444952350";
			$textSms2 = "Ув. $ContactBoss, ожидайте курьера $Time. Всегда с Вами, лаборатория «Микрон» т. +380444952350";
			send_sms($Phone,$textSms,$logger);
			send_sms($PhoneBoss,$textSms2,$logger);
			
			
            //____________________Отправка email Клиника_____________
			$textEmail = "Здравствуйте, $ContactPerson! Ув. $ContactPerson, ожидайте курьера $Time. Всегда с Вами, лаборатория «Микрон» т. +380444952350 В случае необходимости звоните +380444952350";
			$textEmail2 = "Здравствуйте, $ContactBoss! Ув. $ContactBoss, ожидайте курьера $Time. Всегда с Вами, лаборатория «Микрон» т. +380444952350 В случае необходимости звоните +380444952350";
			$subject = "Новый заказ";
			send_email($subject,$Email,$textEmail);
			send_email($subject,$EmailBoss,$textEmail2);
	}
	
	$db->close();
	exit;
}



?>