<?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 "testAPIDivisionsLast.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, 'DIVISIONS');

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;
  	$message = "";
	$result = 0;
	foreach ($logistic->DIVISION as $division) {
    	$division_code = (string)$division->DIVISION_CODE;
		$division_name = (string) $division->DIVISION_NAME;
		$division_comment = (string) $division->DIVISION_COMMENT;

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

		if(!$division_name || trim($division_name) == "") {
			$message .="Не указано имя дивизиона с кодом ".$division_code." \n";
			$error_num++;
			continue;
		}

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

		$query = "SELECT COUNT(*) FROM `atp_divisions` WHERE `outID_code` = '$division_code' AND `instance_id` = $instance_id";
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'DIVISIONS');
		if ($stmt = $db->prepare($query)) {
			if ($stmt->execute()) {
					$stmt->bind_result($result);
					$stmt->fetch();
					$stmt->close();
			}
		}

	
		if ($result == 0) {
			$query = "INSERT INTO atp_divisions (`name`, `comment`, `outID_code`, `instance_id`) VALUES ('$division_name', '$division_comment', '$division_code', $instance_id)";
			if ($stmt = $db->query($query) ) $countIns++;
				else {$message .="Ошибка записи дивизиона в БД ".$division_code." \n"; $error_num++;}
		}
		else {
			$query = "UPDATE atp_divisions SET `name` = '$division_name', `comment` = '$division_comment' WHERE `outID_code` = '$division_code' AND `instance_id` = $instance_id";
			if ($stmt = $db->query($query) ) $countUpd++;
				else {$message .="Ошибка обновления дивизиона БД ".$division_code." \n"; $error_num++;}
		}
		
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update atp_divisions <> '.$query, 'DIVISIONS');

    foreach ($division->FILIALS as $filials) {
			foreach ($filials->FILIAL as $filial) {
    			$filial_code = (string)$filial->FILIAL_CODE;
    			$filial_name = (string)$filial->FILIAL_NAME;
    			$filial_comment = (string)$filial->FILIAL_COMMENT;
    			$filial_zone = (integer) $filial->TIME_ZONE;

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

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

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

				if(!$filial_zone) $filial_zone= 10;

    			$query = "SELECT COUNT(*) FROM `atp_organization` WHERE `outID_code` = '$filial_code' AND `instance_id` = $instance_id AND 
    			`outID_code_division` = '$division_code'";
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'DIVISIONS');
				if ($stmt = $db->prepare($query)) {
					if ($stmt->execute()) {
						$stmt->bind_result($result);
						$stmt->fetch();
						$stmt->close();
					}
				}

			if ($result == 0) {
					$query = "INSERT INTO atp_organization (`name`, `description`, `outID_code_division`, `outID_code`, `instance_id`, `time_zone`) VALUES ('$filial_name', '$filial_comment', '$division_code', '$filial_code', $instance_id, $filial_zone)";
				if ($stmt = $db->query($query) ) $countIns++;
					else {$message .="Ошибка записи в БД филиала ".$filial_code." \n"; $error_num++;}
				}
				else {
					$query = "UPDATE atp_organization SET `name` = '$filial_name', `description` = '$filial_comment', `time_zone` = $filial_zone  WHERE `outID_code` = '$filial_code' AND `instance_id` = $instance_id AND `outID_code_division` = '$division_code'";
    			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' import file_get_contents <> '.$query, 'DIVISIONS');
					if ($stmt = $db->query($query) ) $countUpd++;
						else {$message .="Ошибка обновления в БД филиала ".$filial_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;
}