<?php
require_once 'define.php';
require_once 'settings.php';

$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME,$DB_PORT);
$db->query("SET CHARSET SET utf8");
$db->query("SET NAMES 'utf8'");

class Navision {
	public $authFlag;
	public $login;
	public $password;
	public $isLogin;
	public $sessionID;
	
	public $authChek = false;
	public static $flag;	
	
	public function getTripFromTMSByTime($time) {		
			global $db;	
			if (CheckAuth::check($time->idSession)) {
				$date = date('Y-m-d', strtotime($time->time));
				$arrTripId = array();
				$query = "SELECT t.Trip_ID FROM `tms_trip` t
			INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
			WHERE p.Client_ID=".CLIENT_ID." AND t.`StartTime` >= '$time->time'
							AND t.`StartTime` <= '$date 23:59:59'";
				writeToLogFile($query);
				if ($stmt = $db->prepare($query)) {
					$stmt->execute();
					$stmt->bind_result($Trip_ID);
					while ($stmt->fetch()) {
						$arrTripId[] = $Trip_ID;
					}
					$stmt->close();
				} else {
					return new getTripFromTMSByTimeOutResponse('error');
				}
				if (count($arrTripId) > 0) {
					$xmlObj = new XMLCreator($arrTripId);
					$xml = $xmlObj->creareXML();
					return new getTripFromTMSByTimeOutResponse('success', $xml);
				} else {
					return new getTripFromTMSByTimeOutResponse('empty');
				}
			}	else {
				return new getTripFromTMSByTimeOutResponse('close');
			}
	}
	
	public function getTripFromTMSByDate($date) {		
			global $db;
			if (CheckAuth::check($date->idSession)) {
				$arrTripId = array();
				$query = "SELECT t.Trip_ID FROM `tms_trip` t
			INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
			WHERE p.Client_ID=".CLIENT_ID." AND DATE(t.`StartTime`) = '$date->date'";
				writeToLogFile($query);
				if ($stmt = $db->prepare($query)) {
					$stmt->execute();
					$stmt->bind_result($Trip_ID);
					while ($stmt->fetch()) {
						$arrTripId[] = $Trip_ID;
					}
				} else {
					return new getTripFromTMSByDateOutResponse('error');
				}
				if (count($arrTripId) > 0) {
					$xmlObj = new XMLCreator($arrTripId);
					$xml = $xmlObj->creareXML();
					return new getTripFromTMSByDateOutResponse('success', $xml);
				} else {
					return new getTripFromTMSByDateOutResponse('empty');
				}
			} else {
				return new getTripFromTMSByDateOutResponse('close');
			}
			
			
		//}
	}
	
	public function getTripFromTMSByOrderId($order) {
		if (CheckAuth::check($order->idSession)) {
			global $db;
			$tripID = array();
			$query = "SELECT tp.`Trip_ID` FROM `tms_order` o
			INNER JOIN `tms_loadunloadpoint` lp ON lp.`OrderWarehouse_ID`=o.`Order_ID`
			INNER JOIN `tms_trippoint` tp ON tp.`Point_ID`=lp.`LoadUnloadPoint_ID`
			WHERE o.`Code`='$order->orderId'";
			if ($stmt = $db->prepare($query)) {
				$stmt->execute();
				$stmt->bind_result($Trip_ID);
				if ($stmt->fetch()) {
					$tripID[] = $Trip_ID;
				}
				$stmt->close();
			} else {
				return new getTripFromTMSByOrderIdOutResponse('error');
			}
				
			if (count($tripID) > 0) {
				$xmlObj = new XMLCreator($tripID);
				$xml = $xmlObj->creareXML();
				return new getTripFromTMSByOrderIdOutResponse('success', $xml);
			} else {
				return new getTripFromTMSByOrderIdOutResponse('empty');
			}
		} else {
			return new getTripFromTMSByOrderIdOutResponse('close');
		}			
	}
	
	
	public function ping($id) {		
		if (CheckAuth::check($id->idSession)) {
			return new pingResponse();
		} else {
			return new pingResponse('close');
		}		
	}
	
	public function importRequestFromNav($xml) {
		global $db;	
		if (CheckAuth::check($xml->idSession)) {
			$projectId = false;
			$elit = date('Y-m-d').'_'.mt_rand(100, 999);
			$fileName = 'Elit_import_'.$elit.'.xml';
			file_put_contents(ORDER_FILE_PATH.$fileName, $xml->xml);
			writeToLogFile('File_name'.ORDER_FILE_PATH.$fileName);
				
			$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".CLIENT_ID."
			AND DATE(`Date`)=DATE(NOW()) AND `instance_projectID`='$xml->projectId'";
				
			writeToLogFile('Select project '.$query);
			$stmt = $db->prepare($query);
			$stmt->execute();
			$stmt->bind_result($Project_ID);
			if ($stmt->fetch()) {
				$projectId = $Project_ID;
			}
			$stmt->close();
				
			if (!$projectId) {
			
				$date_project = date('Y-m-d');
				$xmlTask = '<Data InstanceID="'.CLIENT_ID.'" >
				<p type="CreateProject">
				<p type="CreateProject"  ProjectName="'.$fileName.'" ProjectDate="'.$date_project.'"
						InstanceProjectID="'.$xml->projectId.'" />
				</p>
				</Data>';
				$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`) VALUES ('".$xmlTask."',".CLIENT_ID.")";
				writeToLogFile('Insert webTask create project '.$query);
				//echo $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 new importRequestFromNavResponse('error');
				}
				 
				$query = "SELECT `Project_ID` FROM `tms_project` WHERE `Client_ID`=".CLIENT_ID."
				AND DATE(`Date`)=DATE(NOW()) AND `instance_projectID`='$instance_projectID'";
				writeToLogFile('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
			$xmlTask = '<Data InstanceID="'.CLIENT_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`) VALUES ('".$xmlTask."',".CLIENT_ID.")";
			writeToLogFile('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 new importRequestFromNavResponse('error');
			}
			return new importRequestFromNavResponse('success');
		} else {
			return new importRequestFromNavResponse('close');
		}			 		
	}
	
	public function importReadyStatusFromNav($status) {
		global $db;		
		if (CheckAuth::check($status->idSession)) {			
			$xml = new SimpleXMLElement($status->status);
			foreach ($xml->ORDER as $order) {
				$query = "UPDATE `tms_order` SET `CustomInt`=$order->STATUS WHERE `CODE` = '$order->CODE'";
				if (!$db->query($query)) {
					return new importReadyStatusFromNavResponse('error');
				}
			}
			$db->close();
			return new importReadyStatusFromNavResponse('success');						
		} else {
			return new importReadyStatusFromNavResponse('close');
		}
	}
		
	public  function Auth($auth) {
		global $db;		
		$query = "SELECT * FROM `wm_users` WHERE `login`='$auth->login' AND `password`=MD5('$auth->password')";
		$result = $db->query($query);
		
		if ($result->num_rows) {
			$flag = true;			
		} else {			
			$flag = false;			
		}
		$result->close();
		return new AuthResponse($flag);		
	}
	
	public function isLogin($login, $password) {		 
		 include 'ClassMessageAndLogs.php';
		$obj = new MessageAndLogs();
		$obj->WriteLogAttendance('enter isLogin'.$login, 'SOAPlog', 'logs');
		
		include 'settings.php';
		$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME,$DB_PORT);
		$db->query("SET CHARSET SET utf8");
		$db->query("SET NAMES 'utf8'");
		
		$query = "SELECT * FROM `wm_users` WHERE `login`='$login' AND `password`=MD5('$password')";
		$obj->WriteLogAttendance('enter query'.$query, 'SOAPlog', 'logs');
		$result = $db->query($query);
		
		if ($result->num_rows) {
			$this->isLogin = true;
		} else {
			$this->isLogin = false;
		}
		$result->close();
		return $this->isLogin;
	}	
	
}



class AuthResponse {
	public  $AuthResult;
	public $AuthNumber;
	public function __construct($flag){
		global  $db;
		if ($flag) {
			session_start();
			$this->AuthResult = 'Вход разрешен';
			$this->AuthNumber = session_id();
			$query = "INSERT INTO tms_soap_session_id (`session_id`) VALUES ('$this->AuthNumber')";						
			$db->query($query);
		} else {			
			$this->AuthResult = 'Вход закрыт';
			$this->AuthNumber = 0;
		}
	}
}

class importRequestFromNavResponse {
	public $importRequestFromNavResult;
	public function __construct($flag) {
		switch ($flag) {
			case 'success': $this->importRequestFromNavResult = 'Импорт заявок произведен успешно'; 
			break;
			case 'close': $this->importRequestFromNavResult = 'Доступ закрыт. Авторизируйтесь';
			break;
			case 'error': $this->importRequestFromNavResult = 'Ошибка, заявки импортировать не удалось';
			break;
		}	
	}
}

class importReadyStatusFromNavResponse {
	public $importReadyStatusFromNavResult;
	public function __construct($flag, $mess = null) {
		
		if ($flag == 'success') {
			$this->importReadyStatusFromNavResult = 'Импорт статусов прошел успешно';
		} elseif ($flag == 'close') {
			$this->importReadyStatusFromNavResult = 'Доступ закрыт. Авторизируйтесь';
		} elseif ($flag == 'error') {
			$this->importReadyStatusFromNavResult = 'Ошибка импорта';
		}		
	}
}

class exportTripToNavResponse {	
	public $exportTripToNavResponseResult;
	public function __construct($flag) {
		if ($flag) {
			$this->exportTripToNavResponseResult = 'ThirdMethod';
		}
		
	}
}

class pingResponse {
	public $pingResult;
	public function __construct($flag = null) {
		if ($flag == null) {
			$this->pingResult = date('Y-m-d H:i:s');
		} else {
			$this->pingResult = 'Доступ закрыт. Авторизируйтесь';
		}
		
	}
}

class getTripFromTMSByOrderIdOutResponse {
	public $tripResultId;
	public function __construct($flag, $xml = null) {
		if ($flag == 'success') {			
			$this->tripResultId = $xml;			
		} elseif ($flag == 'empty') {
			$this->tripResultId = 'По данному коду рейсов не найдено';
		} elseif ($flag == 'error') {
			$this->tripResultId = 'Ошибка выполнения';
		} elseif ($flag == 'close') {
			$this->tripResultId = 'Доступ закрыт. Авторизируйтесь';
		}		
		return  $this->tripResultId;
	}
}

class getTripFromTMSByDateOutResponse {
	public $tripResultDate;
	public function __construct($flag, $xml = null) {
		if ($flag == 'success') {			
			$this->tripResultDate = $xml;			
		} elseif ($flag == 'empty') {
			$this->tripResultDate = 'За выбраный период рейсов нет';
		} elseif ($flag == 'error') {
			$this->tripResultDate = 'Ошибка выполнения';
		} elseif ($flag == 'close') {
			$this->tripResultDate = 'Доступ закрыт. Авторизируйтесь';
		}	 	
		return  $this->tripResultDate;
	}
}

class getTripFromTMSByTimeOutResponse {
	public $tripResultTime;
	public function __construct($flag, $xml = null) {
		if ($flag == 'success') {			
			$this->tripResultTime = $xml;			
		} elseif ($flag == 'empty') {
			$this->tripResultTime = 'За выбраный период рейсов нет';
		} elseif ($flag == 'error') {
			$this->tripResultTime = 'Ошибка выполнения';
		} elseif ('close') {
			$this->tripResultTime = 'Доступ закрыт. Авторизируйтесь';
		}		
		return  $this->tripResultTime;
	}
}

class XMLCreator {
	private $arrTripId = false;
	private $xml;
	private $db;
	public function __construct(array $tripId) {
		include 'settings.php';
		$this->arrTripId = $tripId;
		$this->db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME,$DB_PORT);
		$this->db->query("SET CHARSET SET utf8");
		$this->db->query("SET NAMES 'utf8'");
	}
	
	public function creareXML() {		
		if (is_array($this->arrTripId)) {
			$dom = new domDocument("1.0", "UTF-8");
			$dom->preserveWhiteSpace = false;
			$dom->formatOutput = true;
			$root = $dom->createElement("TRIPS");
			$dom->appendChild($root);
			foreach ($this->arrTripId as $tripId) {
				writeToLogFile('Trip ID '.$tripId);
				$trip =  $dom->createElement("TRIP");
				$root->appendChild($trip);
				$query = "SELECT c.Car_ID, t.Trip_ID, p.Project_ID, p.Name, p.Date, t.StartTime, t.EndTime, 
				t.Distance, t.Time,	time(t.StartTime)
				FROM tms_trip t
				INNER JOIN `tms_project` p ON p.`Project_ID`=t.`Project_ID`
				INNER JOIN  `tms_car_snapshot` s  ON s.`ID`=t.Car_ID
				INNER JOIN tms_car c ON  c.`Car_ID`=s.`Car_ID`
				WHERE t.Trip_ID = $tripId";
				$stmt = $this->db->prepare($query);
				$stmt->execute();
				$stmt->bind_result($CAR_CODE, $TRIP_CODE, $PROJECT_CODE, $PROJECT_NAME, $PROJECT_OUTPUT_TIME,
				$TRIP_START_TIME, $TRIP_END_TIME, $TRIP_DIST, $TRIP_DURATION, $WAREHOUSE_START_WORK_TIME);
				$stmt->fetch();				
				$stmt->close();
				$car_code = $dom->createElement("CAR_CODE", $CAR_CODE);
				$trip->appendChild($car_code);
				$trip_code = $dom->createElement("TRIP_CODE", $TRIP_CODE);
				$trip->appendChild($trip_code);
				$project_code = $dom->createElement("PROJECT_CODE", $PROJECT_CODE);
				$trip->appendChild($project_code);
				$project_name = $dom->createElement("PROJECT_NAME", $PROJECT_NAME);
				$trip->appendChild($project_name);
				$project_time = $dom->createElement("PROJECT_OUTPUT_TIME", $PROJECT_OUTPUT_TIME);
				$trip->appendChild($project_time);
				$trip_start_time = $dom->createElement("TRIP_START_TIME", $TRIP_START_TIME);
				$trip->appendChild($trip_start_time);
				$trip_end_time = $dom->createElement("TRIP_END_TIME", $TRIP_END_TIME);
				$trip->appendChild($trip_end_time);
				$trip_dist = $dom->createElement("TRIP_DIST", $TRIP_DIST);
				$trip->appendChild($trip_dist);
				$trip_duration = $dom->createElement("TRIP_DURATION", round($TRIP_DURATION));
				$trip->appendChild($trip_duration);
				$warehouse_start_time = $dom->createElement("WAREHOUSE_START_WORK_TIME", $WAREHOUSE_START_WORK_TIME);
				$trip->appendChild($warehouse_start_time);
				
				$orders = $dom->createElement("ORDERS");
				$trip->appendChild($orders);
				$countOdrers = 0;
				$query = "SELECT o.`Code`, tp.`OrderInTrip`, tp.EstimateTime, DATE_ADD(tp.EstimateTime, INTERVAL tp.`DurationInPoint` MINUTE), 
				 o.Order_ID FROM tms_trippoint tp 
				INNER JOIN tms_loadunloadpoint lp ON lp.`LoadUnloadPoint_ID`=tp.`Point_ID`
				INNER JOIN tms_order o ON o.`Order_ID`=lp.`OrderWarehouse_ID`
				WHERE tp.`Trip_ID`=$tripId ORDER BY tp.`OrderInTrip`";
				$stmt = $this->db->prepare($query);
				$stmt->execute();
				$stmt->bind_result($CODE_ORDER, $IN_TRIP_NUMBER, $DELIVERY_DATE_POINT, $DELIVERY_OUT_DATE, $SHOPCODE);
				while ($stmt->fetch()) {
					$countOdrers++;
					$order = $dom->createElement("ORDER");
					$orders->appendChild($order);
					$code_order = $dom->createElement("CODE_ORDER", $CODE_ORDER);
					$order->appendChild($code_order);
					$in_trip_number = $dom->createElement("IN_TRIP_NUMBER", $IN_TRIP_NUMBER);
					$order->appendChild($in_trip_number);
					$date_in_point = $dom->createElement("DELIVERY_DATE_POINT", $DELIVERY_DATE_POINT);
					$order->appendChild($date_in_point);
					$date_out_point = $dom->createElement("DELIVERY_OUT_DATE", $DELIVERY_OUT_DATE);
					$order->appendChild($date_out_point);
					$shopcode = $dom->createElement("SHOPCODE", $SHOPCODE);
					$order->appendChild($shopcode);
				}
				$count_orders = $dom->createElement("TRIP_ORDERS_COUNT", $countOdrers);
				$trip->appendChild($count_orders);
				$stmt->close();
			}
			$this->xml = $dom->saveXML();
			writeToLogFile($this->xml);
			//return '<pre>'. htmlspecialchars($this->xml).'</pre>';
			return $this->xml;
		}
	}
}

class CheckAuth {	
	public static function check($idSession) {
		global $db;
		$query = "SELECT id FROM `tms_soap_session_id` WHERE TIME>=SUBTIME(NOW(), '0".SESSION_TIME_OUT.":00:00') AND `session_id`='$idSession'";
		writeToLogFile('check '.$query);
		$stmt = $db->prepare($query);
		$stmt->execute();
		if ($stmt->fetch()) {			
			return true;
		}		
		return false;
	}
}

$server = new SoapServer("http://{$_SERVER['HTTP_HOST']}".PATH_TO_SERVISE."elit_wsdl.wsdl.php");
$server->setClass("Navision");
$server->handle();

function writeToLogFile($msg) {
	$today = date("Y_m_d");
	$logfile = $today."_log.txt";
	$dir = 'logs';
	$saveLocation=$dir . '/' . $logfile;
	if  (!$handle = @fopen($saveLocation, "a")) {
		exit;
	} else {
		if (@fwrite($handle,"$msg\r\n") === FALSE) {
			exit;
		}
			
		@fclose($handle);
	}
}

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);
	}
}