<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
    require_once("../settings.php");
	//require_once("settings.php");
	//include_once 'TOiR_translate.php';
    require_once("ClassLibs/ClassMessageAndLogs.php");
   // $ObjLogsTOiR = new MessageAndLogs();
	
	$client_id = $_SESSION['client_id'];
	
	
//	$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 = 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" => 'Файл с заявками успешно импортирован')));
	}
	}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" => 'Файл с заявками успешно импортирован')));
	}
}


if ($_REQUEST['func'] == 'addedit_app') {
	$nameSender = $_REQUEST['nameSender'];
	$phoneNumberSender = $_REQUEST['phoneNumberSender'];
	$cityOut = $_REQUEST['cityOut'];
    $phoneNumberReceiver = $_REQUEST['phoneNumberReceiver'];
    $cityIn = $_REQUEST['cityIn'];
    $addressIn = $_REQUEST['addressIn'];
    $description = $_REQUEST['description'];
    $width = $_REQUEST['width'];
    $height = $_REQUEST['height'];
    $length = $_REQUEST['length'];
    $weight = $_REQUEST['height'];

	$project = $_REQUEST['project'];
	
	//$data[name_master] = isset($_REQUEST['status']) ? $_REQUEST['status'] : 0;
	/*foreach ($_POST as $key => $value)
	{			
		$data[$key] = $value;		
	}*/
	$logger = new MessageAndLogs();
	
	if ($_POST['id'] || $_POST['id']!="") {
		
		$query = "UPDATE application_send SET
				     `nameSender` = '$nameSender',
					 `phoneNumberSender` = '$phoneNumberSender',
					 `cityOut` =  '$cityOut',
					 `nameReceiver` = '$nameReceiver',
					 `phoneNumberReceiver` = '$phoneNumberReceiver',
					 `cityIn` =  '$cityIn',
					 `addressIn` = '$addressIn',
					 `description` = '$description',
					 `width` = $width,
					 `height` = $height,
					 `length` = $length,
					 `weight` = $weight
				WHERE idAppSend = $_POST[id]";
	} else {
		
		$query = "INSERT INTO  application_send (
					 `nameSender`,
					 `phoneNumberSender`,
					 `cityOut`,
					 `nameReceiver`,
					 `phoneNumberReceiver`,
					 `cityIn`,
					 `addressIn`,
					 `description`,
					 `width`,
					 `height`,
					 `length`,
					 `weight`
		     ) 
				VALUES (
					'$nameSender',
                    '$phoneNumberSender',
                    '$cityOut',
                    '$nameReceiver',
                    '$phoneNumberReceiver',
                    '$cityIn',
                    '$addressIn',
                    '$description',
                    $width,
                    $height,
                    $length,
                    $weight
			)";
		//$logger->WriteLogs('USER: '.$id_user.' CLIENT: '.$id_client.' QUERY: '.$query, 'saveformref_wms', 'logs');
	}
	if ($stmt = $db->prepare($query)) {
		$stmt->execute();
		$stmt->close();
	
	}
	
	
		$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",'POST_1');
		$_ORDER->appendChild($_CODE);
		$_NAME = $dom->createElement("NAME",'POST_1');
		$_ORDER->appendChild($_NAME);
		
		$_ADDRESS = $dom->createElement("ADDRESS", $addressReceiver);
		$_ORDER->appendChild($_ADDRESS);
		
		$_GeoX = $dom->createElement("GeoX", '50.3889433');
		$_ORDER->appendChild($_GeoX);
		$_GeoY = $dom->createElement("GeoY", '50.3889433');
		$_ORDER->appendChild($_GeoY);
		$_COMMENTS_ORDERS = $dom->createElement("COMMENTS_ORDERS", '');
		$_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", $nameReceiver);
		$_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('d/m/Y'));
		$_ORDER->appendChild($_DELIVERY_DATE);
		$_SHOP_WORK_TIME = $dom->createElement("SHOP_WORK_TIME", '8:00-15:00');
		$_ORDER->appendChild($_SHOP_WORK_TIME);
		$_SHOP_DINNER_TIME = $dom->createElement("SHOP_DINNER_TIME", '');
		$_ORDER->appendChild($_SHOP_DINNER_TIME);
		$_UNLOAD_TIME = $dom->createElement("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);
		
		//$_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;
			}else{
				echo (json_encode(array("success" => false, "message" => 'Ошибка импорта Файла с заявками'))); exit;
			}
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); exit;  }
	
	$db->close();
	exit;
}




