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

//set_time_limit(900);

$instance_id = $_SESSION['client_id'];
$user_id = $_SESSION['id'];
$role = $_SESSION['role_id'];

// -- old monit task function include --->
//include "LogistMobile_checkwebtask.php";
// <-- old monit task function include ---

$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='ilog';
$DB_PASS='1111';
$DB_NAME='tms37';
$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;
        }

$locale = $_SESSION['locale'];
if($locale == 'en'){
	include "/lang/LogistMobile/lang.en.php";
}elseif($locale == 'ru'){
	include "/lang/LogistMobile/lang.ru.php";
}elseif($locale == 'ua'){
	include "/lang/LogistMobile/lang.ua.php";
}		

include "LogistMobile_function.php";

			
// -- old monit task function --->
/*
$c = 0;
function check($lid){
	global $c;
	global $db;
	$c++;
	$in_progress = 0;
	if($c<360){
	$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);
	}else{ 
		//return $in_progress;
		//echo true; exit;
		//return (true);
		//die('true');
		$db->close();
		die (json_encode(array("success" => false, "message" => '')));
	}
	}else{
		
		$query = "UPDATE `tms_web_tasks` SET `in_progress`=-1 WHERE `id` = ".$lid.";";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		$db->close();
		die (json_encode(array("success" => false, "message" => '')));
	}
}
*/
// <-- old monit task function ---


if ($_REQUEST['func'] == 'ImpexpEdit') 
{
	$original_address = addslashes(trim(rtrim($_REQUEST['OriginalAddress'])));
	$geoX = $_REQUEST['GeoX'];
	$geoY = $_REQUEST['GeoY'];
	$project = $_REQUEST['project'];
	$id = $_REQUEST['id'];
	
	$geoX = str_replace(',','.',$geoX);
	$geoY = str_replace(',','.',$geoY);
	
	$query = "UPDATE tms_impexp_ordersource SET `Address`= '".$original_address."', GeoX = '".$geoX."', `GeoY` = '".$geoY."', LinkedOrderID = NULL WHERE ID = ".$id.";";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
		$stmt->close();
		
		
	$xml = '<Data InstanceID="'.$instance_id.'" >
			<p type="LinkSingleOrder">
			<p type="OrderSource" OrderSource_ID="'.$id.'" ProjectID="'.$project.'" />
			</p>
			</Data>';

	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$instance_id.",0)";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
			$last_id = $db->insert_id;
			$stmt->close();
			echo (json_encode(array("success" => true, "message" => $last_id)));
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	
		
		//echo (json_encode(array("success" => true, "message" => "")));
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error.' '.$query ))); }	
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error.' '.$query ))); }
	
	$db->close();
	exit;
}


if ($_REQUEST['func'] == 'ImpexpRelease') 
{
	$project = $_REQUEST['project'];
	
	$xml = '<Data InstanceID="'.$instance_id.'" >
			<p type="LinkOrderSource">
			<p type="LinkOrderSource"  ProjectID="'.$project.'" />
			</p>
			</Data>';

	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$instance_id.",0)";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
			$last_id = $db->insert_id;
			$stmt->close();
			echo (json_encode(array("success" => true, "message" => $last_id)));
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	
	$db->close();
	exit;
}


if (isset($_REQUEST['DeleteOrders'])) 
{
	$arrayOrdersId = $_REQUEST['arrayOrdersId'];	
	$i=0;
	
	
	if(isset( $_REQUEST['all'])){
	$project = $_REQUEST['project'];
	$query = "DELETE FROM `tms_impexp_ordersource` WHERE `LinkedOrderID` IN (".implode(',',$arrayOrdersId).") AND `Project_ID` = ".$project.";";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
		$stmt->close();
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); exit;}
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); exit;}
	}
	
	$xml = '<Data InstanceID="'.$client_id.'" >
			<p type="DeleteOrder">';
	
	while ($i < count($arrayOrdersId)){
		$xml .= '<p type="Order"  Order_ID="'.$arrayOrdersId[$i].'"  />';
		$i++;
	}

	$xml .= '</p>
			</Data>';

	$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$instance_id.",0)";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
			$last_id = $db->insert_id;
			$stmt->close();
			echo (json_encode(array("success" => true, "message" => $last_id)));
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
	
	$db->close();
	exit;
}

/*if (isset($_REQUEST['DeleteOrdersAll'])) 
{
	$arrayOrdersId = $_REQUEST['arrayOrdersId'];
	$project = $_REQUEST['project'];
	
	$query = "DELETE FROM `tms_impexp_ordersource` WHERE `LinkedOrderID` IN (".implode(',',$arrayOrdersId).") AND `Project_ID` = ".$project.";";
	if ($stmt = $db->prepare($query)){
	if ($stmt->execute()){
		$stmt->close();
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); }
	}else{ echo json_encode(array('success'=>false, 'message'=>$db->errno . ' ' . $db->error)); }
	
}*/


if ($_REQUEST['func'] == 'addedit_app') 
{
	
	$name = $_REQUEST['Name'];
	$code = $_REQUEST['Code'];
	if($name == "")
	{
		$name = $code;
	}
	
	$original_address = addslashes(trim(rtrim($_REQUEST['OriginalAddress'])));
	$startTime = $_REQUEST['StartTime'];
	$endTime = $_REQUEST['EndTime'];
	$load_unload_time = $_REQUEST['LoadUnloadTime'];
	$geoX = $_REQUEST['GeoX'];
	$geoY = $_REQUEST['GeoY'];
	$weight = $_REQUEST['weight'];
	$note = $_REQUEST['note'];
	$type_work = $_REQUEST['type_work'];
	$phone_number = $_REQUEST['phone_number'];

	$project = $_REQUEST['project'];
	
	$WAREHOUSE_CODE = $_REQUEST['WAREHOUSE_CODE'];
	
	//$logger = new MessageAndLogs();


		//$dir = $_SERVER['DOCUMENT_ROOT']."/monit2_task_ne_test/app/Logist/files/";
		$dir = $_SERVER['DOCUMENT_ROOT']."/app/Logist/files/";
		
		$filename = $dir.$instance_id."task".rand(1,100).".xml";
		
		if( file_exists($filename) ){ unlink($filename); }
		$dom = new domDocument("1.0", "UTF-8");
		$dom->preserveWhiteSpace = false;
		$dom->formatOutput = true;
		
		$root = $dom->createElement("ORDERS");
		$dom->appendChild($root);
					
		$_ORDER = $dom->createElement("ORDER");
		$root->appendChild($_ORDER);
		
		$_CODE = $dom->createElement("CODE", $code);
		$_ORDER->appendChild($_CODE);
		$_NAME = $dom->createElement("NAME", $name);
		$_ORDER->appendChild($_NAME);
		
		$_ADDRESS = $dom->createElement("ADDRESS", $original_address);
		$_ORDER->appendChild($_ADDRESS);
		
		$_GeoX = $dom->createElement("GeoX", $geoY);
		$_ORDER->appendChild($_GeoX);
		$_GeoY = $dom->createElement("GeoY", $geoX);
		$_ORDER->appendChild($_GeoY);
		$_COMMENTS_ORDERS = $dom->createElement("COMMENTS_ORDERS", $note);
		$_ORDER->appendChild($_COMMENTS_ORDERS);
		$_COMMENTS = $dom->createElement("COMMENTS", '');
		$_ORDER->appendChild($_COMMENTS);
		$_COMMENTS_SHOP = $dom->createElement("COMMENTS_SHOP", '');
		$_ORDER->appendChild($_COMMENTS_SHOP);
		$_CLIENT_CODE = $dom->createElement("CLIENT_CODE", '0000-0000-0000-0000-0001');
		$_ORDER->appendChild($_CLIENT_CODE);
		$_CLIENT_NAME = $dom->createElement("CLIENT_NAME", '');
		$_ORDER->appendChild($_CLIENT_NAME);
		$_SHOP_CODE = $dom->createElement("SHOP_CODE", '419A-8D7B-0000-0000-0000');
		$_ORDER->appendChild($_SHOP_CODE);
		$_SHOP_NAME = $dom->createElement("SHOP_NAME", 'склад');
		$_ORDER->appendChild($_SHOP_NAME);
		$_DELIVERY_DATE = $dom->createElement("DELIVERY_DATE", date('m/d/Y'));
		$_ORDER->appendChild($_DELIVERY_DATE);
		//$_SHOP_WORK_TIME = $dom->createElement("SHOP_WORK_TIME", '8:00-15:00');
		$_SHOP_WORK_TIME = $dom->createElement("SHOP_WORK_TIME", $startTime.'-'.$endTime);
		$_ORDER->appendChild($_SHOP_WORK_TIME);
		$_SHOP_DINNER_TIME = $dom->createElement("SHOP_DINNER_TIME", '');
		$_ORDER->appendChild($_SHOP_DINNER_TIME);
		$_UNLOAD_TIME = $dom->createElement("UNLOAD_TIME", $load_unload_time);
		$_ORDER->appendChild($_UNLOAD_TIME);
		$_SPECIALIZATION_Name = $dom->createElement("SPECIALIZATION_Name", '');
		$_ORDER->appendChild($_SPECIALIZATION_Name);
		$_SPECIALIZATION_Id = $dom->createElement("SPECIALIZATION_Id", '');
		$_ORDER->appendChild($_SPECIALIZATION_Id);
		$_EXPEDITION = $dom->createElement("EXPEDITION", '');
		$_ORDER->appendChild($_EXPEDITION);
		
		$_WAREHOUSE_CODE = $dom->createElement("WAREHOUSE_CODE", $WAREHOUSE_CODE);
		$_ORDER->appendChild($_WAREHOUSE_CODE);
		
		if($instance_id == 292){	
			$_PHONE = $dom -> createElement("PHONE", $phone_number);
			$_ORDER -> appendChild($_PHONE);
			$_CUSTOMSTR4 = $dom -> createElement("CUSTOMSTR4", $type_work);
			$_ORDER -> appendChild($_CUSTOMSTR4);
		}
		
		//$_PRODUCTS = $dom->createElement("PRODUCTS");
		//$_ORDER = $dom -> appendChild($_PRODUCTS);
		
		
		$xml = $dom->save($filename);

			$xml = '<Data InstanceID="'.$instance_id.'" >
			<p type="ImportDataXML">
			<p type="ImportDataXML"  ProjectID="'.$project.'" dir="'.$filename.'" />
			</p>
			</Data>';

			$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$instance_id.",0)";
			//echo $query;
			if ($stmt = $db->prepare($query)){
			$stmt->execute();
			$last_id = $db->insert_id;
			$stmt->close();
			//echo $last_id;
			
			echo (json_encode(array("success" => true, "message" => $last_id)));
			
			//$res = check($last_id);
					
					
			/*if($res){
				//echo (json_encode(array("success" => true, "message" => 'Файл с заявками успешно импортирован'))); exit;
				echo (json_encode(array("success" => true, "message" => $messageConfirm))); exit;
			}else{
				//echo (json_encode(array("success" => false, "message" => 'Ошибка импорта Файла с заявками'))); exit;
				echo (json_encode(array("success" => false, "message" => $messageErrorImport))); exit;
			}*/
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); exit;  }
			
	$db->close();
	exit;
}




$start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 50;

if ($_GET['func'] == 'selectNameTP') 
{
	if(isset($_POST['name_tp']))
	{
		
		$selectNameTP = $_POST['name_tp'];
		//echo $selectNameTP; exit;
		$query = "SELECT `Code`, DATE_FORMAT(`StartServeTime`, '%H:%i') AS `StartServeTime`, DATE_FORMAT(`EndServeTime`, '%H:%i') AS  `EndServeTime`, `Address`, `GeoX`, `GeoY`, `StaticUnloadTime` FROM `tms_warehouse` WHERE `Name`= '".$selectNameTP."' AND `WarehouseType` = 2 AND `instanceID`=".$instance_id.";";
		//echo $query; exit;
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($Code,$StartServeTime,$EndServeTime,$Address,$GeoX,$GeoY,$StaticUnloadTime);
		while ($stmt->fetch()) {
			$data[] = array(
				'code' => $Code,
				'StartServeTime' => $StartServeTime,
				'EndServeTime' => $EndServeTime,
				'Address' => $Address,
				'GeoX' => $GeoX,
				'GeoY' => $GeoY,
				'StaticUnloadTime' => $StaticUnloadTime
			);
		}
		echo json_encode($data);
		
	}else
	{
		$name_search = $_GET['query'];
		$query = "SELECT `Name` FROM `tms_warehouse` WHERE `WarehouseType`=2 AND `Name` LIKE '$name_search%' AND `instanceID`=".$instance_id.";";
		 //echo $query;
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->bind_result($nameTP);
		while ($stmt->fetch()) {
			$data[] = array(
				'nameTP' => $nameTP
			);
		}
		if(empty($data))
		{
			echo json_encode(array("success" => false, "message" => ''));
		}else{
			echo json_encode($data);
		}
		
	}
}


if (isset($_REQUEST['showCheckpoint'])) {
	$data = array();
	//$query = "SELECT `Id`,`StartCheckTime`,`EndCheckTime`,`Description`,`Name`,`FactTripID`,`CarID`,`GeoX`,`GeoY`,`Date`,`OrderInTrip`,`Distance`,`Time`,`PointState`, `Address` FROM `tms_checkpoint`";
	
	$project = $_REQUEST['project'];
	
	$warehouse_in = warehouse_to_users($db,$user_id,$instance_id);
	
	if(!isset($project) || $project == ""){
		echo '{"total":"","rows":[]}';
	}else{
	
	if(count($warehouse_in)>0 && $role!=1){
		$FromWarehouse = " AND o.`FromWarehouse_ID` IN (".implode(",", $warehouse_in).")";
	}else{
		$FromWarehouse = "";
	}
	
	$query="SELECT COUNT(o.`Order_ID`) FROM `tms_order` o INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID` WHERE  p.`Client_ID` = ".$instance_id." AND p.`Project_ID` = ".$project." ".$FromWarehouse.";";
	//echo $query; exit;
	
	if ($stmt = $db->prepare($query)) {
        $stmt->execute();
        $stmt->bind_result($total);
        $stmt->fetch();
        $stmt->close();
	}
	
	/*$query = "SELECT o.`Order_ID`,o.`OriginalAddress`,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`LoadUnloadTime`,o.`IsInTrip`,o.`GeoX`,o.`GeoY`,DATE(o.`Date`) Date,o.`LinkAddress`,o.`Priority`,o.`Name`,o.`Code`, o.`CustomString1`, o.`CustomString2`, o.`CustomString3`, o.`CustomString4`, o.`CustomString5`, o.`CustomString6`, o.`CustomString7`, o.`CustomString8`, z.`Name` AS ZoneName
FROM `tms_order` o
INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID`
LEFT JOIN `tms_zone` z ON z.`Zone_ID` = o.`Zone_ID`
WHERE  p.`Client_ID` = ".$instance_id." AND p.`Project_ID` = ".$project." ".$FromWarehouse." LIMIT ".abs($start).",".($limit).";";*/

$query = "SELECT o.`Order_ID`,o.`OriginalAddress`,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`LoadUnloadTime`,o.`IsInTrip`,ROUND(o.`GeoX`,6) AS GeoX,ROUND(o.`GeoY`,6) AS GeoY, DATE(o.`Date`) AS Date, o.`LinkAddress`,o.`Priority`,o.`Name`,o.`Code`, o.`CustomString1`, o.`CustomString2`, o.`CustomString3`, o.`CustomString4`, o.`CustomString5`, o.`CustomString6`, o.`CustomString7`, o.`CustomString8`, z.`Name` AS ZoneName
,ROUND(SUM(ABS(oc.`CargoValueVolume`)),2) AS ValueVolume, ROUND(SUM(ABS(oc.`CargoValueWeight`)),2) AS ValueWeight
FROM `tms_order` o
INNER JOIN `tms_ordercargo` oc ON oc.`Order_ID` = o.`Order_ID`
INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID`
LEFT JOIN `tms_zone` z ON z.`Zone_ID` = o.`Zone_ID`
WHERE  p.`Client_ID` = ".$instance_id." AND p.`Project_ID` = ".$project." ".$FromWarehouse." GROUP BY o.`Order_ID` LIMIT ".abs($start).",".($limit).";";

	//echo $query; exit;
	
	
	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 '{"total":"'.$total.'","rows":'.json_encode($result).'}';
	}
	
	}
	
	$db->close();
	exit;

}

if (isset($_REQUEST['showCargoCheckpoint'])) {
	$data = array();
	//$query = "SELECT `Id`,`StartCheckTime`,`EndCheckTime`,`Description`,`Name`,`FactTripID`,`CarID`,`GeoX`,`GeoY`,`Date`,`OrderInTrip`,`Distance`,`Time`,`PointState`, `Address` FROM `tms_checkpoint`";
	
	$order_ID = $_REQUEST['order_ID'];
	
	$query="SELECT COUNT(o.`Name`)
									FROM `tms_ordercargo` o
									WHERE o.`Order_ID` = ".$order_ID." AND o.`Name` IS NOT NULL AND (ABS(o.`CargoValueVolume`) > 0 OR ABS(o.`CargoValueWeight`) > 0 OR ABS(o.`CargoValueCount`) > 0);";
	if ($stmt = $db->prepare($query)) 
	{
        $stmt->execute();
        $stmt->bind_result($total);
        $stmt->fetch();
        $stmt->close();
	}
	
	$query = "SELECT o.`Name`, o.`Cost`, CONCAT(ROUND(ABS(o.`CargoValueVolume`),2), ', ',(SELECT `name` FROM `tms_dimensionunit` WHERE `id` = o.`DimensionUnitVolume_ID`)) AS `CargoValueVolume`, CONCAT(ROUND(ABS(o.`CargoValueWeight`),2), ', ',(SELECT `name` FROM `tms_dimensionunit` WHERE `id` = o.`DimensionUnitWeight_ID`)) AS `CargoValueWeight`, CONCAT(ROUND(ABS(o.`CargoValueCount`),2), ', ',(SELECT `name` FROM `tms_dimensionunit` WHERE `id` = o.`DimensionUnitCount_ID`)) AS `CargoValueCount`
					FROM `tms_ordercargo` o
					WHERE o.`Order_ID` = ".$order_ID." AND o.`Name` IS NOT NULL AND (ABS(o.`CargoValueVolume`) > 0 OR ABS(o.`CargoValueWeight`) > 0 OR ABS(o.`CargoValueCount`) > 0)
					LIMIT ".abs($start).",".($limit).";";
	
	
	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);)
			{
				$tmp_s = explode('###', $tmp['Name']);
				$tmp['Name'] = $tmp_s[0];
				$tmp['Code'] = $tmp_s[1];
				$result[] = $tmp;
			}
			
			$stmt->close();
			echo '{"total":"'.$total.'","rows":'.json_encode($result).'}';
	}
	$db->close();
	exit;

}

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

	$project = $_REQUEST['project'];
	
	//$query="SELECT COUNT(o.`ID`) FROM `tms_impexp_ordersource` o INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID` WHERE  p.`Client_ID` = ".$instance_id." AND p.`Project_ID` = ".$project." AND `LinkedOrderID` IS NULL;";
	$query="SELECT COUNT(i.`ID`) FROM `tms_impexp_ordersource` i
LEFT JOIN `tms_order` o ON i.`LinkedOrderID` = o.`Order_ID`
WHERE i.`Project_ID` = ".$project."
AND o.`Order_ID` IS NULL;";
	if ($stmt = $db->prepare($query)) {
        $stmt->execute();
        $stmt->bind_result($total);
        $stmt->fetch();
        $stmt->close();
	}
	
/*$query = "SELECT o.`ID`,o.`Address`,TIME(o.`StartTime`) AS StartTime,TIME(o.`EndTime`) AS EndTime,o.`UnloadTime`,o.`GeoX`,o.`GeoY`,DATE(`DeliveryDate`) DATE,o.`LinkedAddress`,o.`Priority`,o.`Name`,o.`ClientCode`
FROM `tms_impexp_ordersource` o
INNER JOIN `tms_project` p ON p.`Project_ID`=o.`Project_ID`
WHERE p.`Client_ID` = ".$instance_id." AND p.`Project_ID` = ".$project." AND `LinkedOrderID` IS NULL LIMIT ".abs($start).",".($limit).";";
*/
$query="SELECT i.`ID`,i.`Address`,TIME(i.`StartTime`) AS StartTime,TIME(i.`EndTime`) AS EndTime,i.`UnloadTime`,i.`GeoX`,i.`GeoY`,DATE(`DeliveryDate`) DATE,i.`LinkedAddress`,i.`Priority`,i.`Name`,i.`ClientCode` FROM `tms_impexp_ordersource` i
LEFT JOIN `tms_order` o ON i.`LinkedOrderID` = o.`Order_ID`
WHERE i.`Project_ID` = ".$project."
AND o.`Order_ID` IS NULL;";

		if( $stmt = $db->prepare($query) ){
		if( $stmt->execute() ){
		$stmt->bind_result($ID,$Address,$StartTime,$EndTime,$UnloadTime,$GeoX,$GeoY,$DeliveryDate,$LinkedAddress,$Priority,$Name,$ClientCode);
		while ($stmt->fetch()) {
			$data[] = array(
				'Order_ID'=>$ID,
				'OriginalAddress'=>$Address,
				'StartTime'=>$StartTime,
				'EndTime'=>$EndTime,
				'LoadUnloadTime'=>$UnloadTime,
				'IsInTrip'=>'',
				'GeoX'=>$GeoX,
				'GeoY'=>$GeoY,
				'Date'=>$DeliveryDate,
				'LinkAddress'=>$LinkedAddress,
				'Priority'=>$Priority,
				'Name'=>$Name,
				'Code'=>$ClientCode
			);
		}
		$stmt->close();
		}
		}
	
	echo '{"total":"'.$total.'","rows":'.json_encode($data).'}';
	
	$db->close();
	exit;
}

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


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