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

//error_reporting(0);

/*ini_set('error_reporting', E_ALL);
ini_set('error_reporting', E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', 1);*/


set_time_limit(300);
ini_set('memory_limit', '1024M');

include_once "settings.php";
//include "../LogistMobile_checkwebtask.php";
include_once "../schemaValidate.php";

include_once "logger2.php";

//include_once($_SERVER['DOCUMENT_ROOT'].'/monit2_task_ne_test/scripts/ClassLibs/getCoordFromAddrFunc.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/scripts/ClassLibs/getCoordFromAddrFunc.php');

$locale = $_SESSION['locale'];
if($locale == 'en'){
	include "../lang/LogistMobile/lang.en.php";
}elseif($locale == 'ru'){
	include "../lang/LogistMobile/lang.ru.php";
}elseif($locale == 'ua'){
	include "../lang/LogistMobile/lang.ua.php";
}

/*$DB_HOST='194.0.150.90';
$DB_USER='ilog';
$DB_PASS='1111';
$DB_NAME='tms37';
*/

$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()) {
    echo "Error connecting to DB";
    exit;
}
if(isset($_SESSION['location'])){
	$location = $_SESSION['location'];
}
// -- old monit task function --->
/*
$c = 0;
function check($lid){
	global $c;
	global $db;
	global $messageConfirm;
	$c++;
	$in_progress = 0;
	if($c<360){
	$query = "SELECT `in_progress` FROM `tms_web_tasks` WHERE `id` = ".$lid.";";
	$stmt = $db->prepare($query);
	$stmt->execute();
	$stmt->bind_result($in_progress);
	$stmt->fetch();
	$stmt->close();
	
	if( $in_progress == 0 ){
		sleep(1); check($lid);
	}else{ 
		//return $in_progress;
		//echo true; exit;
		//return (true);
		//die('true');
		$db->close();
		//die (json_encode(array("success" => true, "message" => 'Файл с заявками успешно импортирован')));
		die (json_encode(array("success" => true, "message" => $messageConfirm)));
	}
	}else{
		
		$query = "UPDATE `tms_web_tasks` SET `in_progress`=-1 WHERE `id` = ".$lid.";";
		$stmt = $db->prepare($query);
		$stmt->execute();
		$stmt->close();
		$db->close();
		//die (json_encode(array("success" => true, "message" => 'Файл с заявками успешно импортирован')));
		die (json_encode(array("success" => true, "message" => $messageConfirm)));
	}
}
*/
// <-- old monit task function ---



//$dir = 'C:/htdocs/monit2_task_ne_test/app/Logist/files/';
$dir = $_SERVER['DOCUMENT_ROOT']."/app/Logist/files/";

//$SERVER_NAME =  'http://'.$_SERVER['SERVER_NAME'].'/monit2_task_ne_test/app/Logist/';
$SERVER_NAME =  'http://'.$_SERVER['SERVER_NAME'].'/monit2_task_ne/app/Logist/';

$xsd = $SERVER_NAME.'orders.xsd';

//echo (json_encode(array("success" => false, "message" => $dir))); exit;
$client_id = $_SESSION['client_id'];
$project = $_REQUEST['project'];
	
	if(isset($_FILES['file'])){
    $file = $_FILES['file'];
	if ($file['size']!=0){
	//$allowedType = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel', 'application/excel', 'application/xml');
	//if(in_array($file['type'], $allowedType)){
		//$filename = $dir.$file['name'];
		
		$filename = $dir.$client_id.".".pathinfo($file['name'], PATHINFO_EXTENSION);
		$EXTENSION = pathinfo($file['name'], PATHINFO_EXTENSION);
		$filename2 = 'files/'.$client_id.".".pathinfo($file['name'], PATHINFO_EXTENSION);
		$namef = $file['name'];
		if( file_exists($filename) ){ unlink($filename); }
		$m = move_uploaded_file($file['tmp_name'], $filename);
        if($m!=false){
			
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> filename <> '.$filename);
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> EXTENSION <> '.$EXTENSION);
		
		if(file_exists($filename)){

		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> file_exists ');
		
if( $EXTENSION=="xml" || $EXTENSION=="XML"){
// -- ---------------------XML---------------------- -->		
		
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> file_exists xml ');
		
		// -- проверка на валидность. отключено пока -->
		//$libxml = libxml_schema_validate($SERVER_NAME.$filename2,$xsd);
		//if(!$libxml){
		// <-- проверка на валидность --
		
			if(isset($_REQUEST['trip'])){
				$xml = '<Data InstanceID="'.$client_id.'" >
				<p type="ImportTripXML">
				<p type="ImportTripXML"  ProjectID="'.$project.'" dir="'.$filename.'" />
				</p>
				</Data>';
			}else{
				//$filename2 = str_replace(array("/"),'\\',$filename);
				$xml = '<Data InstanceID="'.$client_id.'" >
				<p type="ImportDataXML">
				<p type="ImportDataXML"  ProjectID="'.$project.'" dir="'.$filename.'" pref="'.$location.'" />
				</p>
				</Data>';
			}
			
			$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$client_id.",0)";
			//echo $query;
			if ($stmt = $db->prepare($query)){
			if ($stmt->execute()){
			$last_id = $db->insert_id;
			$stmt->close();
			//echo $last_id;
			

			echo (json_encode(array("success" => true, "message" => $last_id)));
			
			if(!isset($_REQUEST['trip'])){
			// -- привязка 0-координат по инстансу клиента -->
			//get_address_from_coord($client_id);
			// <-- привязка 0-координат по инстансу клиента --
			}
			
			exit;
			/*
			$res = check($last_id);
			if($res){
				//echo (json_encode(array("success" => true, "message" => 'Файл с заявками успешно импортирован')));
				echo (json_encode(array("success" => true, "message" => $messageConfirm)));
				exit;
			}else{
				//echo (json_encode(array("success" => false, "message" => 'Ошибка импорта Файла с заявками')));
				echo (json_encode(array("success" => false, "message" => $messageErrorImport)));
				exit;
			}
			*/
			
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); exit;  }
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); exit;  }
		
		// -- проверка на валидность -->		
		//}else{ 
		//	echo(json_encode(array("success" => false, "message" => $libxml)));
		//	exit;
		//}	
		// <-- проверка на валидность --
// <-- ---------------------XML---------------------- --
}
// -- ---------------------XLSX---------------------- -->	
elseif($EXTENSION=="xlsx" || $EXTENSION=="XLSX" || $EXTENSION=="xls" || $EXTENSION=="XLS"){
	
	writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> file_exists xls ');
	
	include_once $_SERVER['DOCUMENT_ROOT']."/classes/PHPExcel.php";
	include_once $_SERVER['DOCUMENT_ROOT']."/classes/PHPExcel/IOFactory.php";
	
	//include_once $_SERVER['DOCUMENT_ROOT']."/monit2_task_ne_test/classes/PHPExcel.php";
	//include_once $_SERVER['DOCUMENT_ROOT']."/monit2_task_ne_test/classes/PHPExcel/IOFactory.php";

try{
	
	$objReader = PHPExcel_IOFactory::createReader('Excel2007');
	$objReader->setReadDataOnly(true);
	$objPHPExcel = $objReader->load($filename);
	$worksheet = $objPHPExcel->getActiveSheet();
	$highestRow = $worksheet->getHighestRow();
	$highestColumm = $worksheet->getHighestColumn();
	$highestColumm = PHPExcel_Cell::columnIndexFromString($highestColumm);;
	
	writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> highestRow <> '.$highestRow);
	
		$filexml = $dir.$client_id."task".rand(1,100).".xml";
		if( file_exists($filexml) ){ unlink($filexml); }
		
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> filexml <> '.$filexml);
		
		$dom = new domDocument("1.0", "UTF-8");
		$dom->preserveWhiteSpace = false;
		$dom->formatOutput = true;
		$root = $dom->createElement("ORDERS");
		$dom->appendChild($root);
	
	
	$change_value = "";
	
	
	
	for ( $row = 2; $row <= $highestRow; ++$row )
	{
		/*for ($column = 0; $column < $highestColumm; $column++) {
			
			if($column == 0){
				$RowCol = $worksheet->getCellByColumnAndRow($column,$row)->getValue();
				$RowCol = date('d/m/Y', PHPExcel_Shared_Date::ExcelToPHP($RowCol));
			}else{
				$RowCol = $worksheet->getCellByColumnAndRow($column,$row)->getValue();
			}
			
			echo $row.' - '.$column.' - '.$RowCol.'<br/>';
		}*/
	
	writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> CLIENT_CODE <> '.$worksheet->getCellByColumnAndRow(1,$row)->getValue());
	
	if($worksheet->getCellByColumnAndRow(1,$row)->getValue() || $worksheet->getCellByColumnAndRow(1,$row)->getValue()!=""){
		
		if( $worksheet->getCellByColumnAndRow(1,$row)->getValue() != $change_value ){
		
		$_ORDER = $dom->createElement("ORDER");
		$root->appendChild($_ORDER);
		
		
		
		$row0 = $worksheet->getCellByColumnAndRow(0,$row)->getValue();
		//$row0 = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($row0));
		$_DELIVERY_DATE = $dom->createElement("DELIVERY_DATE", $row0);
		$_ORDER->appendChild($_DELIVERY_DATE);
		
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> DELIVERY_DATE <> '.$row0);
		
		$_CODE = $dom->createElement("CODE", $worksheet->getCellByColumnAndRow(1,$row)->getValue());
		$_ORDER->appendChild($_CODE);
		
		$_CLIENT_CODE = $dom->createElement("CLIENT_CODE", $worksheet->getCellByColumnAndRow(2,$row)->getValue());
		$_ORDER->appendChild($_CLIENT_CODE);
		$_CLIENT_NAME = $dom->createElement("CLIENT_NAME", $worksheet->getCellByColumnAndRow(3,$row)->getValue());
		$_ORDER->appendChild($_CLIENT_NAME);
		$_SHOP_CODE = $dom->createElement("SHOP_CODE", $worksheet->getCellByColumnAndRow(4,$row)->getValue());
		$_ORDER->appendChild($_SHOP_CODE);
		$_SHOP_NAME = $dom->createElement("SHOP_NAME", $worksheet->getCellByColumnAndRow(5,$row)->getValue());
		$_ORDER->appendChild($_SHOP_NAME);
		$_ADDRESS = $dom->createElement("ADDRESS", $worksheet->getCellByColumnAndRow(6,$row)->getValue());
		$_ORDER->appendChild($_ADDRESS);
		$_GeoX = $dom->createElement("GeoX", $worksheet->getCellByColumnAndRow(7,$row)->getValue());
		$_ORDER->appendChild($_GeoX);
		$_GeoY = $dom->createElement("GeoY", $worksheet->getCellByColumnAndRow(8,$row)->getValue());
		$_ORDER->appendChild($_GeoY);
		$_SHOP_WORK_TIME = $dom->createElement("SHOP_WORK_TIME", $worksheet->getCellByColumnAndRow(9,$row)->getValue());
		$_ORDER->appendChild($_SHOP_WORK_TIME);
		$_SHOP_DINNER_TIME = $dom->createElement("SHOP_DINNER_TIME", $worksheet->getCellByColumnAndRow(10,$row)->getValue());
		$_ORDER->appendChild($_SHOP_DINNER_TIME);
		
		$_TOTAL_COST = $dom->createElement("TOTAL_COST", $worksheet->getCellByColumnAndRow(11,$row)->getValue());
		$_ORDER->appendChild($_TOTAL_COST);
		$_TOTAL_COUNT = $dom->createElement("TOTAL_COUNT", $worksheet->getCellByColumnAndRow(12,$row)->getValue());
		$_ORDER->appendChild($_TOTAL_COUNT);
		$_TOTAL_WEIGHT = $dom->createElement("TOTAL_WEIGHT", $worksheet->getCellByColumnAndRow(13,$row)->getValue());
		$_ORDER->appendChild($_TOTAL_WEIGHT);
		$_PALLETS_COUNT = $dom->createElement("PALLETS_COUNT", $worksheet->getCellByColumnAndRow(14,$row)->getValue());
		$_ORDER->appendChild($_PALLETS_COUNT);
		
		$_COMMENTS_ORDERS = $dom->createElement("COMMENTS_ORDERS", $worksheet->getCellByColumnAndRow(21,$row)->getValue());
		$_ORDER->appendChild($_COMMENTS_ORDERS);
		$_UPLOAD_TIME = $dom->createElement("UNLOAD_TIME", $worksheet->getCellByColumnAndRow(22,$row)->getValue());
		$_ORDER->appendChild($_UPLOAD_TIME);
		
		$_WAREHOUSE_CODE = $dom->createElement("WAREHOUSE_CODE", $worksheet->getCellByColumnAndRow(23,$row)->getValue());
		$_ORDER->appendChild($_WAREHOUSE_CODE);
		$_NAME = $dom->createElement("NAME", $worksheet->getCellByColumnAndRow(24,$row)->getValue());
		$_ORDER->appendChild($_NAME);
		$_COMMENTS_SHOP = $dom->createElement("COMMENTS_SHOP", $worksheet->getCellByColumnAndRow(25,$row)->getValue());
		$_ORDER->appendChild($_COMMENTS_SHOP);
		$_SPECIALIZATION_Name = $dom->createElement("SPECIALIZATION_Name", $worksheet->getCellByColumnAndRow(26,$row)->getValue());
		$_ORDER->appendChild($_SPECIALIZATION_Name);
		$_SPECIALIZATION_Id = $dom->createElement("SPECIALIZATION_Id", $worksheet->getCellByColumnAndRow(27,$row)->getValue());
		$_ORDER->appendChild($_SPECIALIZATION_Id);
		$_EXPEDITION = $dom->createElement("EXPEDITION", $worksheet->getCellByColumnAndRow(28,$row)->getValue());
		$_ORDER->appendChild($_EXPEDITION);
		$_EQUIPMENT_ID = $dom->createElement("EQUIPMENT_ID", $worksheet->getCellByColumnAndRow(29,$row)->getValue());
		$_ORDER->appendChild($_EQUIPMENT_ID);
		$_EQUIPMENT_NAME = $dom->createElement("EQUIPMENT_NAME", $worksheet->getCellByColumnAndRow(30,$row)->getValue());
		$_ORDER->appendChild($_EQUIPMENT_NAME);
		
		$_COMMENTS = $dom->createElement("COMMENTS", $worksheet->getCellByColumnAndRow(21,$row)->getValue());
		$_ORDER->appendChild($_COMMENTS);
		
		$_PRIORITY = $dom->createElement("PRIORITY", $worksheet->getCellByColumnAndRow(31,$row)->getValue());
		$_ORDER->appendChild($_PRIORITY);
		
		$_CustomStr1 = $dom->createElement("CUSTOMSTR1", $worksheet->getCellByColumnAndRow(32,$row)->getValue());
		$_ORDER->appendChild($_CustomStr1);
		$_CustomStr2 = $dom->createElement("CUSTOMSTR2", $worksheet->getCellByColumnAndRow(33,$row)->getValue());
		$_ORDER->appendChild($_CustomStr2);
		$_CustomStr3 = $dom->createElement("CUSTOMSTR3", $worksheet->getCellByColumnAndRow(34,$row)->getValue());
		$_ORDER->appendChild($_CustomStr3);
		
		
		$_PRODUCTS = $dom->createElement("PRODUCTS");
		$_ORDER->appendChild($_PRODUCTS);
		
		
		
		}
		
		if( $worksheet->getCellByColumnAndRow(19,$row)->getValue() || $worksheet->getCellByColumnAndRow(19,$row)->getValue()!="" ){
		
		$_PRODUCT = $dom->createElement("PRODUCT");
		$_PRODUCTS->appendChild($_PRODUCT);
		
		$_PROD_CODE = $dom->createAttribute("PROD_CODE");
		$_PROD_CODE->value = $worksheet->getCellByColumnAndRow(15,$row)->getValue();
		$_PRODUCT->appendChild($_PROD_CODE);
		
		$_PROD_NAME = $dom->createAttribute("PROD_NAME");
		$_PROD_NAME->value = $worksheet->getCellByColumnAndRow(16,$row)->getValue();
		$_PRODUCT->appendChild($_PROD_NAME);
		
		$_COUNT = $dom->createAttribute("COUNT");
		$_COUNT->value = $worksheet->getCellByColumnAndRow(17,$row)->getValue();
		$_PRODUCT->appendChild($_COUNT);
		
		$_COST = $dom->createAttribute("COST");
		$_COST->value = $worksheet->getCellByColumnAndRow(18,$row)->getValue();
		$_PRODUCT->appendChild($_COST);
		
		$_WEIGHT = $dom->createAttribute("WEIGHT");
		$_WEIGHT->value = $worksheet->getCellByColumnAndRow(19,$row)->getValue();
		$_PRODUCT->appendChild($_WEIGHT);
		
		$_VOLUME = $dom->createAttribute("VOLUME");
		$_VOLUME->value = $worksheet->getCellByColumnAndRow(20,$row)->getValue();
		$_PRODUCT->appendChild($_VOLUME);
		
		
		
		
		}
		
		$change_value = $worksheet->getCellByColumnAndRow(1,$row)->getValue();
		
	}
	}
	
	$xml = $dom->save($filexml);
	
			$xml = '<Data InstanceID="'.$client_id.'" >
			<p type="ImportDataXML">
			<p type="ImportDataXML"  ProjectID="'.$project.'" dir="'.$filexml.'" pref="'.$location.'" />
			</p>
			</Data>';

			$query = "INSERT INTO `tms_web_tasks` (`task`,`user_id`,`in_progress`) VALUES ('".$xml."',".$client_id.",0)";
			//echo $query;
			if ($stmt = $db->prepare($query)){
			$stmt->execute();
			$last_id = $db->insert_id;
			$stmt->close();
			//echo $last_id;
			
			echo (json_encode(array("success" => true, "message" => $last_id)));
			
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); exit;  }
	} catch (Exception $e) {
		writeToLogFile(' -> '.date('Y-m-d H:i:s').' <> Exception <> '.$e->getMessage());
		echo (json_encode(array("success" => true, "message" => $e->getMessage()))); exit;
	}
}
	
// <-- ---------------------XLSX---------------------- --
		
		
		}else{
			echo(json_encode(array("success" => false, "message" => $messageErrorLoad.' '.$namef)));
			exit;
		}
		
		
		
        }else{
			//echo(json_encode(array("success" => false, "message" => 'Ошибка загрузки файла '.$namef)));
			echo(json_encode(array("success" => false, "message" => $messageErrorLoad.' '.$namef)));
			exit;
		}
	}else{
		//echo(json_encode(array("success" => false, "message" => 'Неверный формат файла')));
		echo(json_encode(array("success" => false, "message" => $messageErrorFormat)));
		exit;
	}
	}else{
		//echo(json_encode(array("success" => false, "message" => 'Файл не может быть пустым')));
		echo(json_encode(array("success" => false, "message" => $messageErrorLength)));
		exit;
	}
?>