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

error_reporting(0);
set_time_limit(900);


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

include "settings.php";
include "logger.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');
}

$db2 = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
$db2->query("SET CHARSET SET utf8");
$db2->query("SET NAMES 'utf8'");
if (mysqli_connect_errno()) {	
	exit('Error connecting to DB');
}

//$ObjLogsTOiR = new MessageAndLogs();

$login = $_REQUEST['login'];
$password = $_REQUEST['password'];



$json = file_get_contents('php://input');

writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' importData <> import file_get_contents <> '.$json );

foreach($_REQUEST as $key => $value) {
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' importData <> import key <> '.$_REQUEST[$key] );
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' importData <> import value <> '.$value );
}

function isValidMd5($md5)
	{
		return !empty($md5) && preg_match('/^[a-f0-9]{32}$/', $md5);
	}


function check($lid) {
	global $db;
	while (true) {
		if ($count < CHECK_TIME_OUT) {
			$query = "SELECT `in_progress` FROM `tms_web_tasks` WHERE `id` = $lid";
			//writeToLogFile($count.' '.$query);
			if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->bind_result($in_progress);
				$stmt->fetch();
				$stmt->close();
				if ($in_progress == 1) {
					return true;
				} elseif ($in_progress == -1) {
					return false;
				}
			} else {
				return false;
				//writeToLogFile($count.'Error '.$query);
			}
				
			$count++;
		} else {
			$query = "UPDATE `tms_web_tasks` SET `in_progress`=-1 WHERE `id` = ".$lid.";";
			//writeToLogFile($count.' '.$query);
			if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->close();
				return false;				
			} else {
				//writeToLogFile($count.'Error '.$query);
				return false;				
			};
		}
		sleep(1);
	}
}

function import($instance_id,$xml_post,$projectId,$start_time,$date_project,$name_project){
		global $db;	

try{			
			$elit = date('Y-m-d').'_'.mt_rand(100, 999);
			$fileName = 'ProjectImport'.time().'_'.$instance_id.'.xml';
			if( file_exists($filename) ){ unlink($filename); }
			file_put_contents(ORDER_FILE_PATH.$fileName, $xml_post);
			//writeToLogFile('File_name'.ORDER_FILE_PATH.$fileName);
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' importDataLogist <> import File_name <> '.ORDER_FILE_PATH.$fileName );
			
			if($projectId){
				//$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".$instance_id." AND DATE(`Date`)=DATE(NOW()) AND (`instance_projectID`='".$projectId."' OR `Name`='".$projectId."');";
				$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".$instance_id." AND (`instance_projectID`='".$projectId."' OR `Name`='".$projectId."') ORDER BY `Project_ID` DESC LIMIT 1;";
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' importDataLogist <> import query <> '.$query );
				$stmt = $db->prepare($query);
				$stmt->execute();
				$stmt->bind_result($Project_ID);
				if ($stmt->fetch()) {
					$projectId_ = $Project_ID;
				}
				$stmt->close();
			}
			
			if (!$projectId) {
				$projectId = 'ProjectImport'.$instance_id.'_'.time();
				if($name_project){
					$name_project = strip_tags($name_project);
					if (!get_magic_quotes_gpc()) $name_project = addslashes($name_project);
					$name_project = htmlspecialchars($name_project,ENT_NOQUOTES);
					$name_project = str_replace(array("\n","\r\n","\r"), "", $name_project);
					$ProjectName = $name_project;
				}else{
					$ProjectName = $projectId;
				}
				//$date_project = date('Y-m-d');
				$result = false;
				$xmlTask = '<Data InstanceID="'.$instance_id.'" >
				<p type="CreateProject">
				<p type="CreateProject"  ProjectName="'.$ProjectName.'" ProjectDate="'.$date_project.'"
						InstanceProjectID="'.$projectId.'" WarehouseStartTime="0001-01-01 '.$start_time.':00" />
				</p>
				</Data>';
				$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xmlTask."',".$instance_id.",0)";
				writeToLogFile(' ---> '.date('Y-m-d H:i:s').' importDataLogist <> Insert webTask create project '.$query);

				if ($stmt = $db->prepare($query)) {
					$stmt->execute();
					$last_id = $db->insert_id;
					$stmt->close();
					$result = check($last_id);
				}
				if (!$result) {
					$message = "Ошибка создания проекта на $date_project";
					return false;
				}
				 
				//$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".$instance_id." AND DATE(`Date`)=DATE(NOW()) AND `instance_projectID`='".$projectId."';";
				$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".$instance_id." AND (`instance_projectID`='".$projectId."' OR `Name`='".$projectId."') ORDER BY `Project_ID` DESC LIMIT 1;";
				writeToLogFile(' ---> '.date('Y-m-d H:i:s').' importDataLogist <> Select task after Insert  '.$query);
				$stmt = $db->prepare($query);
				$stmt->execute();
				$stmt->bind_result($Project_ID);
				if ($stmt->fetch()) {
					$projectId_ = $Project_ID;
				}
				$stmt->close();
			}
			
			//import orders
			if($projectId_){
				
			$xmlTask = '<Data InstanceID="'.$instance_id.'" >
			<p type="ImportDataXML">
			<p type="ImportDataXML"  ProjectID="'.$projectId_.'" dir="'.ORDER_FILE_PATH.$fileName.'" /></p>
			</Data>';
			$result = false;
			$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xmlTask."',".$instance_id.",0)";
			writeToLogFile(' ---> '.date('Y-m-d H:i:s').' importDataLogist <> Insert web_task orders '.$query);
			if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$last_id = $db->insert_id;
				$stmt->close();
				$result = check($last_id);
			}
			if (!$result) {			
				return false;
			}
			
			writeToLogFile(' ---> '.date('Y-m-d H:i:s').' importDataLogist <> return projectId '.$projectId);
			return $projectId;
			
			}else{
				return false;
			}
			
	}catch(Exception $e){
		echo '<?xml version="1.0" encoding="utf-8"?><RESULT>'.$e->getMessage().'</RESULT>';
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> import exeption '.$e->getMessage() );
		return false;
	}
	
}

if(isset($_REQUEST['login']) && isset($_REQUEST['password'])){
	
	$login = $_REQUEST['login'];
	$password = $_REQUEST['password'];
	
	//$query = "SELECT client_id FROM `wm_users` WHERE `login` = '".$login."' AND `password` = '".md5($password)."';";
	$query = "SELECT u.client_id,c.`is_blocked` FROM `wm_users` u INNER JOIN `wm_clients` c ON u.`client_id` = c.`id` WHERE `login` = '".$login."' AND `password` = '".md5($password)."';";
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> login '.$query );
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($client_id,$blocked);
		$stmt->store_result();
		if($stmt->num_rows()>0){
			$stmt->fetch();
			
			if($blocked==1){ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Пользователь с таким логином заблокирован</RESULT>'; exit; }
			
		}else{
			//echo 'Авторизация не прошла, проверьте логин и пароль'; exit;
			echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Авторизация не прошла, проверьте логин и пароль</RESULT>'; exit;
		}
	$stmt->close();
	
	
	
		session_start();			
		$idSession = session_id();
		$query = "INSERT INTO tms_soap_session_id (`session_id`,`instance_id`) VALUES ('".$idSession."',".$client_id.")";
		writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> tms_soap_session_id '.$query );
		$db->query($query);
		//echo $idSession; exit;
		echo '<?xml version="1.0" encoding="utf-8"?><RESULT>'.$idSession.'</RESULT>'; exit;
		
	}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка выполнения</RESULT>'; exit; }
	}else{ 	echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка выполнения</RESULT>'; exit; }

}elseif(isset($_REQUEST['key'])){
	
	if( isValidMd5($_REQUEST['key']) ){
	
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> _REQUEST  key '.$_REQUEST['key'] );
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> _GET  xml '.$_GET['xml'] );
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> _POST  xml '.$_POST['xml'] );
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> _REQUEST  project '.$_REQUEST['project'] );
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> _REQUEST  time '.$_REQUEST['time'] );
	
	/*function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
	}*/
	
	//header('Content-Encoding: gzip');
	//$opts = array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0'));
	//$context = stream_context_create($opts);
	//$data = file_get_contents('php://input', false, $context);
	
	//$data = file_get_contents('php://input');
	//$data = mb_convert_encoding($data, 'HTML-ENTITIES', "UTF-8");
	//$data = str_replace('&#65279;', '', $data);
	//writeToLogFile( ' -> '.date('Y-m-d H:i:s').' importDataLogist <> file_get_contents <> '.$data );
	//$xml_post = trim($data);
	
	
	//if(isset($_POST['xml'])){
	
	$key = $_REQUEST['key'];
	//$xml_post = $_REQUEST['xml'];
	$xml_post = $_REQUEST['xml'];
	$xml_post = trim(stripcslashes($xml_post));
	
	
	
	if(!isset( $_REQUEST['project'] ) || $_REQUEST['project']==""){
		$project_id = false;
	}else{
		$project_id = $_REQUEST['project'];
		$project_id = trim(rtrim($project_id));
	}
	
	if(!isset( $_REQUEST['time'] ) || $_REQUEST['time']==""){
		$start_time = '09:00';
	}else{ $start_time = $_REQUEST['time']; }
	
	
	if(!isset( $_REQUEST['date_project'] ) || $_REQUEST['date_project']==""){
		$date_project = date('Y-m-d');
	}else{
		//if( (bool)strtotime($_REQUEST['date_project']) ){
			$date_project = $_REQUEST['date_project'];
		//}else{
		//	echo '<RESULT>Проверьте дату проекта</RESULT>'; exit;
		//}
	}
	
	if( !isset( $_REQUEST['name_project'] ) || $_REQUEST['name_project']=="" ){
		$name_project = null;
	}else{
		$name_project = $_REQUEST['name_project'];
	}
	
	
	if(!isset($xml_post) || $xml_post==""){
		$xml_post = $json;
		$xml_post = str_replace('&#65279;', '', $xml_post);
		$xml_post = str_replace('&amp;#045;', '-', $xml_post);
	}
	
	
	
	if($xml_post || $xml_post!=""){
	

	
	$query = "SELECT instance_id FROM `tms_soap_session_id` WHERE TIME>=SUBTIME(NOW(), '0".SESSION_TIME_OUT.":00:00') AND `session_id`='".$key."' ORDER BY `time` DESC LIMIT 1";
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> key tms_soap_session_id '.$query );
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($instance_id);
		$stmt->store_result();
		if($stmt->num_rows()>0){
			$stmt->fetch();
			writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> call import' );
			$xml = import($instance_id,$xml_post,$project_id,$start_time,$date_project,$name_project);
			if($xml){
				echo '<?xml version="1.0" encoding="utf-8"?><RESULT>'.$xml.'</RESULT>';
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> <RESULT>'.$xml.'</RESULT>' );
				exit;
			}else{
				echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка импорта</RESULT>';
				writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> importDataLogist <> <RESULT>Ошибка импорта</RESULT>' );
				exit;
			}
		}else{
			//echo 'Доступ закрыт. Авторизируйтесь'; exit;
			echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Доступ закрыт. Авторизируйтесь</RESULT>'; exit;
		}
	}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка выполнения</RESULT>'; exit; }
	}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка выполнения</RESULT>'; exit; }
	
	}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка, XML не может быть пустым</RESULT>'; exit; }
	/*}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Ошибка, XML не может быть пустым в POST запросе</RESULT>'; exit; }*/
	
	}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>EMPTY KEY</RESULT>'; exit; }
}else{ echo '<?xml version="1.0" encoding="utf-8"?><RESULT>EMPTY REQUEST</RESULT>'; exit; }

