<?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 "testAPIClientsLast.php";
//include "testAPIClients310816.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');

/*$xml = '<CLIENTS>
		<CLIENT>
		<CODE>91627d2d-a2f0-11e0-9de3-000423be2930</CODE>
		<CLIENT_IS_DELETED>false</CLIENT_IS_DELETED>
		<MAIN>
			<INN_CODE>6501154884</INN_CODE>
			<KPP_CODE>650101001</KPP_CODE>
			<CLIENT_NAME>Форум  Бокс</CLIENT_NAME>
			<CLIENT_PHONE>4242 -752020</CLIENT_PHONE>
			<ADDRESS>_</ADDRESS>
			<CLIENT_CATEGORY>1</CLIENT_CATEGORY>
		</MAIN>
		<CONTACTS/>
		<CONTRACTS/>
		<BANK_ACCOUNTS/>
		<SHOPS>
			<SHOP>
				<SHOP_CODE>7b2324ad-c79a-11e0-893e-000423be2931</SHOP_CODE>
				<SHOP_TK>9defb958-ced8-11e1-ad2c-0025902b1bc7</SHOP_TK>
				<SHOP_NAME>ООО "Форум" м-н"Форум"</SHOP_NAME>
				<SHOP_ADDRESS>"693000"&amp;"Сахалинская обл"&amp;""&amp;"Южно-Сахалинск г"&amp;""&amp;"Пуркаева М.А. ул"&amp;"106в"&amp;""&amp;""</SHOP_ADDRESS>
				<SHOP_WORK_TIME>01.01.0001 9:00:00-01.01.0001 20:00:00</SHOP_WORK_TIME>
				<SHOP_DINNER_TIME>01.01.0001 0:00:00-01.01.0001 0:00:00</SHOP_DINNER_TIME>
				<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
				<SHOP_IS_DELETED>false</SHOP_IS_DELETED>
			</SHOP>
			<SHOP>
				<SHOP_CODE>7b2324ae-c79a-11e0-893e-000423be2931</SHOP_CODE>
				<SHOP_TK>00000000-0000-0000-0000-000000000000</SHOP_TK>
				<SHOP_NAME>ООО "Форум" м-н"Форум-2"</SHOP_NAME>
				<SHOP_ADDRESS>"693004"&amp;"Сахалинская обл"&amp;""&amp;"Южно-Сахалинск г"&amp;""&amp;"Пуркаева М.А. ул"&amp;"61"&amp;""&amp;""</SHOP_ADDRESS>
				<SHOP_WORK_TIME>01.01.0001 9:00:00-01.01.0001 18:00:00</SHOP_WORK_TIME>
				<SHOP_DINNER_TIME>01.01.0001 0:00:00-01.01.0001 0:00:00</SHOP_DINNER_TIME>
				<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
				<SHOP_IS_DELETED>false</SHOP_IS_DELETED>
			</SHOP>
			<SHOP>
				<SHOP_CODE>b9eb6817-cdc5-11e4-8a3d-0025902b1bc7</SHOP_CODE>
				<SHOP_TK>9defb958-ced8-11e1-ad2c-0025902b1bc7</SHOP_TK>
				<SHOP_NAME>ООО "Форум" м-н"Форум"</SHOP_NAME>
				<SHOP_ADDRESS/>
				<SHOP_WORK_TIME>01.01.0001 9:00:00-01.01.0001 20:00:00</SHOP_WORK_TIME>
				<SHOP_DINNER_TIME>01.01.0001 0:00:00-01.01.0001 0:00:00</SHOP_DINNER_TIME>
				<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
				<SHOP_IS_DELETED>false</SHOP_IS_DELETED>
			</SHOP>
		</SHOPS>
	</CLIENT></CLIENTS>';*/
	
writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$xml, 'CLIENTS');

	

if(isset($_REQUEST['key'])){
	
	try{
	// проверка ключа сесии
	$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 = "";
	$contact_person = "";
	$contract = "";
	$WarehouseType = 2;
	$UseLeaseCar = 1;
	$GeoX = '0.00';
	$GeoY = '0.00';
	$banc_acc = "";
	$resultShop = 0;
	$picture_id =1;
	$selectedpicture_id = 1;

	//print_r($logistic);
	
   foreach ($logistic->CLIENT as $client) {
	   
	   writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' foreach <> '.$client->CODE, 'CLIENTS');
	   
	   $external_id = (string)$client->CODE;
	   $is_deleted = $client->CLIENT_IS_DELETED;
	   if(!$is_deleted || trim($is_deleted) == "") $is_deleted = 0;
	   if($is_deleted=="true") $is_deleted = 1;
	   if($is_deleted=="false") $is_deleted = 0;
	   
   		foreach ($client->MAIN as $main) {
   			
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' foreach <> '.$main->INN_CODE, 'CLIENTS');
			
			$inn_code = (string)$main->INN_CODE;
			$kpp_code = (string)$main->KPP_CODE;
			$client_name = (string)$main->CLIENT_NAME;
			$address = (string) $main->ADDRESS;
			$client_phone = (string)$main->CLIENT_PHONE;
			$client_category = (integer)$main->CLIENT_CATEGORY;
			$Client_ID = "";

			/**************************Проверка на наличие данных********************************/
			if(!$external_id || trim($external_id) == "") {
				$message .="Не указан код \n";
				$error_num++;
				continue;
			}
			
			if(!$inn_code || trim($inn_code) == "") $inn_code = NULL;
			
			if(!$kpp_code || trim($kpp_code) == "") $kpp_code = NULL;
				
			if(!$client_name || trim($client_name) == "") {
				$message .="Не указано имя контрагента ".$external_id." \n";
				$error_num++;
				continue;
			}
			if(!$address || trim($address) == "") $address = NULL;

			if(!$client_phone || trim($client_phone) == "") $client_phone = NULL;
				
			if(!$client_category || trim($client_category) == "")$client_category=1;

			/*******************************Проверяем наличие клиента в БД*********************************/
			$query = "SELECT COUNT(*) FROM `tms_client` WHERE `Code` = '$external_id' AND `instance_id` = $instance_id";
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' checkClient isExists <> '.$query, 'CLIENTS');
			if ($stmt = $db->prepare($query)) {
				if ($stmt->execute()) {
						$stmt->bind_result($result);
						while($stmt->fetch()){}
						$stmt->close();
				}
			}
			
	   		/********************************Контактные лица**********************************/
	   		$contact_person = "";
			foreach ($client->CONTACTS->CONTACT as $contact) {
	   			$contact_name = (string) $contact->CONTACT_NAME;
	   			$contact_phone = (string) $contact->CONTACT_PHONE;
	   			$contact_comment = (string) $contact->CONTACT_COMMENT;

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

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

	   			$contact_person .= $contact_name." ".$contact_phone." ".$contact_comment;
	   		}

	   		/*****************************************Контракты************************************/
			$contract = "";
	   		foreach ($client->CONTRACTS->CONTRACT as $contract) {
	   			$contract_code = (string) $contract->CONTRACT_CODE;
	   			$contract_comment = (string) $contract->CONTRACT_COMMENT;

	   			if(!$contract_code || trim($contract_code) == "") $contract_code= NULL;
				if(!$contract_comment || trim($contract_comment) == "") $contract_comment= NULL;

	   			$contract .= $contract_code." ".$contract_comment;
	   		}

	   		/**************************************Банковские счета*************************************/
				$banc_acc = "";
	   			foreach ($client->BANK_ACCOUNTS->BANK_ACCOUNT as $banc_acc) {
	   			$banc_acc_code = (string) $banc_acc->BANK_ACCOUNT_CODE;
	   			$banc_acc_comment = (string) $banc_acc->BANK_ACCOUNT_COMMENT;

	   			if(!$banc_acc_code || trim($banc_acc_code) == "") $banc_acc_code= NULL;
					
				if(!$banc_acc_comment || trim($banc_acc_comment) == "") $banc_acc_comment= NULL;

	   			$banc_acc .= $banc_acc_code." ".$banc_acc_comment;
	   		}

	   	/************************************Запись в БД данных клиента ************************************/
		if ($result == 0) {
				
				$query = "INSERT INTO `tms_client` (`Code`, `kpp_code`, `name`, `Address`, `Phone`, `ContactPerson`, `UseLeaseCar`, `CustomText1`, `CustomText2`, `CategoryID`, `instance_id`, `DeletedRecord`, `CustomText3`) VALUES ('$external_id', '$kpp_code', '$client_name', '$address', '$client_phone', '$contact_person', $UseLeaseCar, '$contract', '$banc_acc', '$client_category', $instance_id, $is_deleted, '$inn_code')";
				if ($stmt = $db->query($query) ) {$countIns++;}
					else {$message .="Ошибка записи клиента в БД ".$external_id." \n"; $error_num++;}

			}
			else {
				
				$query = "UPDATE `tms_client` SET `ContactPerson`='$contact_person', `kpp_code` = '$kpp_code', `name` = '$client_name', `Address`= '".$address."', `Phone`= '$client_phone', `UseLeaseCar` = $UseLeaseCar, `CustomText1` = '$contract', `CustomText2`='$banc_acc', `CategoryID` = '$client_category', `DeletedRecord`=$is_deleted, `CustomText3` = '$inn_code' WHERE `Code`='$external_id' AND `instance_id` = $instance_id";
				if ($stmt = $db->query($query) ) $countUpd++;
					else {$message .="Ошибка обновления клиента в БД ".$external_id." \n"; $error_num++;}
			}
			
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update/insert tms_client <> '.$query, 'CLIENTS');

			$query = "SELECT `Client_ID` FROM `tms_client` WHERE `Code` = '$external_id' AND `instance_id` = $instance_id";
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update/insert tms_client <> '.$query, 'CLIENTS');
				if ($stmt = $db->prepare($query)) {
						if ($stmt->execute()) {
								$stmt->bind_result($Client_ID);
								while($stmt->fetch()){}
								$stmt->close();
						}
					}

	   		/*****************************************Магазины***************************************/
	   			foreach ($client->SHOPS->SHOP as $shop) {
	   			$shop_code = (string) $shop->SHOP_CODE;
	   			$shop_name = (string) $shop->SHOP_NAME;
	   			$shop_address = (string) $shop->SHOP_ADDRESS;
	   			$shop_address_add = (string) $shop->ADDRESS;
				$shop_address = clearStr($shop_address);
				$shop_address_add = clearStr($shop_address_add);
	   			if ($shop_address_add || trim($shop_address_add) != "") $shop_address .=" (".$shop_address_add.")";
	
	   			$shop_work_time = (string)$shop->SHOP_WORK_TIME;
	   			$shop_work_time = explode('-', $shop_work_time);
	   			$shop_work_time[0] = substr(trim($shop_work_time[0]), 10);
	   			$shop_work_time[1] = substr(trim($shop_work_time[1]), 10);
	   			$shop_dinn_time = (string)$shop->SHOP_DINNER_TIME;
	   			$shop_dinn_time = explode('-', $shop_dinn_time);
	   			$shop_dinn_time[0] = substr(trim($shop_dinn_time[0]), 10);
	   			$shop_dinn_time[1] = substr(trim($shop_dinn_time[1]), 10);
	   			
	   			$shop_filial_code = (string) $shop->FILIAL_CODE;
	   			$shop_is_deleted = $shop->SHOP_IS_DELETED;
				if(!$shop_is_deleted || trim($shop_is_deleted) == "") $shop_is_deleted = 0;
				if($shop_is_deleted=="true") $shop_is_deleted = 1;
				if($shop_is_deleted=="false") $shop_is_deleted = 0;
				if ($is_deleted == 1) $shop_is_deleted = 1;
				$sec_type = 0;
				
				$shop_tk = (string) $shop->SHOP_TK;
				//********************************** SHOP_TK
				if($shop_tk == '00000000-0000-0000-0000-000000000000' || trim($shop_tk) == "" || !$shop_tk){
					
				}else{
					$address_jur = "";
					$query = "SELECT `address_jur` FROM `atp_transport_companies` WHERE `outID_code` = '".$shop_tk."';";
					writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' checkClient isExists <> '.$query, 'CLIENTS');
					if ($stmt = $db->prepare($query)) {
						if ($stmt->execute()) {
							$stmt->bind_result($address_jur);
							while($stmt->fetch()){
								$shop_address = clearStr($address_jur);
								//$shop_code = $shop_tk;
								$sec_type = 1;
							}
							$stmt->close();
						}
					}
				}
				
	   			/**************************Проверка  полноты данных*******************************/

	   			if(!$shop_code || trim($shop_code) == "") {
					$message .="Не указан код магазина у контрагента  ".$external_id." \n";
					$error_num++;
					continue;
				}

				if(!$shop_name || trim($shop_name) == "") $shop_name = $client_name;

				if(!$shop_address || trim($shop_address) == ""){
					$message .="Не указан адрес магазина у контрагента  ".$external_id." \n";
					$error_num++;
					continue;
				}

				if(!$shop_filial_code || trim($shop_filial_code) == "") {
					$message .="Не указан код филиала магазина у контрагента  ".$external_id." \n";
					$error_num++;
					continue;
				}
				
				

	   			//**********************************Проверяем наличие магазинов******************************//
	   			$query = "SELECT COUNT(*) FROM `tms_warehouse` WHERE `Code` = '$shop_code' AND `DeletedRecord` = 0 AND `WarehouseType` = 2 AND `instanceID` = $instance_id AND `Client_ID` = $Client_ID;";
					writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' checkClient isExists <> '.$query, 'CLIENTS');
					if ($stmt = $db->prepare($query)) {
						if ($stmt->execute()) {
								$stmt->bind_result($resultShop);
								while($stmt->fetch()){}
								$stmt->close();
						}
					}
					
				

			   	//**********************Записываем или обновляем данные магазина***********************//
						if ($resultShop == 0) {
							if( $shop_is_deleted == 1 ){}
							else{
							$query = "INSERT INTO `tms_warehouse` (`Code`, `Name`, `filial_code`, `Address`, `StartServeTime`,`EndServeTime`, `StartDinner`, `EndDinner`, `WarehouseType`, `Client_ID`, `GeoX`, `GeoY`, `DeletedRecord`, `PictureID`, `SelectedPictureID`, `instanceID`, sec_type) VALUES ('$shop_code', '".addslashes($shop_name)."', '$shop_filial_code', '".addslashes($shop_address)."', '0001-01-01 $shop_work_time[0]', '0001-01-01 $shop_work_time[1]', ' 0001-01-01 $shop_dinn_time[0]', '0001-01-01 $shop_dinn_time[1]', $WarehouseType, $Client_ID, '$GeoX', '$GeoY', $shop_is_deleted, $picture_id, $selectedpicture_id, $instance_id, $sec_type)";
							writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update/insert tms_warehouse <> '.$query, 'CLIENTS');
							if ($stmt = $db->query($query) ) { //$countIns++;
							}
								else {$message .="Ошибка записи магазина в БД ".$shop_code." \n"; $error_num++;}
							}
						}
						else {
							
				if(!$shop_address || trim($shop_address) == "" || trim($shop_address) == "_"){
					$address_update = "";
				}else{
					$address_update = "`Address` = '".addslashes($shop_address)."',";
				}
				
				if($GeoX == '0.00' || $GeoY == '0.00'){
					$GeoXGeoY = "";
				}else{
					$GeoXGeoY = "`GeoX`='$GeoX', `GeoY`='$GeoY',";
				}			
							//if( $sec_type == 1 ){  $GeoXGeoY = "`GeoX`='0.00', `GeoY`='0.00',"; }
							
							$query = "UPDATE `tms_warehouse` SET `Name`= '".addslashes($shop_name)."', `filial_code` = '$shop_filial_code', ".$address_update." `StartServeTime` = '0001-01-01 $shop_work_time[0]', `EndServeTime` = '0001-01-01 $shop_work_time[1]', `StartDinner` = '0001-01-01 $shop_dinn_time[0]', `EndDinner` = '0001-01-01 $shop_dinn_time[1]', ".$GeoXGeoY." `DeletedRecord` = $shop_is_deleted, `PictureID`=$picture_id, `SelectedPictureID`=$selectedpicture_id, sec_type = $sec_type WHERE `Code` = '$shop_code' AND `instanceID` = $instance_id AND WarehouseType = $WarehouseType AND `DeletedRecord` = 0 AND `Client_ID` = $Client_ID";
							
							writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update/insert tms_warehouse <> '.$query, 'CLIENTS');
							if ($stmt = $db->query($query) ){ //$countUpd++;
							}
								else {$message .="Ошибка обновления магазина в БД ".$shop_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; }
	
	}catch(Exception $e){
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' Exception <> '.$e->Message, 'CLIENTS');
	}
	
	
}else{
	result_message_xml(-1,'Доступ закрыт. Авторизируйтесь',0,0,0);
	exit;
}

