<?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 "testAPICompanyLast.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, 'COMPANIES');

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;
	$error_num = 0;
	$result = 0;
	$message = "";
    foreach ($logistic->TRANSPORT_COMPANI as $trans_comp) {
    	$code = (string) $trans_comp->TRANSPORT_COMPANI_CODE;
    	$name = (string) $trans_comp->TRANSPORT_COMPANI_NAME;
    	$short_name = (string) $trans_comp->TRANSPORT_COMPANI_SHORTNAME;
    	$comments = (string) $trans_comp->TRANSPORT_COMPANI_COMMENT;
    	$address_jur = (string) $trans_comp->TRANSPORT_COMPANI_ADDRESS;
		$filial = (string) $trans_comp->TRANSPORT_COMPANI_FILIAL;
    	$is_deleted = $trans_comp->TRANSPORT_COMPANI_IS_DELETED;

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

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

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

		if(!$short_name || trim($short_name) == "") $short_name = $name;

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

		$address_jur = clearStr($address_jur);
		if(!$address_jur || trim($address_jur) == "") $address_jur= NULL;
			
    	$query = "SELECT COUNT(*) FROM `atp_transport_companies` WHERE `outID_code` = '$code' AND `instance_id` = $instance_id";
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' isExists <> '.$query, 'COMPANIES');
		if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->bind_result($result);
				$stmt->fetch();
				$stmt->close();
			}
		
		if($is_deleted == 1 || $is_deleted == "true") {
			if($result !=0){
				$query = "DELETE FROM `atp_transport_companies` WHERE `outID_code` = '$code' AND `instance_id` = $instance_id";
				if($db->query($query))	$countDel++;
			}
			else {$countDel++;
				//$message .="Удаление не выполнено. Компания с кодом ".$code." не найдена\n";
				//$error_num++;
			}
			continue;
		}

		if ($result == 0) {
			$query = "INSERT INTO `atp_transport_companies` (`name_jur`, `short_name`, `address_jur`, `outID_code`, `instance_id`, `comments`, `filial_code`) VALUES ('$name', '$short_name', '$address_jur', '$code', $instance_id, '$comments', '$filial')";

			if($db->query($query))	$countIns++;
				else {$message .="Ошибка записи компании в БД ".$code." \n"; $error_num++;}

			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'COMPANIES');
			}
			else {
				$query = "UPDATE `atp_transport_companies` SET `name_jur` = '$name', `short_name`='$short_name', `address_jur`='$address_jur', `comments` = '$comments', `filial_code` = '$filial'  WHERE `outID_code` = '$code'  AND `instance_id` = $instance_id";
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'COMPANIES');
			if($db->query($query)) $countUpd++;
				else {$message .="Ошибка обновления компании в БД ".$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;
}

