<?php
//header('Content-Type: text/html; charset=utf-8');
header("Content-Type: application/xml; charset=utf-8");
set_time_limit(120);

define('PATH_TO_SERVISE', '/app/Logist/files/');
define('ORDER_FILE_PATH', $_SERVER['DOCUMENT_ROOT'].PATH_TO_SERVISE);
define('CHECK_TIME_OUT', 120);
define('SESSION_TIME_OUT', 2);

include "../settings.php";
include "logger.php";
include "importAPIFunction.php";
//include "testAPIWarehousesLast.php";

$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()) {
	exit('Error connecting to DB');
}

$xml = file_get_contents('php://input');
writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$xml, 'WAREHOUSE');

if(isset($_REQUEST['key'])){
	
	// проверка ключа сесии
	$check_key_result = check_key($_REQUEST['key']);
	if(!$check_key_result && $check_key_result == ""){
	
	// выборка instance_id клиента по ключу сесии
	$instance_id = get_instanceid($_REQUEST['key']);

	//$instance_id = 92;
	if($instance_id){
	
	// проверка валидности хмл
	checkXML($xml);
	
	if($xml && $xml!=""){
		$xml = str_replace('&#65279;', '', $xml);
		$xml = str_replace('&amp;#045;', '-', $xml);

  $logistic = new SimpleXMLElement($xml);

  	$countIns = 0;
  	$countUpd = 0;
  	$countDel = 0;
	$result = 0;
	$error_num = 0;
	$message="";

    foreach ($logistic->WAREHOUSE as $value) {
    	$WAREHOUSE_CODE = $value->WAREHOUSE_CODE;
		$WAREHOUSE_NAME = $value->WAREHOUSE_NAME;
		$FILIAL_CODE = $value->FILIAL_CODE;
		$WAREHOUSE_ADDRESS = $value->WAREHOUSE_ADDRESS;
		$WAREHOUSE_GEOX = $value->WAREHOUSE_GEOX;
		$WAREHOUSE_GEOY = $value->WAREHOUSE_GEOY;
		$WAREHOUSE_WORK_TIME = $value->WAREHOUSE_WORK_TIME;
		
		if( !isset($WAREHOUSE_WORK_TIME) || $WAREHOUSE_WORK_TIME=="" ){
			$WAREHOUSE_WORK_TIME = array('09:00','18:00');
		}else{
			$WAREHOUSE_WORK_TIME = explode('-',$WAREHOUSE_WORK_TIME);
		}
		
		$WAREHOUSE_LOADING_TYPE = $value->WAREHOUSE_LOADING_TYPE;
		$WAREHOUSE_IS_DELETED = $value->WAREHOUSE_IS_DELETED;
		if(!$WAREHOUSE_IS_DELETED || trim($WAREHOUSE_IS_DELETED) == "") $WAREHOUSE_IS_DELETED = 0;
	   if($WAREHOUSE_IS_DELETED=="true") $WAREHOUSE_IS_DELETED = 1;
	   if($WAREHOUSE_IS_DELETED=="false") $WAREHOUSE_IS_DELETED = 0;

		if(!$WAREHOUSE_CODE || trim($WAREHOUSE_CODE) == "") {
			$message .="Не указан код склада \n";
			$error_num++;
			continue;
		}

		if(!$WAREHOUSE_NAME || trim($WAREHOUSE_NAME) == "") {
			$message .="Не указано имя склада с кодом ".$WAREHOUSE_CODE." \n";
			$error_num++;
			continue;
		}
		if(!$FILIAL_CODE || trim($FILIAL_CODE) == "") {
			$message .="Не указан код филиала склада с кодом ".$WAREHOUSE_CODE." \n";
			$error_num++;
			continue;
		}
		if(!$WAREHOUSE_ADDRESS || trim($WAREHOUSE_ADDRESS) == "") {
			$message .="Не указан адрес склада с кодом ".$WAREHOUSE_CODE." \n";
			$error_num++;
			continue;
		}
		if(!$WAREHOUSE_GEOX || trim($WAREHOUSE_GEOX) == "") $WAREHOUSE_GEOX = '0.00';

		if(!$WAREHOUSE_GEOY || trim($WAREHOUSE_GEOY) == "") $WAREHOUSE_GEOY = '0.00';

		if(!$WAREHOUSE_LOADING_TYPE || trim($WAREHOUSE_LOADING_TYPE) == "") $WAREHOUSE_LOADING_TYPE = NULL;

		$query = "SELECT COUNT(*) FROM `tms_warehouse` WHERE `Code` = '$WAREHOUSE_CODE' AND `DeletedRecord` = 0 AND `WarehouseType` = 1 AND `instanceID` = $instance_id";
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'WAREHOUSE');
		if ($stmt = $db->prepare($query)) {
		if ($stmt->execute()) {
				$stmt->bind_result($result);
				while($stmt->fetch()){}
				$stmt->close();
		}}
		
		if ($result == 0) {
			$query = "INSERT INTO `tms_warehouse` (`Code`,`Name`,`filial_code`,`Address`,`GeoX`,`GeoY`,`StartServeTime`,`EndServeTime`,`warehouse_loading_type`,`instanceID`, `WarehouseType`, `DeletedRecord`)
			VALUES ('$WAREHOUSE_CODE','$WAREHOUSE_NAME','$FILIAL_CODE','$WAREHOUSE_ADDRESS','$WAREHOUSE_GEOX','$WAREHOUSE_GEOY','0001-01-01 $WAREHOUSE_WORK_TIME[0]','0001-01-01 $WAREHOUSE_WORK_TIME[1]','$WAREHOUSE_LOADING_TYPE',$instance_id, 1, $WAREHOUSE_IS_DELETED)";
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'WAREHOUSE');
			if ($stmt = $db->query($query) ) $countIns++;
				else {$message .="Ошибка записи склада в БД ".$WAREHOUSE_CODE." \n"; $error_num++;}
		}
		else {
			//if($WAREHOUSE_GEOX == '0.00' || $WAREHOUSE_GEOY == '0.00'){
			//	$query = "UPDATE `tms_warehouse` SET `Code`='$WAREHOUSE_CODE',`Name`='$WAREHOUSE_NAME',`filial_code`='$FILIAL_CODE',`Address`='$WAREHOUSE_ADDRESS',`StartServeTime`='0001-01-01 $WAREHOUSE_WORK_TIME[0]',`EndServeTime`='0001-01-01 $WAREHOUSE_WORK_TIME[1]',`warehouse_loading_type`='$WAREHOUSE_LOADING_TYPE',
			//	`DeletedRecord` = $WAREHOUSE_IS_DELETED WHERE `Code` = '$WAREHOUSE_CODE' AND `instanceID` = $instance_id";
			//}else{
			//	$query = "UPDATE `tms_warehouse` SET `Code`='$WAREHOUSE_CODE',`Name`='$WAREHOUSE_NAME',`filial_code`='$FILIAL_CODE',`Address`='$WAREHOUSE_ADDRESS',`GeoX`='$WAREHOUSE_GEOX',`GeoY`='$WAREHOUSE_GEOY',`StartServeTime`='0001-01-01 $WAREHOUSE_WORK_TIME[0]',`EndServeTime`='0001-01-01 $WAREHOUSE_WORK_TIME[1]',`warehouse_loading_type`='$WAREHOUSE_LOADING_TYPE',
			//	`DeletedRecord` = $WAREHOUSE_IS_DELETED WHERE `Code` = '$WAREHOUSE_CODE' AND `instanceID` = $instance_id";
			//}
			if($WAREHOUSE_GEOX == '0.00' || $WAREHOUSE_GEOY == '0.00'){
				$query = "UPDATE `tms_warehouse` SET `Code`='$WAREHOUSE_CODE',`Name`='$WAREHOUSE_NAME',`filial_code`='$FILIAL_CODE',`Address`='$WAREHOUSE_ADDRESS',`StartServeTime`='0001-01-01 00:00:00',`EndServeTime`='0001-01-01 23:00:00',`warehouse_loading_type`='$WAREHOUSE_LOADING_TYPE',
				`DeletedRecord` = $WAREHOUSE_IS_DELETED WHERE `Code` = '$WAREHOUSE_CODE' AND `instanceID` = $instance_id";
			}else{
				$query = "UPDATE `tms_warehouse` SET `Code`='$WAREHOUSE_CODE',`Name`='$WAREHOUSE_NAME',`filial_code`='$FILIAL_CODE',`Address`='$WAREHOUSE_ADDRESS',`GeoX`='$WAREHOUSE_GEOX',`GeoY`='$WAREHOUSE_GEOY',`StartServeTime`='0001-01-01 00:00:00',`EndServeTime`='0001-01-01 23:00:00',`warehouse_loading_type`='$WAREHOUSE_LOADING_TYPE',
				`DeletedRecord` = $WAREHOUSE_IS_DELETED WHERE `Code` = '$WAREHOUSE_CODE' AND `instanceID` = $instance_id";
			}
			
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'WAREHOUSE');
			if ($stmt = $db->query($query) ) $countUpd++;
				else {$message .="Ошибка обновления склада в БД ".$WAREHOUSE_CODE." \n"; $error_num++;}
		}
		
    	}
		
		result_message_xml($error_num,$message,$countIns,$countUpd,$countDel);
		
		$db->close();
		exit;
	
	
	}else{
		result_message_xml(-1,'Ошибка, XML не может быть пустым',0,0,0);
		exit;
	}
	
	}else{
		result_message_xml(-1,'Доступ закрыт. Авторизируйтесь',0,0,0);
		exit;
	}
	
	}else{ 	echo $check_key_result; exit; }
	
}else{
	result_message_xml(-1,'Доступ закрыт. Авторизируйтесь',0,0,0);
	exit;
}

