<?php 
session_start();
header('Content-Type: text/html; charset=utf-8');

set_time_limit(180);

$client_id = $_SESSION['client_id'];

//require "log.php";
//include "../settings.php";
include "writedblog.php";

include "logger.php";

$dbset = json_decode($_SESSION['settingsApp'],true);
$db = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);

/*$DB_HOST='194.0.150.90';
$DB_USER='root';
$DB_PASS='12345678';
$DB_NAME='tmslogistic';
$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;
}


if (isset($_REQUEST['tms_order'])) {
	$data = array();
	$time = $_REQUEST['time'];
	$project = $_REQUEST['project'];

	//$query = "SELECT `Order_ID`,`CanUseLeaseCar`,`OriginalAddress`,`Warehouse_ID`,`StartTime`,`EndTime`,`LoadUnloadTime`,`ClientCar`,`Zone_ID`,`IsInTrip`,`GeoX`,`GeoY`,`Project_ID`,`Dispatcher_ID`,`Category_ID`,`IsPassive`,`IsGrouped`,`Date`,`PictureIDInTrip`,`SelectedPictureIDInTrip`,`PictureIDNotInTrip`,`SelectedPictureIDNotInTrip`,`LinkAddress`,`Priority`,`Name`,`Code` FROM `tms_order` WHERE `IsInTrip` = 0 AND DATE(`Date`)='".$time."';";
/*$query = "SELECT o.`Order_ID` AS ID,c.Name AS `Client`,IF(`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,o.Code,o.OriginalAddress,o.`StartTime`,o.`EndTime`,o.`LoadUnloadTime`,o.`GeoX`,o.`GeoY`,o.`Name`
FROM `tms_order` o
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
WHERE `IsInTrip` = 0 AND DATE(`Date`) = '".$time."';";*/
//+++	

if($CustomInt == 'Да'){
			$CustomInt = '<img src="app/images/Circle_Green.png" width="16" height="16" />';
}elseif($CustomInt == 'Нет'){
			$CustomInt = '<img src="app/images/Circle_Red.png" width="16" height="16" />';
}

/*$query = "SELECT o.`Order_ID` AS ID,c.Name AS `Client`,IF(`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,o.Code,o.OriginalAddress,o.`StartTime`,o.`EndTime`,o.`LoadUnloadTime`,o.`GeoX`,o.`GeoY`,o.`Name`, IF(o.CustomInt=1, '<img src=\"app/images/Circle_Green.png\" width=\"16\" height=\"16\" />', '<img src=\"app/images/Circle_Red.png\" width=\"16\" height=\"16\" />') as CustomInt
FROM `tms_order` o
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID`
WHERE o.`IsInTrip` = 0 AND DATE(p.`Date`) = '".$time."' AND p.`Client_ID` = ".$client_id.";";*/
/*
$query = "SELECT o.`Order_ID` AS ID,c.Name AS `Client`,IF(`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,o.Code,o.OriginalAddress,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`LoadUnloadTime`,o.`GeoX`,o.`GeoY`,o.`Name`, IF(o.CustomInt=1, '<img src=\"app/images/Circle_Green.png\" width=\"16\" height=\"16\" />', '<img src=\"app/images/Circle_Red.png\" width=\"16\" height=\"16\" />') AS CustomInt, o.`Priority`
FROM `tms_order` o
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
INNER JOIN `tms_project` p ON p.`Project_ID`= o.`Project_ID`
WHERE o.`IsInTrip` = 0 AND p.`Client_ID` = ".$client_id." AND p.`Project_ID` = (SELECT Project_ID FROM tms_project WHERE DATE(tms_project.`Date`) = '".$time."' AND tms_project.`Client_ID` = ".$client_id." ORDER BY tms_project.`Project_ID` DESC LIMIT 1);";
*/
$query = "SELECT o.`Order_ID` AS ID,c.Name AS `Client`,IF(`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,o.Code,o.OriginalAddress,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`LoadUnloadTime`,o.`GeoX`,o.`GeoY`,o.`Name`, IF(o.CustomInt=1, '<img src=\"app/images/Circle_Green.png\" width=\"16\" height=\"16\" />', '<img src=\"app/images/Circle_Red.png\" width=\"16\" height=\"16\" />') AS CustomInt, o.`Priority`
FROM `tms_order` o
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
INNER JOIN `tms_project` p ON p.`Project_ID`= o.`Project_ID`
WHERE o.`IsInTrip` = 0 AND p.`Client_ID` = ".$client_id." AND p.`Project_ID` = ".$project.";";


	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}

if ($_REQUEST['func'] == 'tms_trip') {
	$time = isset($_REQUEST['time']) ? $_REQUEST['time'] : date('Y-m-d', time());
	$project = $_REQUEST['project'];
	
	//$query = "SELECT `Trip_ID`,`Name`,`Car_ID`,`TripPrice`,`Distance`,`Time`,`Comments`,`StartTime`,`EndTime` FROM tms_trip WHERE DATE(`StartTime`) = '".$time."';";
	/*$query = "SELECT t.`Trip_ID`,t.`Name`,t.`Car_ID`,d.`Login`,t.`TripPrice`,t.`Distance`,t.`Time`,t.`Comments`,t.`StartTime`,t.`EndTime`,IF(ft.`Closed` IS NULL,'не выпущен','выпущен') AS Closed, t.`Project_ID` FROM `tms_trip` t
LEFT JOIN `tms_facttrip` ft ON ft.`TripId` = t.`Trip_ID`
INNER JOIN `tms_car` c ON c.`Car_ID`=t.`Car_ID`
INNER JOIN `tms_device` d ON c.`Device_id`=d.`ID`
WHERE DATE(t.`StartTime`) = '".$time."';";*/

//+++	
/*$query = "SELECT  t.`Trip_ID` AS TID,t.`Name`,t.`Car_ID`,  CONCAT('',wc.`car_name`,' (',d.`Login`,')') AS Login , d.`Login` AS Login2, t.`TripPrice`,t.`Distance`,t.`Time`,
		t.`Comments`,t.`StartTime`,t.`EndTime`,IF(ft.`Closed` IS NULL,'не выпущен','выпущен') AS Closed, IF(ft.`Closed` IS NULL,0,1) AS Closed2, 
		t.`Project_ID`, IF(t.`Distance` IS NULL,'не просчитан','просчитан') AS Calculated, 
		(SELECT COUNT(`TripPoint_ID`) FROM `tms_trippoint` WHERE `Type` = 1 AND `Trip_ID` = TID) AS ColChek, lt.`is_lock` AS is_lock
FROM `tms_trip` t
INNER JOIN `tms_car_snapshot` c ON c.`ID`=t.`Car_ID`
LEFT JOIN `tms_facttrip` ft ON ft.`TripId` = t.`Trip_ID`
 INNER JOIN `tms_device` d ON c.`Device_id`=d.`ID`
 INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
 LEFT JOIN  `tms_web_lock_trip` lt ON lt.`trip_id`=t.`Trip_ID`
INNER JOIN `wm_car_info` wc ON wc.`imei` = d.`Login`  
WHERE DATE(p.`Date`) = '".$time."' AND p.`Client_ID` = ".$client_id." GROUP BY t.`Trip_ID`;";
*/

/*$query = "SELECT  p.`Project_ID`,t.`Trip_ID` AS TID,t.`Name`,t.`Car_ID`,  CONCAT('',wc.`car_name`,' (',d.`Login`,')') AS Login , d.`Login` AS Login2, t.`TripPrice`,t.`Distance`,t.`Time`,
		t.`Comments`,t.`StartTime`,t.`EndTime`,IF(ft.`Closed` IS NULL,'не выпущен','выпущен') AS Closed, IF(ft.`Closed` IS NULL,0,1) AS Closed2, 
		t.`Project_ID`, IF(t.`Distance` IS NULL,'не просчитан','просчитан') AS Calculated, 
		(SELECT COUNT(`TripPoint_ID`) FROM `tms_trippoint` WHERE `Type` = 1 AND `Trip_ID` = TID) AS ColChek, lt.`is_lock` AS is_lock
FROM `tms_trip` t
INNER JOIN `tms_car_snapshot` c ON c.`ID`=t.`Car_ID`
LEFT JOIN `tms_facttrip` ft ON ft.`TripId` = t.`Trip_ID`
 INNER JOIN `tms_device` d ON c.`Device_id`=d.`ID`
  LEFT JOIN  `tms_web_lock_trip` lt ON lt.`trip_id`=t.`Trip_ID`
INNER JOIN `wm_car_info` wc ON wc.`imei` = d.`Login`
INNER JOIN `tms_project` p ON p.`Project_ID`= t.`Project_ID`
WHERE p.`Client_ID` = ".$client_id."
AND p.`Project_ID` = (SELECT Project_ID FROM tms_project WHERE DATE(tms_project.`Date`) = '".$time."' AND tms_project.`Client_ID` = ".$client_id." ORDER BY tms_project.`Project_ID` DESC LIMIT 1)
GROUP BY t.`Trip_ID`;";
*/
$query = "SELECT  p.`Project_ID`,t.`Trip_ID` AS TID,t.`Name`,t.`Car_ID`,  CONCAT('',wc.`car_name`,' (',d.`Login`,')') AS Login , d.`Login` AS Login2, t.`TripPrice`,t.`Distance`,t.`Time`,
		t.`Comments`,t.`StartTime`,t.`EndTime`,IF(ft.`Closed` IS NULL,'не выпущен','выпущен') AS Closed, IF(ft.`Closed` IS NULL,0,1) AS Closed2, 
		t.`Project_ID`, IF(t.`Distance` IS NULL,'не просчитан','просчитан') AS Calculated, 
		(SELECT COUNT(`TripPoint_ID`) FROM `tms_trippoint` WHERE `Type` = 1 AND `Trip_ID` = TID) AS ColChek, lt.`is_lock` AS is_lock,t.`WalkerNum`
FROM `tms_trip` t
INNER JOIN `tms_car_snapshot` c ON c.`ID`=t.`Car_ID`
LEFT JOIN `tms_facttrip` ft ON ft.`TripId` = t.`Trip_ID`
 INNER JOIN `tms_device` d ON c.`Device_id`=d.`ID`
  LEFT JOIN  `tms_web_lock_trip` lt ON lt.`trip_id`=t.`Trip_ID`
INNER JOIN `wm_car_info` wc ON wc.`imei` = d.`Login`
INNER JOIN `tms_project` p ON p.`Project_ID`= t.`Project_ID`
WHERE p.`Client_ID` = ".$client_id."
AND p.`Project_ID` = ".$project."
GROUP BY t.`Trip_ID`;";

//echo $query;

	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			
			if (count($result) > 0) {
				foreach ($result as $key => $value) {
					if (is_null($value['is_lock'])) {
						$result[$key]['is_lock']  = 'Нет';
					} elseif ((int) $value['is_lock'] == 0){
						$result[$key]['is_lock']  = 'Нет';
					} elseif ((int) $value['is_lock'] == 1) {
						$result[$key]['is_lock']  = 'Да';
					}
										
					if (!is_null($value['StartTime'])) {
						//print_r($value); exit();
						$result[$key]['StartTime'] = substr($value['StartTime'], 11);
						$result[$key]['EndTime'] = substr($value['EndTime'], 11);
					}
					$result[$key]['Distance'] = round($value['Distance']/1000, 2);
				}				
			}			
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}



if ($_REQUEST['func'] == 'tms_device') {
	
	$time = $_REQUEST['time'];
	$project = $_REQUEST['project'];
	//+++	
		/*$query = "
		SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login FROM `tms_device` d INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login` WHERE d.`Client_id` = ".$client_id."
		AND d.ID NOT IN (
		SELECT Device_id FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." )";*/
	
	// -- с настройкой блокировки
	$query = "SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login FROM `tms_device` d
INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login`
INNER JOIN `tms_car` cr ON cr.`Device_id` = d.`ID`
WHERE d.`Client_id` = ".$client_id." AND cr.Active=1 AND d.ID NOT IN (
		SELECT Device_id FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." );";
	
	// -- с учетем нескольких ходок
	$query = "SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login FROM `tms_device` d
INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login`
INNER JOIN `tms_car` cr ON cr.`Device_id` = d.`ID`
WHERE d.`Client_id` = ".$client_id." AND cr.Active=1;";
	
	$query = "SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login FROM `tms_device` d
INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login`
INNER JOIN tms_car_snapshot cs ON cs.`Device_id` = d.`ID` 
WHERE d.`Client_id` = ".$client_id." AND cs.Active=1 AND cs.`Project_ID` = ".$project.";";
	
	/*$query = "SELECT `ID`,`Login` FROM `tms_device` WHERE `Client_id` =$client_id AND ID NOT IN (
			SELECT Device_id FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE DATE(p.`Date`) = DATE(NOW()) AND p.LockedDisp_ID=4)";*/
	
	
	/* "SELECT Device_id FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE DATE(p.`Date`) = DATE(NOW()) AND p.LockedDisp_ID=4";
 */	
	/* $query = "SELECT d.`ID`,d.`Login` FROM `tms_device` d
		INNER JOIN tms_car_snapshot c ON c.`Device_id`=d.`ID`
		INNER JOIN tms_trip t ON c.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE d.`Client_id`=$client_id  AND DATE(p.`Date`) = DATE(NOW()) 
		AND d.ID NOT IN (SELECT `ID` FROM `tms_device` WHERE `Client_id` =$client_id)";
	 */
	
	/* $query = "SELECT d.`ID`,d.`Login` FROM `tms_car_snapshot` s
INNER JOIN `tms_project` p ON p.`Project_ID`=s.`Project_ID`
LEFT JOIN `tms_trip` t ON t.`Car_ID`=s.ID
INNER JOIN tms_device d ON s.`Device_id`=d.`ID`
WHERE d.`Client_id`=$client_id AND DATE(p.`Date`) = DATE(NOW())
	AND NOT IN ()"; */
	
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}



// ++++++++ change car ++++++++++++++++
if ($_REQUEST['func'] == 'tms_device_change') {
	
	$time = $_REQUEST['time'];
	
	//$query = "SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login, d.ID AS CarId FROM `tms_device` d INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login` WHERE d.`Client_id` = ".$client_id."";
	$query = "SELECT d.`Login` AS ID,CONCAT('',c.`car_name`,' (',d.`Login`,')') AS Login, cr.`Car_ID` AS CarId FROM `tms_device` d INNER JOIN `tms_car` cr ON cr.`Device_id` = d.`ID` INNER JOIN `wm_car_info` c ON c.`imei` = d.`Login` WHERE d.`Client_id` = ".$client_id."";
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}

if ($_REQUEST['func'] == 'checkCarIn') {
	
	$ID = $_REQUEST['ID'];
	$CarId = $_REQUEST['CarId'];
	$time = $_REQUEST['time'];
	$project = $_REQUEST['project'];
	
	/*$query = "SELECT s.`Car_ID` FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." AND s.`Car_ID` = ".$CarId."";
	*/
	$query = "SELECT s.`Car_ID` FROM tms_car_snapshot s
		INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID`
		INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
		WHERE p.`Project_ID` =".$project." AND p.`Client_ID` = ".$client_id." AND s.`Car_ID` = ".$CarId."";
	
	
	if($stmt = $db->prepare($query)){
	$stmt->execute();
	$stmt->bind_result($Device_id);
	$stmt->fetch();
	$stmt->close();
		echo '{"success":true,"message":"'.$Device_id.'"}';
	}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; }
	
	$db->close();
	exit;
}

if ($_REQUEST['func'] == 'changeCarIn') {
		$carid = $_REQUEST['carid'];
		$login = $_REQUEST['login'];
		$loginold = $_REQUEST['loginold'];
		$trid = $_REQUEST['trid'];
		$between = $_REQUEST['between'];
		$time = $_REQUEST['time'];
		$project = $_REQUEST['project'];
		
		//$query = "SELECT t.`Trip_ID`,s.ID,s.`Car_ID` FROM tms_car_snapshot s INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID` INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID` WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." AND s.Car_ID = ".$carid.";";
		//$query = "SELECT tms_car_snapshot.ID, tms_car_snapshot.`Car_ID` FROM tms_car_snapshot LEFT JOIN tms_car ON tms_car_snapshot.Car_ID = tms_car.Car_ID WHERE tms_car.Car_ID = ".$carid." AND tms_car_snapshot.Project_ID = (SELECT Project_ID FROM tms_trip WHERE Trip_ID = ".$trid." LIMIT 1)";
		$query = "SELECT tms_car_snapshot.ID, tms_car_snapshot.`Car_ID` FROM tms_car_snapshot LEFT JOIN tms_car ON tms_car_snapshot.Car_ID = tms_car.Car_ID WHERE tms_car.Car_ID = ".$carid." AND tms_car_snapshot.Project_ID = ".$project.";";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		if($stmt = $db->prepare($query)){
		$stmt->execute();
		//$stmt->bind_result($Trip_ID,$Snap_ID_new,$Car_ID_new);
		$stmt->bind_result($Snap_ID_new,$Car_ID_new);
		$stmt->fetch();
		$stmt->close();
		
		if($Snap_ID_new || $Snap_ID_new!=""){
		
		//$query = "SELECT t.`Car_ID`,f.`Car_ID` FROM `tms_trip` t INNER JOIN  `tms_facttrip` f ON t.`Trip_ID` = f.`TripId` WHERE t.`Trip_ID` = ".$trid.";";
		//$query = "SELECT s.ID,s.`Car_ID` FROM tms_car_snapshot s INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID` INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID` WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." AND s.Car_ID = (SELECT c.Car_ID FROM tms_device d INNER JOIN tms_car c ON d.ID = c.`Device_id` WHERE d.login = ".$loginold.")";
		$query = "SELECT s.ID,s.`Car_ID` FROM tms_car_snapshot s INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID` INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID` WHERE p.`Project_ID` = ".$project." AND p.`Client_ID` = ".$client_id." AND s.Car_ID = (SELECT c.Car_ID FROM tms_device d INNER JOIN tms_car c ON d.ID = c.`Device_id` WHERE d.login = ".$loginold.")";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		if($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($Snap_ID_old,$Car_ID_old);
		$stmt->fetch();
		$stmt->close();
		}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
		
		if(!isset($between) || $between==""){
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' !between' );
			$query = "UPDATE `tms_trip` SET `Car_ID` = ".$Snap_ID_new." WHERE `Trip_ID` = ".$trid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			if($stmt = $db->prepare($query)){
			$stmt->execute();
			$stmt->close();
			}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			
			$query = "SELECT ID FROM `tms_facttrip` WHERE `TripId` = ".$trid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			$result = $db->query($query);
			if ($result->num_rows) {
				$query = "UPDATE `tms_facttrip` f INNER JOIN `tms_checkpoint` c ON c.`FactTripID` = f.`ID` SET f.Car_ID = ".$Car_ID_new.", c.CarID = ".$Car_ID_new." WHERE f.`TripId` = ".$trid.";";
				writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
				if($stmt = $db->prepare($query)){
				$stmt->execute();
				$stmt->close();
				}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			}
			
		}else{
			//echo 'between';
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' between' );
			$query = "UPDATE `tms_trip` SET `Car_ID` = ".$Snap_ID_new." WHERE `Trip_ID` = ".$trid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			if($stmt = $db->prepare($query)){
			$stmt->execute();
			$stmt->close();
			}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			
			$query = "SELECT ID FROM `tms_facttrip` WHERE `TripId` = ".$trid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			$result = $db->query($query);
			if ($result->num_rows) {
				$query = "UPDATE `tms_facttrip` f INNER JOIN `tms_checkpoint` c ON c.`FactTripID` = f.`ID` SET f.Car_ID = ".$Car_ID_new.", c.CarID = ".$Car_ID_new." WHERE f.`TripId` = ".$trid.";";
				if($stmt = $db->prepare($query)){
				$stmt->execute();
				$stmt->close();
				}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			}
			
			
			$query = "SELECT t.`Trip_ID` FROM tms_car_snapshot s INNER JOIN tms_trip t ON s.`ID`=t.`Car_ID` INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID` WHERE DATE(p.`Date`) = DATE('".$time."') AND p.`Client_ID` = ".$client_id." AND s.Car_ID = ".$carid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			if($stmt = $db->prepare($query)){
			$stmt->execute();
			$stmt->bind_result($Trip_ID);
			$stmt->fetch();
			$stmt->close();
			}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			
			$query = "UPDATE `tms_trip` SET `Car_ID` = ".$Snap_ID_old." WHERE `Trip_ID` = ".$Trip_ID.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			if($stmt = $db->prepare($query)){
			$stmt->execute();
			$stmt->close();
			}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; $db->close(); exit; }
			
			$query = "SELECT ID FROM `tms_facttrip` WHERE `TripId` = ".$Trip_ID.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			$result = $db->query($query);
			if ($result->num_rows) {
				$query = "UPDATE `tms_facttrip` f INNER JOIN `tms_checkpoint` c ON c.`FactTripID` = f.`ID` SET f.Car_ID = ".$Car_ID_old.", c.CarID = ".$Car_ID_old." WHERE f.`TripId` = ".$Trip_ID.";";
				writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
				if($stmt = $db->prepare($query)){
				$stmt->execute();
				$stmt->close();
				}
			}
		}
		
		echo '{"success":true,"message":""}';
		
		}else{ echo '{"success":false,"message":"Снимок для данного устройства не создан"}'; }
		
		}else{ echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; }
		$db->close();
		exit;	
}
// ++++++++ change car ++++++++++++++++





if ($_REQUEST['func'] == 'tms_project') {
	
	//$time = $_REQUEST['time'];
	$time = isset($_REQUEST['time']) ? $_REQUEST['time'] : date('Y-m-d', time());
	
	//$query = "SELECT `Project_ID` AS ID,`Name` FROM `tms_project`;";
	//+++	
	$query = "SELECT `Project_ID` AS ID,`Name` FROM `tms_project` WHERE DATE(`Date`)='".$time."' AND `Executing`=1 AND `Client_ID` = ".$client_id." ORDER BY `Project_ID` DESC;";
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}

if ($_REQUEST['func'] == 'tms_warehouse') {
	
	//+++
	$query = "SELECT `Warehouse_ID` AS ID, w.`Name` FROM `tms_warehouse` w WHERE w.`WarehouseType` = 1 AND `instanceID` = ".$client_id."";
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo'{rows:'.json_encode($result).'}';
	}
	$db->close();
	exit;
}


if ($_REQUEST['func'] == 'tms_trippoint') {
	
	$userID = $_REQUEST['userID'];
	$time = $_REQUEST['time'];
	$FactTripID = $_REQUEST['FactTripID'];
	
	/*function updateonerrortime(){
			global $db;
			global $FactTripID;
			$query = "UPDATE tms_trip SET `Distance` = NULL, `Time` = NULL, `StartTime` = NULL, `EndTime` = NULL WHERE `Trip_ID` = ".$FactTripID.";";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->close();
	}*/
	
	//$query = "SELECT `TripPoint_ID`,`Type`,`Point_ID`,`Address`,`EstimateTime`,`DurationInPoint`,`OrderInTrip`,`Trip_ID`,`Route`,`Distance`,`Time`,`GeoX`,`GeoY`,`Name`,`WaitTime`,`LateTime` FROM `tms_trippoint` WHERE `Trip_ID` = ".$FactTripID.";";
	$query = "SELECT * FROM ((SELECT t.`TripPoint_ID` AS ID, c.Name AS `Client`,IF(w.`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,o.Code,o.`OriginalAddress`,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`LoadUnloadTime`,o.`GeoX`,o.`GeoY`,o.Name, t.OrderInTrip, t.`EstimateTime`, t.`DurationInPoint`, t.Distance , IF(o.CustomInt=1, 'Да', 'Нет') as CustomInt, o.`Priority`
	FROM `tms_trippoint` t
INNER JOIN `tms_loadunloadpoint` lp ON
t.`Point_ID` = lp.`LoadUnloadPoint_ID`
LEFT JOIN `tms_order` o ON lp.`OrderWarehouse_ID`=o.`Order_ID`
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
WHERE t.`Trip_ID` = ".$FactTripID.")
UNION ALL
(SELECT t.`TripPoint_ID` AS ID, c.Name AS `Client`, IF(w.`WarehouseType`=1,'Склад','Магазин') AS WarehouseType,w.Code,w.Address,TIME(w.`StartServeTime`) AS StartTime,TIME(w.`EndServeTime`) AS EndTime,w.`StaticUnloadTime`,w.`GeoX`,w.`GeoY`,w.`Name`, t.OrderInTrip, t.`EstimateTime`, t.`DurationInPoint`, t.Distance, 'Нет', NULL  FROM `tms_trippoint` t
INNER JOIN `tms_loadunloadpoint` lp ON t.`Point_ID` = lp.`LoadUnloadPoint_ID`
INNER JOIN `tms_warehouse` w ON lp.`OrderWarehouse_ID` = w.`Warehouse_ID`
LEFT JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
WHERE t.`Trip_ID` = ".$FactTripID.")) t ORDER BY  t.`OrderInTrip`;";
	
	//echo $query;
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($ID, $Client,$WarehouseType,$Code,$OriginalAddress,$StartTime,$EndTime,$LoadUnloadTime,$GeoX,$GeoY,$Name, $OrderInTrip, $EstimateTime, $DurationInPoint, $Distance, $CustomInt, $Priority);
	
		

 
	while ($stmt->fetch()) {
//add		
		if( strtotime($EstimateTime) ){
			$DurationUNIX = (int)($DurationInPoint*60) + strtotime($EstimateTime);
			$Duration = date('H:i:s', $DurationUNIX);
			
			$EstimateTime = date('H:i:s',strtotime($EstimateTime));
			
			
		}else{
			//$EstimateTime = substr($EstimateTime, 11 ,-6);
			//$Duration = '';
			//updateonerrortime();
		}
//endadd	

		if($CustomInt == 'Да'){
			$CustomInt = '<img src="app/images/Circle_Green.png" width="16" height="16" />';
		}elseif($CustomInt == 'Нет'){
			$CustomInt = '<img src="app/images/Circle_Red.png" width="16" height="16" />';
		}
		
		
		
	$data[] = array(
			'ID' => $ID,
			'Client' => $Client,
			'WarehouseType' => $WarehouseType,
			'Code' => $Code,
			'OriginalAddress' => $OriginalAddress,
			'StartTime' => $StartTime,
			'EndTime' => $EndTime,
			'LoadUnloadTime' => $LoadUnloadTime,
			'GeoX' => $GeoX,
			'GeoY' => $GeoY,
			'Name' => $Name,
			'OrderInTrip' => $OrderInTrip,
			'EstimateTime' => $EstimateTime,
			'Duration' => $Duration,
			'Distance' => Round($Distance/1000),
			'CustomInt' => $CustomInt,
			'Priority' => $Priority
		);
	}
	$stmt->close();
	echo'{rows:'.json_encode($data).'}';
	/*if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo'{rows:'.json_encode($result).'}';
	}*/
	$db->close();
	exit;
}


if (isset($_REQUEST['addTrip'])) {

$date = $_REQUEST['date'];
$flag = $_REQUEST['flag'];
$trip_id = $_REQUEST['trip_id'];
$trip_name = $_REQUEST['trip_name'];
$trip_master = $_REQUEST['trip_master'];
$trip_project = $_REQUEST['trip_project'];

$trip_warehouse1 = $_REQUEST['trip_warehouse1'];
$trip_warehouse2 = $_REQUEST['trip_warehouse2'];

$trip_houre = $_REQUEST['trip_houre'];
$trip_min = $_REQUEST['trip_min'];
$trip_comments = $_REQUEST['trip_comments'];

$dates = date('Y-m-d').' '.$trip_houre.':'.$trip_min.':00';
$datee = date('Y-m-d').' 23:59:59';

		//+++ not use, project create server by xml
		/*if( is_numeric($trip_project) ){
			
		}else{
			$query = "INSERT INTO `tms_project` (`Name`) VALUES ('".$trip_project."')";
            $stmt = $db->prepare($query);
            $stmt->execute();
			$trip_project = $db->insert_id;
			$stmt->close();
		}*/
		
		$WalkerNum = 0;
		$query = "SELECT `WalkerNum` FROM tms_trip t
INNER JOIN tms_car_snapshot cs ON cs.ID = t.`Car_ID`
INNER JOIN tms_car c ON cs.`Car_ID` = c.`Car_ID`
INNER JOIN tms_device d ON d.`ID` = c.`Device_id`
WHERE d.`Login` = '".$trip_master."' AND t.`Project_ID` = ".$trip_project." ORDER BY `Trip_ID` DESC LIMIT 1;";
		writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$query );
		if($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($WalkerNum);
		$stmt->fetch();
		$stmt->close();
		}
		
		$WalkerNum = $WalkerNum + 1;
		
		if($flag='add'){
			
			//$query = "INSERT INTO `tms_trip` (`Name`,`Car_ID`,`Comments`,`StartTime`,`EndTime`,`Project_ID`,`Dispatcher_ID`) VALUES  ('".$trip_name."',(SELECT c.`Car_ID` FROM tms_car c INNER JOIN tms_device d ON d.`ID` = c.`Device_id` WHERE d.`Login`=".$trip_master."),'".$trip_comments."','".$dates."','".$datee."',".$trip_project.",4);";
			$query = "INSERT INTO `tms_trip` (`Name`,`Car_ID`,`Comments`,`StartTime`,`EndTime`,`Project_ID`,`Dispatcher_ID`,`WalkerNum`) 
					VALUES  ('".$trip_name."',(SELECT ID FROM `tms_car_snapshot` WHERE `Car_ID`=(SELECT c.`Car_ID` FROM tms_car c INNER JOIN tms_device d ON d.`ID` = c.`Device_id` WHERE d.`Login`='".$trip_master."') AND `Project_ID`=$trip_project),'".$trip_comments."','".$dates."','".$datee."',".$trip_project.",4,".$WalkerNum.");";
			//echo $query;
			writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$query );
			if($stmt = $db->prepare($query)){
            $stmt->execute();
			$trip_id = $db->insert_id;
			$stmt->close();
				echo '{"success":true,"message":""}';
			}else{
				echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}'; exit;
			}
			
			
			
			
			
			
			//$queryW1 = "SELECT lp.`LoadUnloadPoint_ID` FROM `tms_warehouse2` w INNER JOIN `tms_loadunloadpoint` lp ON lp.`OrderWarehouse_ID` = w.`Warehouse_ID` WHERE w.`WarehouseType` = ".$trip_warehouse1.";";
			
			$query = "INSERT INTO `tms_loadunloadpoint` (`IsOrderPoint`, `OrderWarehouse_ID`, `IsStartWarehouse`) 
					VALUES (0, $trip_warehouse1, 1)";
			$stmt = $db->prepare($query);
			$stmt ->execute();
			$loadPoint_Id = $db->insert_id;
			$stmt->close();
			/* -- `IsOrderPoint`=0
			-- `OrderWarehouse_ID` from form
			-- `IsStartWarehouse` 0 and 1 */
			
			/*$query = "INSERT INTO `tms_trippoint`
(`Type`,`Point_ID`,`Address`,`Trip_ID`,`GeoX`,`GeoY`,`Name`, `OrderInTrip`)
SELECT 8,$loadPoint_Id,`Address`,$trip_id,`GeoX`,`GeoY`,`Name`,1
FROM `tms_warehouse` WHERE `Warehouse_ID`=$trip_warehouse1";*/
$query = "INSERT INTO `tms_trippoint`
(`Type`,`Point_ID`,`Address`,`Trip_ID`,`GeoX`,`GeoY`,`Name`, `OrderInTrip`)
SELECT 1,$loadPoint_Id,`Address`,$trip_id,`GeoX`,`GeoY`,`Name`,1
FROM `tms_warehouse` WHERE `Warehouse_ID`=$trip_warehouse1";
			
			$stmt = $db->prepare($query);
            $stmt->execute();
			$stmt->close();
			
			$query = "INSERT INTO `tms_loadunloadpoint_index` VALUES (NULL)";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$LoadUnloadPoint_ID = $db->insert_id;
			$stmt->close();
			
			
			//$queryW2 = "SELECT lp.`LoadUnloadPoint_ID` FROM `tms_warehouse2` w INNER JOIN `tms_loadunloadpoint` lp ON lp.`OrderWarehouse_ID` = w.`Warehouse_ID` WHERE w.`WarehouseType` = ".$trip_warehouse2.";";
			$query = "INSERT INTO `tms_loadunloadpoint` (`LoadUnloadPoint_ID`, `IsOrderPoint`, `OrderWarehouse_ID`, `IsStartWarehouse`)
			VALUES ($LoadUnloadPoint_ID, 0, $trip_warehouse2, 0)";
			$stmt = $db->prepare($query);
			$stmt ->execute();
			$unLoadPoint_Id = $db->insert_id;
			$stmt->close();
			
			/*$query = "INSERT INTO `tms_trippoint`
(`Type`,`Point_ID`,`Address`,`Trip_ID`,`GeoX`,`GeoY`,`Name`, `OrderInTrip`)
SELECT 8,$unLoadPoint_Id,`Address`,$trip_id,`GeoX`,`GeoY`,`Name`,2
FROM `tms_warehouse` WHERE `Warehouse_ID`=$trip_warehouse2";*/
			$query = "INSERT INTO `tms_trippoint`
(`Type`,`Point_ID`,`Address`,`Trip_ID`,`GeoX`,`GeoY`,`Name`, `OrderInTrip`)
SELECT 1,$unLoadPoint_Id,`Address`,$trip_id,`GeoX`,`GeoY`,`Name`,2
FROM `tms_warehouse` WHERE `Warehouse_ID`=$trip_warehouse2";
			$stmt = $db->prepare($query);
            $stmt->execute();
			$stmt->close();
		}
		
		$db->close();
		exit;
}

if (isset($_REQUEST['bindPointToTrip'])) {
	
	$dropPosition = $_REQUEST['dropPosition'];
	$pointsArr = $_REQUEST['pointsArr'];
	$fromPointId = $_REQUEST['fromPointId'];
	
	$trip_id = $_REQUEST['trip_id'];
	$tripPointNewId = array();
	#$order_id = $_REQUEST['order_id'];
	
	
	$query = "SELECT MAX(ID) FROM `tms_lupointcargo_index`";
	$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($ID);
		$stmt->fetch();
		$stmt->close();
		
		$nextID = $ID + count($pointsArr);
	
		$query = "INSERT INTO `tms_lupointcargo_index` (`ID`) VALUES($nextID)";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		//echo $query;
	
	foreach ($pointsArr as $order_id) {
		$ID++;
		$query = "SELECT `OriginalAddress`, `GeoX`, `GeoY`, `Name` FROM `tms_order` WHERE `Order_ID`=$order_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($OriginalAddress, $GeoX, $GeoY, $Name);
		while ($stmt->fetch()) {
			$orderDataArr = array(
					'address' => $OriginalAddress,
					'GeoX' => $GeoX,
					'GeoY' => $GeoY,
					'Name' => $Name
			);
		}
		
		$query = "SELECT lp.`OrderWarehouse_ID` FROM tms_trippoint  tp
		INNER JOIN `tms_loadunloadpoint` lp ON lp.`LoadUnloadPoint_ID`=tp.`Point_ID`
		WHERE tp.`Trip_ID`=$trip_id AND lp.`IsStartWarehouse`=0";
		

		
		
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($fromWarehouse_ID);
		$stmt->fetch();
		$stmt->close();
		
		$query = "INSERT INTO `tms_loadunloadpoint_index` VALUES (NULL)";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$LoadUnloadPoint_ID = $db->insert_id;
		$stmt->close();
		
		$query = "SELECT `StartTime`, `EndTime`, `Date` FROM `tms_order` WHERE `Order_ID` = $order_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($StartTime, $EndTime, $Date);
		$stmt->fetch();
		$stmt->close();
		
		if($StartTime == ''){$StartTime = null;}
		if($EndTime == ''){$EndTime = null;}
		
		// SELECT StartTime, EndTime, Date FROM tms_order WHERE Order_ID = $order_id 
		$query = "INSERT INTO `tms_loadunloadpoint` (`LoadUnloadPoint_ID`, `OrderWarehouse_ID`, `FromWarehouse_ID`, `IsOrderPoint`, `StartTime`, `EndTime`, `FixedDate`)
		VALUES ($LoadUnloadPoint_ID, $order_id, $fromWarehouse_ID, 1, '$StartTime', '$EndTime', '$Date')";
		//echo $query;exit;
		$stmt = $db->prepare($query);
		$stmt->execute();
		$point_id = $db->insert_id;
		$stmt->close();
		
		$query = "SELECT MIN(`OrderInTrip`) FROM `tms_trippoint` WHERE `Trip_ID` = $trip_id";
		writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($OrderInTrip2);
		$stmt->fetch();
		$stmt->close();
		writeToLogFile( ' -> OrderInTrip Selected '.date('Y-m-d H:i:s').' '.$OrderInTrip2 );
		
		/* $query = "SELECT `OrderInTrip` FROM `tms_trippoint` WHERE `Trip_ID`=$trip_id  ORDER BY `OrderInTrip` DESC LIMIT 1";		
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($maxOrderInTrip);
		$stmt->fetch();
		$stmt->close();
		
		$OrderInTrip = $maxOrderInTrip; */
		
		$query = "INSERT INTO `tms_trippoint` (`Type`, `Point_ID`, `OrderInTrip`, `Address`, `GeoX`, `GeoY`, `Name`, `Trip_ID`)
		VALUES (1, $point_id, 0, '$orderDataArr[address]', $orderDataArr[GeoX], $orderDataArr[GeoY], '$orderDataArr[Name]', $trip_id) ";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$tripPointNewId[] = $db->insert_id;
		$stmt->close();
		
		/* $secondStorageOrderInTrip = ++$OrderInTrip;
		$query = "UPDATE `tms_trippoint` SET OrderInTrip=$secondStorageOrderInTrip
		WHERE `Trip_ID`=$trip_id AND OrderInTrip=$maxOrderInTrip AND Type=8";
		
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close(); */
		
		$query = "UPDATE tms_trip SET `Distance` = NULL,  `Time`=NULL, `StartTime`=null, `EndTime`=null WHERE Trip_ID=$trip_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		$query = "UPDATE `tms_order` SET IsInTrip=1 WHERE `Order_ID`=$order_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		//+++
		/*$query = "INSERT INTO `tms_lupointcargo_index` VALUES (NULL)";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$Lupointcargo_ID = $db->insert_id;
		$stmt->close();
		*/
		
		/*
		$query = "INSERT INTO `tms_lupointcargo`
		(Lupointcargo_ID,`DimensionUnitVolume_ID`,`CargoValueVolume`,`LUPoint_ID`,`DimensionUnitWeight_ID`,`CargoValueWeight`,`Specialization_ID`,`Comments`,`UnloadType_ID`,`Name`,`CargoValueCount`,`DimensionUnitCount_ID`,`Cost`)
		SELECT ".$Lupointcargo_ID.",`DimensionUnitVolume_ID`,`CargoValueVolume`,".$point_id.",`DimensionUnitWeight_ID`,`CargoValueWeight`,`Specialization_ID`,`Comments`,`UnloadType_ID`,`Name`,`CargoValueCount`,`DimensionUnitCount_ID`,`Cost`
		FROM `tms_ordercargo` WHERE `Order_ID` = ".$order_id.";";
		*/
		$query = "INSERT INTO `tms_lupointcargo`
		(`LUPointCargo_ID`,`DimensionUnitVolume_ID`,`CargoValueVolume`,`LUPoint_ID`,`DimensionUnitWeight_ID`,`CargoValueWeight`,`Specialization_ID`,`Comments`,`UnloadType_ID`,`Name`,`CargoValueCount`,`DimensionUnitCount_ID`,`Cost`)
		SELECT ".$ID.", `DimensionUnitVolume_ID`,`CargoValueVolume`,".$point_id.",`DimensionUnitWeight_ID`,`CargoValueWeight`,`Specialization_ID`,`Comments`,`UnloadType_ID`,`Name`,`CargoValueCount`,`DimensionUnitCount_ID`,`Cost`
		FROM `tms_ordercargo` WHERE `Order_ID` = ".$order_id.";";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
				$stmt->execute();
				$stmt->close();
		//+++
	}
	
		$strPoint = implode(',', $tripPointNewId);
		if ($dropPosition == 'after') {
			$afterDropPoint = '>';
			$beforeDropPoint = '<=';
		} elseif ($dropPosition == 'before') {
			$afterDropPoint = '>=';
			$beforeDropPoint = '<';
		}
		
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$strPoint );
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$dropPosition );
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$afterDropPoint );
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$beforeDropPoint );
		
		//after drop point
		$pointAfterArr = array();
		/*$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` WHERE OrderInTrip $afterDropPoint (
		SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId AND OrderInTrip<>0
		) AND `TripPoint_ID` NOT IN ($strPoint) AND `Type`<>8 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";*/
		
		$query = "SELECT `TripPoint_ID` FROM `tms_trippoint`
		LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
		WHERE OrderInTrip $afterDropPoint (
		SELECT OrderInTrip FROM tms_trippoint 
		WHERE `TripPoint_ID`=$fromPointId AND OrderInTrip<>0
		) AND `TripPoint_ID` NOT IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 1 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";// 
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($TripPoint_ID);
		while ($stmt->fetch()) {
			$pointAfterArr[] =  $TripPoint_ID;
		}
		$stmt->close();
		
		$sd = implode(',', $pointAfterArr);
		writeToLogFile( ' -> pointAfterArr '.date('Y-m-d H:i:s').' '.$sd );
		writeToLogFile( ' -> pointAfterArr count'.date('Y-m-d H:i:s').' '.count($pointAfterArr) );
		
		$pointBeforeArr = array();
		/*$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` WHERE OrderInTrip $beforeDropPoint (
		SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId AND OrderInTrip<>0
		) AND `TripPoint_ID` NOT IN ($strPoint) AND `Type`<>8 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";*/
		$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` 
		LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
		WHERE OrderInTrip $beforeDropPoint (
		SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId AND OrderInTrip<>0
		) AND `TripPoint_ID` NOT IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 1
		AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($TripPoint_ID);
		while ($stmt->fetch()) {
			$pointBeforeArr[] =  $TripPoint_ID;
		}
		$stmt->close();
		
		
		$query = "SELECT MIN(`OrderInTrip`) FROM `tms_trippoint` WHERE `Trip_ID` = $trip_id";
		writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($OrderInTrip2);
		$stmt->fetch();
		$stmt->close();
		writeToLogFile( ' -> OrderInTrip Selected '.date('Y-m-d H:i:s').' '.$OrderInTrip2 );
		
		$orderInTrip = 2;
		if($OrderInTrip2 > 1){ $orderInTrip++; }
		
		
		writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$orderInTrip );
		foreach ($pointBeforeArr as $idPoint) {
			$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			echo $query."\n";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->close();
			$orderInTrip++;
		}
		writeToLogFile( ' -> orderInTrip 2 '.date('Y-m-d H:i:s').' '.$orderInTrip );
		foreach ($tripPointNewId as $idPoint) {
			$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			echo $query."\n";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->close();
			$orderInTrip++;
		}
		writeToLogFile( ' -> orderInTrip 3 '.date('Y-m-d H:i:s').' '.$orderInTrip );
		foreach ($pointAfterArr as $idPoint) {
			$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			echo $query."\n";
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->close();
			$orderInTrip++;
		}
		
		writeToLogFile( ' -> orderInTrip 4 '.date('Y-m-d H:i:s').' '.$orderInTrip );
		//$query = "SELECT TripPoint_ID FROM tms_trippoint WHERE Trip_ID=$trip_id AND `Type`=8 ORDER BY `OrderInTrip` DESC LIMIT 1";
		$query = "SELECT TripPoint_ID FROM tms_trippoint 
		LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
		WHERE Trip_ID=$trip_id AND `tms_loadunloadpoint`.`IsOrderPoint` = 0 ORDER BY `OrderInTrip` DESC LIMIT 1";
		
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($TripPoint_ID);
		$stmt->fetch();
		$stmt->close();
		
		//if(count($pointAfterArr) == 0){ $orderInTrip++; }
		
		
		$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$TripPoint_ID";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		echo $query."\n";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		$db->close();
		exit;
}

if (isset($_REQUEST['unBindPointFromTrip'])) {
	#$tripPoint_id = $_REQUEST['tripPoint_id'];
	$trip_id = $_REQUEST['trip_id'];
	$pointsArr = $_REQUEST['pointsArr'];	
	
	$strPoint = implode(',', $pointsArr);
	#check  is sklad
	$type = false;
	//$query = "SELECT `Type` FROM `tms_trippoint` WHERE `TripPoint_ID` IN ($strPoint) AND `Type`=8 LIMIT 1";
	$query = "SELECT `Type` FROM `tms_trippoint` 
LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
WHERE `TripPoint_ID` IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 0 LIMIT 1;";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($type);
	$stmt->fetch();
	$stmt->close();
	if ($type) {
		echo 0;
		exit;
	}
		
	$arrOfBindPoints = array();
	$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` WHERE Trip_ID=$trip_id AND TripPoint_ID NOT IN ($strPoint) ORDER BY `OrderInTrip`";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($TripPoint_ID);
	while ($stmt->fetch()) {
		$arrOfBindPoints[] = $TripPoint_ID;
	}
	$stmt->close();
	$orderInTrip = 1;
	foreach ($arrOfBindPoints as $TripPoint_ID) {
		$query = "UPDATE `tms_trippoint` SET `OrderInTrip`=$orderInTrip WHERE `Trip_ID`=$trip_id AND TripPoint_ID=$TripPoint_ID";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		$orderInTrip++;
	}
	
	foreach ($pointsArr as $tripPoint_id) {
		$query = "SELECT l.`OrderWarehouse_ID`, l.`LoadUnloadPoint_ID`, tp.`OrderInTrip`  FROM `tms_trippoint` tp
		INNER JOIN `tms_loadunloadpoint` l ON l.`LoadUnloadPoint_ID`=tp.`Point_ID`
		WHERE tp.`TripPoint_ID`=$tripPoint_id";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($order_id, $LoadUnloadPoint_ID, $OrderInTrip);
		$stmt->fetch();
		$stmt->close();
		
		$query = "DELETE FROM tms_trippoint WHERE TripPoint_ID=$tripPoint_id";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		$query = "DELETE FROM tms_loadunloadpoint WHERE `LoadUnloadPoint_ID`=$LoadUnloadPoint_ID";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		$query = "UPDATE `tms_order` SET IsInTrip=0 WHERE `Order_ID`=$order_id";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		$query = "UPDATE tms_trip SET `Distance` = NULL, `Time`=NULL, `StartTime`=NULL, `EndTime`=NULL WHERE Trip_ID=$trip_id";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		/*$tripPointDataArr = array();
		 $query = "SELECT `TripPoint_ID`, `OrderInTrip` FROM `tms_trippoint`
		WHERE `Trip_ID`=$trip_id AND `OrderInTrip`>$OrderInTrip ";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($TripPoint_ID, $OrderInTrip);
		while ($stmt->fetch()) {
		$tripPointDataArr[] = array(
				'TripPoint_ID' => $TripPoint_ID,
				'OrderInTrip' => $OrderInTrip
		);
		}
		
		if (count($tripPointDataArr)>0) {
		foreach ($tripPointDataArr as $valueArr) {
		$newOrderInTrip = $valueArr['OrderInTrip']--;
		$query = "UPDATE `tms_trippoint` SET OrderInTrip=$newOrderInTrip,  `Distance` = NULL, `Time`= NULL
		WHERE TripPoint_ID=$valueArr[TripPoint_ID]";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		//_________________
			
		}
		} else {
		$query = "UPDATE `tms_trippoint` SET `Distance` = NULL, `Time`= NULL WHERE `Trip_ID`=$trip_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		} */
		
		
		//+++
		$query = "DELETE FROM `tms_lupointcargo` WHERE `LUPoint_ID` = ".$tripPoint_id.";";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		
		/*$query = "DELETE FROM `tms_lupointcargo_index` WHERE `ID` IN (SELECT `LUPointCargo_ID` FROM `tms_lupointcargo` WHERE `LUPoint_ID` = ".$tripPoint_id.");";
		writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();*/
		//+++
	}
	
	$db->close();
	exit;
}



$c = 0;
function check($lid){
	global $c;
	global $db;
	$c++;
	$in_progress = 0;
	if($c<240)
	{
		$query = "SELECT `in_progress` FROM `tms_web_tasks` WHERE `id` = ".$lid.";";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($in_progress);
		$stmt->fetch();
		$stmt->close();
		
		if( $in_progress == 0 )
		{
			sleep(1); check($lid);
		}elseif($in_progress == -1)
		{ 
			$query = "SELECT `result_message` FROM `tms_web_tasks` WHERE `id` = ".$lid.";";
			writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->bind_result($result_message);
			$stmt->fetch();
			$stmt->close();
			die($result_message);
		}elseif($in_progress == 1)
		{
			//return $in_progress;
			//echo true; exit;
			die('true');
		}else
		{
			die('true');
		}
	}else
	{
		return false;
		$query = "UPDATE `tms_web_tasks` SET `in_progress`=-1 WHERE `id` = ".$lid.";";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
	}
}

if (isset($_REQUEST['CalculateTrip'])) {
	
	$Login = $_REQUEST['Login'];
	$TripID = $_REQUEST['Trip_ID'];
	$WalkerNum = $_REQUEST['WalkerNum'];
	$WithChange = $_REQUEST['Withchange'];
	//if($_REQUEST['Withchange'] == true){$WithChange = 1;}else{$WithChange = 0;}
	
	$countid=0;
	$query = "SELECT COUNT(t.`Trip_ID`) FROM tms_trip t INNER JOIN tms_car_snapshot cs ON cs.ID = t.`Car_ID` INNER JOIN tms_car c ON cs.`Car_ID` = c.`Car_ID` INNER JOIN tms_device d ON d.`ID` = c.`Device_id` WHERE d.`Login` = '".$Login."' AND t.`Project_ID` = (SELECT `Project_ID` FROM `tms_trip` WHERE `Trip_ID`=".$TripID.") AND t.`Distance` IS NULL AND t.`Trip_ID` NOT IN(".$TripID.") AND t.WalkerNum < ".$WalkerNum.";";
	writeToLogFile( ' -> '.date('Y-m-d H:i:s').' '.$query );
	if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $stmt->bind_result($countid);
      $stmt->fetch();
	  $stmt->close();
    }
	writeToLogFile( ' -> countid '.date('Y-m-d H:i:s').' '.$countid );
	if((int)$countid > 0){
		echo false;
		writeToLogFile( ' -> false '.date('Y-m-d H:i:s'));
	}else{
	
	/*$xml = '<Data Login="'.$Login.'" Password="'.$password.'">
	<p type="CalculateTrip">
	<p type="CalculateTrip"  TripID="'.$TripID.'" />
	</p>
	</Data>';*/
	
	
	
	$xml = '<Data InstanceID="'.$client_id.'" >
	<p type="CalculateTrip">
	<p type="CalculateTrip"  TripID="'.$TripID.'" ChangeOrder="'.$WithChange.'" />
	</p>
	</Data>';
    
	//$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$Login.")";
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$client_id.")";
	
	writeToLogFile( ' -> query CalculateTrip '.date('Y-m-d H:i:s').' '.$query );
	//echo $query;
	  //writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroxml <> '.$query );
	if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $last_id = $db->insert_id;
      $stmt->close();
	  //echo true;
	  
		$res = check($last_id);
		echo $res;
	  
    }
	
	}
	
	$db->close();
	exit;
}


if (isset($_REQUEST['ReleaseTrip'])) {
	
	$Project_ID = $_REQUEST['Project_ID'];
	$Login = $_REQUEST['Login'];
	$arrayTripId = $_REQUEST['arrayTripId'];
	
	//if(count($arrayTripId)>1){
	$i=0;
	$xml = '<Data InstanceID="'.$client_id.'" >
			<p type="ReleaseTripNotAll">';
	while ($i < count($arrayTripId)){
		$xml .= '<p type="ReleaseTripNotAll"  Trip_ID="'.$arrayTripId[$i].'" ProjectID="'.$Project_ID.'"  />';
		$i++;
	}
	$xml .= '</p>
			</Data>';
	/*}else{
	$xml = '<Data InstanceID="'.$client_id.'" >
			<p type="ReleaseTrip">
			<p type="ReleaseTrip"  ProjectID="'.$Project_ID.'" />
			</p>
			</Data>';
    }*/
	
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$client_id.")";
	
	//echo $query; exit;
	//writeToLogFile( ' -> '.date('Y-m-d H:i:s').' <> synchroxml <> '.$query );
	if ($stmt = $db->prepare($query)){
    $stmt->execute();
	$last_id = $db->insert_id;
    $stmt->close();
	//echo true;
	  
	$res = check($last_id);
	echo $res;
	}
	
	
	
	$db->close();
	exit;
}

if (isset($_REQUEST['RecalculateTrip'])) {
	
	$Login = $_REQUEST['Login'];
	$TripID = $_REQUEST['Trip_ID'];
	

	/*$xml = '<Data Login="'.$Login.'" Password="'.$password.'">
	<p type="RecalculateTrip">
	<p type="RecalculateTrip"  TripID="'.$TripID.'" />
	</p>
	</Data>';*/
    
	$xml = '<Data InstanceID="'.$client_id.'" >
	<p type="RecalculateTrip">
	<p type="RecalculateTrip"  TripID="'.$TripID.'" />
	</p>
	</Data>';
	
	//$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$Login.")";
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$client_id.")";

	  if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $last_id = $db->insert_id;
      $stmt->close();
	  //echo $last_id;
	  
		$res = check($last_id);
		echo $res;
	  
    }
	
	
	
	$db->close();
	exit;
}



if (isset($_REQUEST['AutoplanTrip'])) {

	$time = $_REQUEST['time'];
	$Project_ID = $_REQUEST['project'];
	
	//$query = "SELECT `Project_ID` FROM `tms_project` WHERE DATE(`Date`)='".$time."' AND `Executing`=1 AND `Client_ID` = ".$client_id." ORDER BY `Date` DESC;";
	/*$query = "SELECT `Project_ID` FROM `tms_project` WHERE DATE(`Date`)='".$time."' AND `Executing`=1 AND `Client_ID` = ".$client_id." ORDER BY `Project_ID` DESC LIMIT 1;";
	if($stmt = $db->prepare($query)){
	$stmt->execute();
	$stmt->bind_result($Project_ID);
	$stmt->fetch();
	$stmt->close();
	}*/
	
	$xml = '<Data InstanceID="'.$client_id.'" >
	<p type="AutoplanTrip">
	<p type="AutoplanTrip" ProjectID="'.$Project_ID.'" />
	</p>
	</Data>';
	
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$client_id.",0)";
	if ($stmt = $db->prepare($query)){
		$stmt->execute();
		$last_id = $db->insert_id;
		$stmt->close();
	  
		$res = check($last_id);
		echo $res;
	}

	$db->close();
	exit;
	
	
}




if ($_REQUEST['func'] == 'getRoutePath') {
	$TripID = $_REQUEST['TripID'];
	$trip_route = "";
	$query = "SELECT ASTEXT(`Route`) FROM `tms_trippoint` WHERE `Trip_ID` = ".$TripID." ORDER BY `OrderInTrip` ASC;";
	//echo $query;
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($str);
	while ($stmt->fetch()) {
		if($str || $str!=""){
		$str = substr($str,11,strlen($str)-1);
		$str = substr($str,0,strlen($str)-1);
		$trip_route .= $str;
		}
	}
	$stmt->close();
	//if($trip_route!=""){ $trip_route = substr($str,0,strlen($str)-1); }
	echo $trip_route;
	$db->close();
	exit;
}

if ($_REQUEST['func'] == 'getRoutePoint') {	
	$TripID = $_REQUEST['TripID'];
	$arrOfCoordinates = array();
	
	//$query = "SELECT `GeoX`,`GeoY`,`TripPoint_ID`,`Name`,`Address`,`EstimateTime`,`Type` FROM `tms_trippoint` WHERE `Trip_ID` = ".$TripID.";";	 
	
	$query = "SELECT t.`GeoX`, t.`GeoY`, t.`TripPoint_ID`, t.`Name`, t.`Address`, t.`EstimateTime`, lp.IsOrderPoint AS `Type`, c.Name as Client, t.`OrderInTrip` FROM
	`tms_trippoint` t
	INNER JOIN `tms_loadunloadpoint` lp ON
	t.`Point_ID` = lp.`LoadUnloadPoint_ID`
	LEFT JOIN `tms_order` o ON lp.`OrderWarehouse_ID`=o.`Order_ID`
	LEFT JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
	LEFT JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`	
	WHERE `Trip_ID` = ".$TripID.";";
	
	if($stmt = $db->prepare($query)){
		$stmt->execute();
		$stmt->bind_result($GeoX,$GeoY,$Id,$Name,$Address,$EstimateTime,$Type,$Client,$OrderInTrip);
		while ($stmt->fetch()) {
			$arrOfCoordinates[] = array(
				'GeoX' => $GeoX,
				'GeoY' => $GeoY,
				'Id' => $Id,
				'Name' => $Name,
				'Address' => $Address,
				'EstimateTime' => $EstimateTime,
				'Phone' => $Phone,
				'Type' => $Type,
				'Client' => $Client,
				'OrderInTrip' => $OrderInTrip
			);
		}
		$stmt->close();
		echo json_encode($arrOfCoordinates);
	}
	$db->close();
	exit;
}

if ($_REQUEST['resetCalculate']) {
	sleep(1);
}


if (isset($_REQUEST['removePointPositionInTrip'])) {
	$fromPointId = $_REQUEST['fromPointId'];
	$pointsArr = $_REQUEST['pointsArr'];
	$dropPosition = $_REQUEST['dropPosition'];
	$trip_id = $_REQUEST['trip_id'];
	$strPoint = implode(',', $pointsArr);
	$Type = false;
	//$query = "SELECT `Type` FROM `tms_trippoint` WHERE `TripPoint_ID` IN ($strPoint) AND Trip_ID=$trip_id AND `Type`=8 LIMIT 1";
	$query = "SELECT `Type` FROM `tms_trippoint` 
LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
WHERE `TripPoint_ID` IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 0 LIMIT 1";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($Type);
	$stmt->fetch();
	$stmt->close();
	if ($Type) {
		echo 0;
		exit;
	}
	
	if ($dropPosition == 'after') {
		$afterDropPoint = '>';
		$beforeDropPoint = '<=';
	} elseif ($dropPosition == 'before') {
		$afterDropPoint = '>=';
		$beforeDropPoint = '<';
	}
	
	
	//after drop point
	$pointAfterArr = array();
	/*$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` WHERE OrderInTrip $afterDropPoint (
	SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId
	) AND `TripPoint_ID` NOT IN ($strPoint) AND `Type`<>8 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";*/
	
	$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` 
LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
WHERE OrderInTrip $afterDropPoint (
	SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId
	) AND `TripPoint_ID` NOT IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 1 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";
	
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($TripPoint_ID);
	while ($stmt->fetch()) {
	$pointAfterArr[] =  $TripPoint_ID;
	}
	$stmt->close();
	
	$pointBeforeArr = array();
	/*$query = "SELECT `TripPoint_ID` FROM `tms_trippoint` WHERE OrderInTrip $beforeDropPoint (
	SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId
	) AND `TripPoint_ID` NOT IN ($strPoint) AND `Type`<>8 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";*/
	$query = "SELECT `TripPoint_ID` FROM `tms_trippoint`
	LEFT JOIN `tms_loadunloadpoint` ON tms_trippoint.`Point_ID` = tms_loadunloadpoint.`LoadUnloadPoint_ID`
	WHERE OrderInTrip $beforeDropPoint (
	SELECT OrderInTrip FROM tms_trippoint WHERE `TripPoint_ID`=$fromPointId
	) AND `TripPoint_ID` NOT IN ($strPoint) AND tms_loadunloadpoint.`IsOrderPoint` = 1 AND Trip_ID=$trip_id ORDER BY `OrderInTrip`";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($TripPoint_ID);
	while ($stmt->fetch()) {
	$pointBeforeArr[] =  $TripPoint_ID;
	}
	$stmt->close();
	
	
		$query = "SELECT MIN(`OrderInTrip`) FROM `tms_trippoint` WHERE `Trip_ID` = $trip_id";
		writeToLogFile( ' -> orderInTrip '.date('Y-m-d H:i:s').' '.$query );
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($OrderInTrip2);
		$stmt->fetch();
		$stmt->close();
		writeToLogFile( ' -> OrderInTrip Selected '.date('Y-m-d H:i:s').' '.$OrderInTrip2 );
		
		$orderInTrip = 2;
		if($OrderInTrip2 > 1){ $orderInTrip++; }

	
	
	foreach ($pointBeforeArr as $idPoint) {
	$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->close();
	$orderInTrip++;
	}
	foreach ($pointsArr as $idPoint) {
	$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->close();
	$orderInTrip++;
	}
	foreach ($pointAfterArr as $idPoint) {
	$query = "UPDATE `tms_trippoint` SET OrderInTrip =$orderInTrip WHERE `TripPoint_ID`=$idPoint";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->close();
	$orderInTrip++;
	}
	
	$query = "UPDATE `tms_trippoint` SET `Distance` = NULL, `Time`= NULL WHERE `Trip_ID`=$trip_id";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->close();
	
	$db->close();
	exit;
}



if (isset($_REQUEST['checkProjectExist'])) {
	
	$time = $_REQUEST['time'];
	
	//$query = "SELECT COUNT(Project_ID) AS RESULT FROM `tms_project` WHERE DATE(`Date`)=DATE(NOW()) AND `Executing`=1;";
	//$query = "SELECT COUNT(Project_ID) AS RESULT FROM `tms_project` WHERE DATE(`Date`)=DATE('".$time."') AND `Executing`=1;";
	$query = "SELECT COUNT(Project_ID) AS RESULT FROM `tms_project` WHERE DATE(`Date`)=DATE('".$time."') AND `Executing`=1 AND `Client_ID`=".$client_id.";";
	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo json_encode($result);
	}
	$db->close();
	exit;
}

if (isset($_REQUEST['addProject'])) {
	$name_project = $_REQUEST['name_project'];
	$date_project = $_REQUEST['date_project'];
	
	$xml = '<Data InstanceID="'.$client_id.'" >
	<p type="CreateProject">
	<p type="CreateProject"  ProjectName="'.$name_project.'" ProjectDate="'.$date_project.'" />
	</p>
	</Data>';
    
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xml."',".$client_id.")";
	  //echo $query;
	  if ($stmt = $db->prepare($query)){
      $stmt->execute();
	  $last_id = $db->insert_id;
      $stmt->close();
	  //echo $last_id;
	  
		$res = check($last_id);
		echo $res;
	  
    }
	
	
	
	$db->close();
	exit;
}

if (isset($_REQUEST['unLockTrip'])) {
	$trip_id = $_REQUEST['trip_id'];
	$query = "UPDATE `tms_web_lock_trip` SET is_lock=0 WHERE  `trip_id`=$trip_id";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->close();
	$db->close();
	exit;
}

if (isset($_REQUEST['lockTrips'])) {
	$projectId = $_REQUEST['projectId'];
	$tripIdArr = array();
	$query = "SELECT `Trip_ID` FROM `tms_trip` WHERE  `Project_ID`=$projectId AND `Distance` IS NOT NULL";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($Trip_ID);
	while ($stmt->fetch()) {
		$tripIdArr[] = $Trip_ID;
	}
	$stmt->close();
	foreach ($tripIdArr as $trip_id) {
		$id = false;
		$query = "SELECT id FROM `tms_web_lock_trip` WHERE `trip_id`=$trip_id";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($id);
		$stmt->fetch();
		$stmt->close();
		if ($id) {
			$query = "UPDATE `tms_web_lock_trip` SET is_lock=1 WHERE id=$id";
		} else {
			$query = "INSERT INTO `tms_web_lock_trip` (`trip_id`, `is_lock`) VALUES ($trip_id, 1)";
		}
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		unset($id);
	}
	
	$db->close();
	exit;
}




if (isset($_REQUEST['DeleteTrip'])) {
	$arrayOrdersId = $_REQUEST['arrayOrdersId'];	
	$i=0;
	
	$xml = '<Data InstanceID="'.$client_id.'" >
			<p type="DeleteTrip">';
	
	while ($i < count($arrayOrdersId)){
		$xml .= '<p type="Trip"  Trip_ID="'.$arrayOrdersId[$i].'"  />';
		$i++;
	}
	
	$xml .= '</p>
			</Data>';
	
	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$client_id.",0)";
	//echo $query;
	if ($stmt = $db->prepare($query)){
	$stmt->execute();
	$last_id = $db->insert_id;
	$stmt->close();
	  
	$res = check($last_id);
	echo $res;
	
	}else{ echo json_encode(array("success" => true, "message" => $db->errno.' '.$db->error)); }
}







if (isset($_REQUEST['tms_order_onmap'])) {
	$data = array();
	$time = $_REQUEST['time'];

$query = "SELECT o.`Order_ID`, c.Name AS `Client`,o.Code,o.OriginalAddress,o.`GeoX`,o.`GeoY`,o.`Name`
FROM `tms_order` o
INNER JOIN `tms_warehouse` w ON w.`Warehouse_ID` = o.`Warehouse_ID`
INNER JOIN `tms_client` c ON c.`Client_ID` = w.`Client_ID`
INNER JOIN `tms_project` p ON p.`Project_ID`= o.`Project_ID`
WHERE o.`IsInTrip` = 0 AND p.`Client_ID` = ".$client_id." AND p.`Project_ID` = (SELECT Project_ID FROM tms_project WHERE DATE(tms_project.`Date`) = '".$time."' AND tms_project.`Client_ID` = ".$client_id." ORDER BY tms_project.`Project_ID` DESC LIMIT 1);";

	if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo json_encode($result);
	}
	$db->close();
	exit;
}

if ($_POST['func'] == 'showCenterMap')
{
	
	$query = "SELECT `MapCenter_longitude`, `MapCenter_latitude` FROM `wm_settings` WHERE `client_id` = ".$client_id.";";
	if ($stmt = $db->prepare($query))
	{
		if(!$stmt = $db->query($query)){
			echo '{"success":false,"message":"'.$db->errno.' '.$db->error.'"}';
	}else{
			//$result = $stmt->fetch_all(MYSQLI_ASSOC);
			for ($result = array(); $tmp = $stmt->fetch_array(MYSQLI_ASSOC);) $result[] = $tmp;
			$stmt->close();
			echo json_encode($result);
	}
	$db->close();
	exit;
	}
}