<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
	
	//set_time_limit(900);
	
    //require_once("../settings.php");
	//require_once("settings.php");
	//include_once 'TOiR_translate.php';
    //require_once("ClassLibs/ClassMessageAndLogs.php");
	$client_id = $_SESSION['client_id'];
	//include "LogistMobile_checkwebtask.php";
	
   // $ObjLogsTOiR = new MessageAndLogs();
	
$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";
}
	
	
//	$instance_id = $_SESSION['client_id'];
        //require "log.php";
        //include "../settings.php";
	//	include "writedblog.php";
		//require_once 'settings.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='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;
        }

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


$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" => true, "message" => 'Файл с заявками успешно импортирован')));
		die (json_encode(array("success" => true, "message" => $messageConfirm)));
	}
	}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" => true, "message" => 'Файл с заявками успешно импортирован')));
		die (json_encode(array("success" => true, "message" => $messageConfirm)));
	}
}

if ($_REQUEST['func'] == 'addedit_app') 
{
	
	$name = $_REQUEST['Name'];
	$code = $_REQUEST['Code'];
	if($name == "")
	{
		$name = $code;
	}
	
	$original_address = $_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'];

	$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.$client_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);
		
		//$_PRODUCTS = $dom->createElement("PRODUCTS");
		//$_ORDER = $dom -> appendChild($_PRODUCTS);
		
		
		$xml = $dom->save($filename);

			$xml = '<Data InstanceID="'.$client_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."',".$client_id.",0)";
			//echo $query;
			if ($stmt = $db->prepare($query)){
			$stmt->execute();
			$last_id = $db->insert_id;
			$stmt->close();
			//echo $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;
}




