<?php

 include_once 'modules/EcmReports/RaportMSH/FileHandler.php';
 include_once 'modules/EcmReports/RaportMSH/XlsReader.php';
 include_once 'modules/EcmReports/RaportMSH/Order.php';
 include_once 'modules/EcmReports/RaportMSH/ProductFactory.php';

$uploaded=0;

if(isset($_POST["submit"])) {
	$fileHandler = new FileHandler();
	if($fileHandler->uploadFile()){
		$xlsReader = new XlsReader($fileHandler->target_file);

		$productFactory = new ProductFactory($xlsReader->getArray(),$_REQUEST['date'],$fileHandler);

		$productFactory->createProducts();
		
		$uploaded=1;
	} else {
		$uploaded=2;
	}
} else {
	if($_REQUEST['delete']!=""){
		$query="delete from orders where file_id='".$_REQUEST['delete']."'";
		$res=$GLOBALS['db']->query($query);
	}
	$query="select file_id,file_name,user_id,file_date from orders group by file_id";
	$res=$GLOBALS['db']->query($query);
	$files = [];
	while($dane=$GLOBALS['db']->fetchByAssoc($res)){
		$user = new User();
		$user->retrieve($dane['user_id']);
		$dane['user_name']=$user->full_name;
		$files[]=$dane;
	}
}

$date = new DateTime ();
$date->modify ( "-1 month" );

$smarty = new Sugar_Smarty ();
$smarty->assign ( 'MOD', $mod_strings );
$smarty->assign ( 'files', $files );
$smarty->assign ( 'uploaded', $uploaded);
$smarty->assign ( 'count', ProductFactory::getObjectCount());
$smarty->assign ( 'date', $date->format ( "01.m.Y" ) );

echo $smarty->fetch ( "modules/EcmReports/RaportMSH/tpl/FileUpload.html" );
?>
