<?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 "testAPIDriversLast.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, 'DRIVERS');

/*$xml = '<DRIVERS>
	<DRIVER>
		<CODE>8427519c-eaa1-11e2-814b-0025902b1bc7</CODE>
		<NAME>Сергей</NAME>
		<SURNAME>Климов</SURNAME>
		<PATRONYMIC>Вячеславович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>554ff903-5918-11e6-81b2-0025902b1bc7</CODE>
		<NAME>Максим</NAME>
		<SURNAME>Буганов</SURNAME>
		<PATRONYMIC>Николаевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>4d61536e-7f90-11e6-81b2-0025902b1bc7</CODE>
		<NAME>Кирилл</NAME>
		<SURNAME>Цуканов</SURNAME>
		<PATRONYMIC>Сергеевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>e832ead3-7cda-11e3-87f9-0025902b1bc7</CODE>
		<NAME>Роман</NAME>
		<SURNAME>Волгин</SURNAME>
		<PATRONYMIC>Викторович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>3756646a-d2b6-11e4-8a3d-0025902b1bc7</CODE>
		<NAME>Вячеслав</NAME>
		<SURNAME>Вара</SURNAME>
		<PATRONYMIC>Анатольевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>683dcd77-f381-11e4-8a3d-0025902b1bc7</CODE>
		<NAME>Сергей</NAME>
		<SURNAME>Ракшин</SURNAME>
		<PATRONYMIC>Владимирович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>ef56094a-0829-11e5-8a3d-0025902b1bc7</CODE>
		<NAME>Ншан</NAME>
		<SURNAME>Ташчян</SURNAME>
		<PATRONYMIC>Аршакович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>fc5f5596-0a85-11e6-8dda-0025902b1bc7</CODE>
		<NAME>Алексей</NAME>
		<SURNAME>Шлапак</SURNAME>
		<PATRONYMIC>Олегович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>808f41f5-a78a-11e0-8eda-0015170f712d</CODE>
		<NAME>Сергей</NAME>
		<SURNAME>Черняков</SURNAME>
		<PATRONYMIC>Викторович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>9b4991e5-2f60-11e5-91f2-0025902b1bc7</CODE>
		<NAME>Евгений</NAME>
		<SURNAME>Карнович</SURNAME>
		<PATRONYMIC>Владимирович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>6aa51e8c-54fa-11e5-9752-0025902b1bc7</CODE>
		<NAME>Дмитрий</NAME>
		<SURNAME>Поступной</SURNAME>
		<PATRONYMIC>Викторович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>b7a0dc7b-2855-11e0-a77f-00e081b0c21d</CODE>
		<NAME>Алексей</NAME>
		<SURNAME>Денисенко</SURNAME>
		<PATRONYMIC>Витальевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>d657e809-2855-11e0-a77f-00e081b0c21d</CODE>
		<NAME>Евгений</NAME>
		<SURNAME>Рябцев</SURNAME>
		<PATRONYMIC>Александрович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>ef4bc94a-508e-11e1-ab5e-0015170f712d</CODE>
		<NAME>Дмитрий</NAME>
		<SURNAME>Газизов</SURNAME>
		<PATRONYMIC>Андреевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>ef4bc94c-508e-11e1-ab5e-0015170f712d</CODE>
		<NAME>Александр</NAME>
		<SURNAME>Иванов</SURNAME>
		<PATRONYMIC>Андреевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>0816fe2d-f5a3-11e3-aba6-0025902b1bc7</CODE>
		<NAME>Александр</NAME>
		<SURNAME>Комков</SURNAME>
		<PATRONYMIC>Викторович</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>1987b6de-a9f9-11e5-bedd-0025902b1bc7</CODE>
		<NAME>Сергей</NAME>
		<SURNAME>Забелин</SURNAME>
		<PATRONYMIC>Николаевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
	<DRIVER>
		<CODE>cd2e9785-d502-11e5-bedd-0025902b1bc7</CODE>
		<NAME>Андрей</NAME>
		<SURNAME>Киселев</SURNAME>
		<PATRONYMIC>Васильевич</PATRONYMIC>
		<FILIAL_CODE>52f3747e-601f-47f0-a598-7560ae002eb1</FILIAL_CODE>
		<DRIVER_IS_DELETED>false</DRIVER_IS_DELETED>
	</DRIVER>
</DRIVERS>';
*/
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;
	$resultEmpl = 0;
	$error_num = 0;
	$message = "";
    foreach ($logistic->DRIVER as $driver) {
    	$code = (string) $driver->CODE;
    	$surname = (string) $driver->SURNAME;
    	$name = (string) $driver->NAME;
    	$patronymic = (string) $driver->PATRONYMIC;
    	$phone = (string) $driver->PHONE;
    	$inn_code = (string) $driver->INN_CODE;
    	$address = (string)$driver->ADDRESS;
    	$birthday = (string)$driver->BIRTHDAY;
    	$sex = (string)$driver->SEX;
    	$topical = (integer)$driver->TOPICAL;
    	$employment_type = (integer)$driver->EMPLOYMENT_TYPE;
    	$employment_date = $driver->EMPLOYMENT_DATE;
    	$dismissal_date = $driver->DISMISSAL_DATE;
    	$position_id = (integer)$driver->POSITION_ID;
    	$division_id = (integer)$driver->DIVISION_ID;
    	$filial_code = (string)$driver->FILIAL_CODE;
    	$is_deleted = $driver->DRIVER_IS_DELETED;

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

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

		if(!$surname || trim($surname) == "") $name = $surname." ".$name;

		if(!$patronymic || trim($patronymic) == "") $name = $name." ".$patronymic;

		if(!$employment_type || trim($employment_type) == "") $employment_type = 1;

		if(!$employment_date || trim($employment_date) == "") $employment_date = "0001-01-01";
		
		if(!$dismissal_date || trim($dismissal_date) == "") $dismissal_date = "0001-01-01";
			
		if(!$division_id || trim($division_id) == "") $division_id = 1;
			
		if(!$phone || trim($phone) == "") $phone = NULL;

		if(!$inn_code || trim($inn_code) == "")$inn_code = NULL;
			
		if(!$birthday || trim($birthday) == "")$birthday = "0001-01-01";
			
		if(!$filial_code || trim($filial_code) == "") {
			$message .="Не указан филиал водителя п.номер ".$code." \n";
			$error_num++;
			continue;
		}
		
		if(!$sex || trim($sex) == "") $sex = NULL;
		
		$query = "SELECT `id` FROM `atp_position` WHERE `id_type_position` =$position_id LIMIT 1";
		if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->bind_result($position_id);
				$stmt->fetch();
				$stmt->close();
			}
		if(!$position_id) $position_id = -1;

    	$query = "SELECT COUNT(*) FROM `wm_drivers` WHERE `Code` = '$code' AND `client_id` = $instance_id";
    		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 `wm_drivers` WHERE `Code` = '$code' AND `client_id` = $instance_id";
				if($db->query($query))	$countDel++;
					writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update_employee<> '.$query, 'DRIVERS');
			}
			else {$countDel++;
				//$message .="Удаление не выполнено. Водителя с кодом ".$code." не найдено\n";
			}
			continue;
		}

		/****************************Проверка на наличие сотрудника**************************/
		$query = "SELECT COUNT(*) FROM `tms_employee` WHERE `Code` = '$code'";
    		if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->bind_result($resultEmpl);
				$stmt->fetch();
				$stmt->close();
			}

		/******************************Запись данных водителя******************************/

		if ($result == 0) {
			$query = "INSERT INTO `wm_drivers` (`client_id`,`name`,`patronymic`,`surname`,`tel_number`,`Code`) VALUES ($instance_id, '$name', '$patronymic','$surname', '$phone', '$code')";

			if($db->query($query))	$countIns++;
				else {$message .="Ошибка записи водителя в БД ".$code." \n"; $error_num++;}
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' insert<> '.$query, 'DRIVERS');
			/****************************Проверка на наличие сотрудника**************************/
					$query = "SELECT COUNT(*) FROM `tms_employee` WHERE `Code` = '$code'";
			    		if ($stmt = $db->prepare($query)) {
							$stmt->execute();
							$stmt->bind_result($resultEmpl);
							$stmt->fetch();
							$stmt->close();
						}
			/*********************************Обновление базы сотрудников***************************************/
			if($resultEmpl !=0){
				/*
				$query = "UPDATE `tms_employee` 
						SET 
							`last_name`='$patronymic',
							`middle_name`='$surname',
							`inn`='$inn_code',
							`address`='$address',
							`phone`='$phone',
							`birthday`='$birthday',
							`sex`='$sex',
							`topical`='$topical',
							`id_employment_type`='$employment_type',
							`id_division`=$division_id,
							`Position_ID`=$position_id,
							`employment_date`='$employment_date',
							`date_of_dismissal`='$dismissal_date',
							`Organization_ID` = '$filial_code',
							`instance_id` = $instance_id
						WHERE 
							`Code`='$code'";
				*/
				$query = "UPDATE `tms_employee` 
						SET 
							`Name`='$name',
							`Phone`='$phone',
							`instanceID` = $instance_id
						WHERE 
							`Code`='$code'";
							
						if($db->query($query)) $countUpd++;
							else {$message .="Ошибка обновления сотрудника в БД ".$code." \n"; $error_num++;}
						writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update_employee<> '.$query, 'DRIVERS');
				}
				else {
					$message .="Водителя с кодом ".$code."  в базе сотрудников не найдено\n";
					}
				continue;
				/******************************************************************************************/
			}
			else {
				$query = "UPDATE `wm_drivers` SET `client_id` = $instance_id, `name`='$name', `patronymic`='$patronymic', `surname`='$surname', `tel_number`= '$phone', `Code`= '$code' WHERE `Code` = '$code'  AND `client_id` = $instance_id";
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update <> '.$query, 'DRIVERS');
			if($db->query($query)){ //$countUpd++;
			}else {$message .="Ошибка обновления водителя в БД ".$code." \n"; $error_num++;}
			/****************************Проверка на наличие сотрудника**************************/
					$query = "SELECT COUNT(*) FROM `tms_employee` WHERE `Code` = '$code'";
			    		if ($stmt = $db->prepare($query)) {
							$stmt->execute();
							$stmt->bind_result($resultEmpl);
							$stmt->fetch();
							$stmt->close();
						}
			/*********************************Обновление базы сотрудников***************************************/
			if($resultEmpl !=0){
				/*
				$query = "UPDATE `tms_employee` 
						SET 
							`last_name`='$patronymic',
							`middle_name`='$surname',
							`inn`='$inn_code',
							`address`='$address',
							`phone`='$phone',
							`birthday`='$birthday',
							`sex`='$sex',
							`topical`='$topical',
							`id_employment_type`='$employment_type',
							`id_division`=$division_id,
							`Position_ID`=$position_id,
							`employment_date`='$employment_date',
							`date_of_dismissal`='$dismissal_date',
							`Organization_ID` = '$filial_code',
							`instance_id` = $instance_id
						WHERE 
							`Code`='$code'";
				*/
				$query = "UPDATE `tms_employee` 
						SET 
							`Name`='$name',
							`Phone`='$phone',
							`instanceID` = $instance_id
						WHERE 
							`Code`='$code'";
							
						if($db->query($query)){ $countUpd++;
						}else{$message .="Ошибка обновления сотрудника в БД ".$code." \n"; $error_num++;}
						writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' update_employee<> '.$query, 'DRIVERS');
				}
				else {
					$message .="Водителя с кодом ".$code."  в базе сотрудников не найдено\n";
					}
				continue;
				/******************************************************************************************/
		}
	}
    
		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;
}

