<?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);
error_reporting(0);


require_once "importAPIFunction.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');
}

function export($dateFrom,$GMT) {
	
	global $db;
	
	$dom = new domDocument("1.0", "UTF-8");
	$dom->preserveWhiteSpace = false;
	$dom->formatOutput = true;
	
	$query = "SELECT `Message`, `DeviceLoginName`, `GeoX`, `GeoY` FROM `tms_events` WHERE `EventType` IN (1,2) AND ADDTIME(`date`, '0 ".$GMT.":0:0') >= '".$dateFrom."'";
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> export <> '.$query, 'export');
	if ($stmt = $db->prepare($query)) {
	if ($stmt->execute()) {
		$stmt->bind_result($Message,$DeviceLoginName,$GeoX,$GeoY);
		$stmt->store_result();
		if($stmt->num_rows()>0){

		$root = $dom->createElement("EVENTS");
		$dom->appendChild($root);
			
		while ($stmt->fetch()) {
			
			$EVENT = $dom->createElement("EVENT");
			$root->appendChild($EVENTS);
			
			$NAME_EVENT = $dom->createElement("EVENT_NAME", $Message);
			$EVENT->appendChild($NAME_EVENT);
			
			$DEVICE = $dom->createElement("DEVICE", $DeviceLoginName);
			$EVENT->appendChild($DEVICE);
			
			$GEOX = $dom->createElement("GEOX", $GeoX);
			$EVENT->appendChild($GEOX);
			
			$GEOY = $dom->createElement("GEOY", $GeoY);
			$EVENT->appendChild($GEOY);
			
			
		}
		
		$stmt->close();
		return  $dom->saveXML();
		
		}else{
			result_message_xml(-1,'События не найдеы',0,0,0);
			exit;
		}
	}else{
			result_message_xml(-1,'События не найдеы',0,0,0);
			exit;
		}
	}else{
			result_message_xml(-1,'События не найдеы',0,0,0);
			exit;
		}
	
}

if(isset($_REQUEST['key'])){
	
	writeToLogFile( ' ---> '.date('Y-m-d H:i:s').' <> export event ', 'export');
	
	$key = $_REQUEST['key'];
	
	if( isset($_REQUEST['date']) ){
		$start_date = $_REQUEST['start_date'];
		$dateFrom = $start_date.' 00:00:00';
	}else{
		$dateFrom = date('Y-m-d').' 00:00:00';
		//$dateTo = date('Y-m-d').' 23:59:59';
	}
	
	$query = "SELECT ss.instance_id,s.`gmt` FROM `tms_soap_session_id` ss INNER JOIN `wm_settings` s ON s.`client_id` = ss.instance_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').' <> export <> '.$query, 'export' );
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($instance_id,$client_gmt);
		$stmt->store_result();
		if($stmt->num_rows()>0){
			$stmt->fetch();
			$GMT = $client_gmt;
			$xml = export($dateFrom,$GMT);
			echo $xml; exit;
		}else{
			//echo 'Доступ закрыт. Авторизируйтесь'; exit;
			result_message_xml(-1,'Доступ закрыт. Авторизируйтесь',0,0,0); exit;
		}
	}else{ result_message_xml(-1,'Ошибка выполнения',0,0,0); exit; }
	}else{ result_message_xml(-1,'Ошибка выполнения',0,0,0); exit; }
	
	//}else{ result_message_xml(-1,'Тег filial_code отсутствует',0,0,0); exit; }
	
}else{
	result_message_xml(-1,'Пустой запрос',0,0,0);
	exit;
}


