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

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

//require_once ('../../settings.php');
//require_once("../ClassLibs/ClassMessageAndLogs.php");

require_once("../../scripts/ClassLibs/ClassReport.php");
require_once 'Export.php';

include "settings.php";
include "logger.php";

$GMT = 2;

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

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

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

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


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`,s.`gmt` FROM `wm_users` u INNER JOIN `wm_clients` c ON u.`client_id` = c.`id` INNER JOIN `wm_settings` s ON s.`client_id` = c.`id` WHERE `login` = '".$login."' AND `password` = '".md5($password)."';";
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> loginClient <> '.$query );
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($client_id,$blocked,$client_gmt);
		$stmt->store_result();
		if($stmt->num_rows()>0){
			$stmt->fetch();
			$GMT = $client_gmt;
			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').' <> loginClient <> '.$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(isset($_REQUEST['start_date']) && isset($_REQUEST['end_date'])){
		$start_date = $_REQUEST['start_date'];
		$end_date = $_REQUEST['end_date'];
		$reg = "/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/";
		if( (preg_match($reg,$start_date)) && (preg_match($reg,$end_date)))
		{
			$dateFrom = $start_date.' 00:00:00';
			$dateTo = $end_date.' 23:59:59';
		}else{
			echo '<?xml version="1.0" encoding="utf-8"?><RESULT>Неверный формат даты</RESULT>'; exit;
		}
	}else{
		$dateFrom = date('Y-m-d').' 00:00:00';
		$dateTo = date('Y-m-d').' 23:59:59';
	}
	
	$imei = null;
	if(isset($_REQUEST['car_code'])){
		$imei = $_REQUEST['car_code'];
	}
	
	$order_code = null;
	if(isset($_REQUEST['order_code'])){
		$order_code = $_REQUEST['order_code'];
	}
	
	$key = $_REQUEST['key'];
	$query = "SELECT ss.instance_id,s.`gmt`,u.locale FROM `tms_soap_session_id` ss INNER JOIN `wm_settings` s ON s.`client_id` = ss.instance_id LEFT JOIN `wm_users` u ON u.client_id = s.`client_id` WHERE ss.TIME>=SUBTIME(NOW(), '0".SESSION_TIME_OUT.":00:00') AND ss.`session_id`='".$key."' ORDER BY ss.`time` DESC LIMIT 1";
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> loginClient <> '.$query );
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($instance_id,$client_gmt,$client_locale);
		$stmt->store_result();
		if($stmt->num_rows()>0){
			$stmt->fetch();
			$GMT = $client_gmt;
			$locale = $client_locale;
			//$xml = export($dateFrom = date('Y-m-d').' 00:00:00', $dateTo = date('Y-m-d').' 23:59:59', $instance_id, $GMT);
			$xml = export($dateFrom, $dateTo, $instance_id, $GMT, $imei, $order_code, $locale);
			echo $xml; 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; }
	
	
	
}


