<?php

///////////////////////////////////////////////////////////////////////////////////////////////////
// START GENERATING THE REPORT ////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

if ($OK and $R['generateReport']) {

	///////////////////////////////////////////////////////////////////////////////////////////////
	// CHECK IF NO CHOSEN COLUMNS OR NO PIVOTS SELECTED ///////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////

	// COUNT CHOSEN COLUMNS ///////////////////////////////////////////////////////////////////////
	$columnsCount=0;
	if ( is_array($reportColumns)) {
		foreach($reportColumns as $colDet) {
			if ($colDet['s']) $columnsCount++;
		}
	}

	// COUNT CHOSEN PIVOTS ////////////////////////////////////////////////////////////////////////
	$pivotsCount=0;
	if ( is_array($pivotTables)) {
		foreach($pivotTables as $pivDet) {
			if ($pivDet['s']) $pivotsCount++;
		}
	}

	// display error if no columns / pivots
	if (!$columnsCount and !$pivotsCount) {
		$showMessage['warning'] = $_LANG['reportsGeneration']['startReport']['reportUndefined'];
		$OK=0;
	}

	// CHECK IF triggerReport IS SET AND CORRECT //////////////////////////////////////////////////
	$generationTimestamp=0;
	if ($R['triggerReport']!="now" and $R['triggerReport']!="programmed") {
		$showMessage['warning'] = $_LANG['reportsGeneration']['startReport']['noValidValueForReportTrigger'];
		$OK=0;
	}
	// CHECK IF triggerReport IS SET TO PROGRAMMED AND GENERATION TIMESTAMP IS NOT VALID //////////
	if ($R['triggerReport']=="programmed") {
		if (!$R['triggerDate'] or !checkValidDate($R['triggerDate'])) {
			$showMessage['warning'] = $_LANG['reportsGeneration']['startReport']['noDateTimeTrigger'];
			$OK=0;
		}
		// GET GENERATION TIMESTAMP AND CHECK IT --------------------------------------------------
		if ($OK) {
			$generationTimestamp=strtotime(standard2mysqlDateConversion($R['triggerDate']).' '.$R['triggerTime']);
			// check min limit
			if ($generationTimestamp<TIMESTAMP+$CFG['reportsGeneration']['generation']['triggerReport']['minTime']) {
				$showMessage['warning'] = sprintf($_LANG['reportsGeneration']['startReport']['reportTrigger_minTime'], date(MYSQL_FORMAT." H:i:s", TIMESTAMP+$CFG['reportsGeneration']['generation']['triggerReport']['minTime']));
				$OK=0;
			}
			// check max limit
			elseif ($generationTimestamp>TIMESTAMP+$CFG['reportsGeneration']['generation']['triggerReport']['maxTime']) {
				$showMessage['warning'] = sprintf($_LANG['reportsGeneration']['startReport']['reportTrigger_maxTime'], date(MYSQL_FORMAT." H:i:s", TIMESTAMP+$CFG['reportsGeneration']['generation']['triggerReport']['maxTime']));
				$OK=0;
			}
		}
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// CHECK THAT THIS USER HAS ACCESS TO THE REPORT //////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {
		$accessToReportSQL="SELECT idReport FROM `$DBTReportsAccess` WHERE idReport='".$idReport."' AND idUser='".$S['auth']['idUser']."' LIMIT 1";
		$accessToReportArr=$db->GetRow($accessToReportSQL);
		if ($db->ErrorNo()) {
			writeLog("Could not get report access.", 'events', 10);
			$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['cantCheckAccessToReport'];
			$OK=0;
		} else {
			if (!$accessToReportArr['idReport']) {
				$showMessage['warning'] = $_LANG['reportsGeneration']['startReport']['noAccessToReport'];
				$OK=0;
			}
		}
	}

	// CHECK REPORT VALABILITY ////////////////////////////////////////////////////////////////////
	if ($OK) {

		// check if valability is set
		if (!is_numeric($R['valabilityPeriod']) or $R['valabilityPeriod']<=0) {
			$showMessage['warning']=$_LANG['reportsGeneration']['startReport']['noValabilityPeriod'];
			$OK=0;
		}
		// check if valability measure unit is set
		if (!$R['valabilityMeasureUnit']) {
			$showMessage['warning']=$_LANG['reportsGeneration']['startReport']['noValabilityMu'];
			$OK=0;
		}
		// calculate the valability in minutes
		switch($R['valabilityMeasureUnit']) {
			case 'minutes': $totalValability=$R['valabilityPeriod'];break;
			case 'hours': $totalValability=$R['valabilityPeriod']*60;break;
			case 'days': $totalValability=$R['valabilityPeriod']*1440;break;
			case 'weeks': $totalValability=$R['valabilityPeriod']*10080;break;
			default:$totalValability=0;break;
		}
		// and check if it exceeds the configured limit
		if ($totalValability>$CFG['reportsGeneration']['generation']['valability']['maxDuration']) {
			$showMessage['warning']=sprintf($_LANG['reportsGeneration']['startReport']['valabilityTooBig'], round($CFG['reportsGeneration']['generation']['valability']['maxDuration']/1440, 2) );
			$OK=0;
		}
		// invalid valability
		if (!$totalValability) {
			$showMessage['warning']=$_LANG['reportsGeneration']['startReport']['valabilityInvalid'];
			$OK=0;
		}

	}

	// CHECK IF THE LIMIT OF CONCURRENT GENERATIONS WAS NOT MET ///////////////////////////////////
	if ($OK) {
		// check manual generations per user
		$manualGenerationsPerUser = getGeneratingReports(CURRENT_ID_USER, 'manual');
		if (count($manualGenerationsPerUser)>=$CFG['reportsGeneration']['concurrentGeneration']['manualGenerationsPerUser']) {
			$OK = 0;
			$showMessage['warning'] = sprintf($_LANG['reportsGeneration']['startReport']['manualGenPerUserLimitMet'], $CFG['reportsGeneration']['concurrentGeneration']['manualGenerationsPerUser']);
		}
		// check manual generations globally
		$manualGenerationsGlobal = getGeneratingReports(0, 'manual');
		if (count($manualGenerationsGlobal)>=$CFG['reportsGeneration']['concurrentGeneration']['manualGenerationsGlobal']) {
			$OK = 0;
			$showMessage['warning'] = sprintf($_LANG['reportsGeneration']['startReport']['manualGenGlobalLimitMet'], $CFG['reportsGeneration']['concurrentGeneration']['manualGenerationsGlobal']);
		}
	}


	///////////////////////////////////////////////////////////////////////////////////////////////
	// CHECK FILTERS //////////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	// updates $OK or changes
	include("index_startReportGeneration_validateFilters.php");

	///////////////////////////////////////////////////////////////////////////////////////////////
	// DETERMINE NEW REPORTS COMPATIBILITY DATA ///////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	include('index_startReportGeneration_compatNewReports.php');

	///////////////////////////////////////////////////////////////////////////////////////////////
	// ADD REPORT TO DATABASE /////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {

		// CALCULATE EXPIRE TIME ------------------------------------------------------------------
		if (!$generationTimestamp) {
			$expireTime=TIMESTAMP+$totalValability*60;
		} else {
			$expireTime=$generationTimestamp+$totalValability*60;
		}

		// DETERMINE COLUMNS/FILTERS TO BE STORED IN GENERATING REPORT ----------------------------
		if ($checkCompatibility) {
			$stdColumnsSer = $compat['stdColumns'] ? json_encode($compat['stdColumns']) : '';
			$custColumnsSer = $compat['customColumns'] ? json_encode($compat['customColumns']) : '';
			$stdFiltersSer = $compat['stdFilters'] ? json_encode($compat['stdFilters']) : '';
			$custFiltersSer = $compat['customFilters'] ? json_encode($compat['customFilters']) : '';
			$columnsOrderSer = $compat['columnsOrder'] ? json_encode($compat['columnsOrder']) : '';
		} else {
			$stdColumnsSer = $custColumnsSer = $stdFiltersSer = $custFiltersSer = $columnsOrderSer = '';
		}

		// RUN SQL ////////////////////////////////////////////////////////////////////////////////
		$addReportSQL="
			INSERT INTO `$DBTReportsGenerating` (
				idUser,  idReport, startTime, endTime, viewed, status, expireTime, addTime, setToStartTime,
				source, stdColumns, customColumns, stdFilters, customFilters, columnsOrder, platform, execTrigger
			) VALUES (
				'".CURRENT_ID_USER."', '".$idReport."', '0', '0', '0', 'pending', '".$expireTime."', '".TIMESTAMP."', '".$generationTimestamp."',
				?, ?, ?, ?, ?, ?, ?, ?
			)
		";
		$addReportEx=$db->Execute($addReportSQL, [$reportDetails['source'], $stdColumnsSer, $custColumnsSer,  $stdFiltersSer, $custFiltersSer, $columnsOrderSer, ($runningPlatform=='cli'?'cli':'browserSync'), 'manual'] );
		// check sql
		if (!$addReportEx) {
			$OK=0;
			$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['cantAddReportInDb'];
			writeLog("Could not add report into db. SQL: ".$addReportSQL, 'events', 10);
		} else {
			$idReportGenerating=$db->Insert_ID();
			if (!$idReportGenerating) {
				$OK=0;
				$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['noReportId'];
			}
		}

	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// GENERATE DIRECTORIES STRUCTURE TO STORE REPORT INPUTS //////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {

		$currentReportDir=$MODULE_REL_PATH.$CFG['paths']['generatedReports'].$idReportGenerating.'/';

		if ( !\Engine\Dir::create($currentReportDir) ) {
			$OK=0;
			$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['dirError'];
		}
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// CREATE THE REPORT INPUT FILE (serialized info containing: columns, filters, etc) ///////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {
		$reportInput= [];

/*
		// =-=-=-=-=-=-=-=-=-=-=-= TEST REPORT COLUMNS ONE BY ONE =-=-=-=-=-=-=-=-=-=-=-=
//		unset($S['startCol']);
		$S['startCol']++;
		$idx=0;
		foreach($reportColumns as $col=>$colDet) {
			$idx++;
			if ($idx==$S['startCol']) {
				$reportColumns[$col]=array('s'=>1, 'v'=>1, 'n'=>$colDet['n']);
				echo "Column: ".$col."<br>";
			} else {
				$reportColumns[$col]=array('s'=>0, 'v'=>1, 'n'=>$colDet['n']);
			}

		}
		echo $S['startCol'].' / '.count($reportColumns)."<br>";
		// =-=-=-=-=-=-=-=-=-=-=-= TEST REPORT COLUMNS ONE BY ONE =-=-=-=-=-=-=-=-=-=-=-=
*/


		// report id
		$reportInput['idReport']=$idReport;

		// report source
		$reportInput['reportSource']=$reportDetails['source'];

		// report columns
		$reportInput['columns']=$reportColumns;
		// force adding of the custom columns that are neither selected nor visible (bad concept applied here, but all custom columns are considered "selected" to simplify the pivot tables); should be rethought when the module is redone
		if ($reportCustomColumns) {
			foreach($reportCustomColumns as $col=>$colDet) {
				if (!$colDet['v'] and !$colDet['s']) $reportInput['columns'][$col]=$colDet;
			}
		}

		// report filters
		$reportInput['filters']= [];;
		foreach($reportFilters as $filter=>$filterDet) {
			$reportInput['filters'][$filter]=$filterDet['value'];
		}

		// report custom filters
		$reportInput['customFilters']= [];
		foreach($reportCustomFilters as $filter=>$filterDet) {
			if (strlen($filterDet['minValue'])) $reportInput['customFilters'][$filter]['minValue']=$filterDet['minValue'];
			if (strlen($filterDet['maxValue'])) $reportInput['customFilters'][$filter]['maxValue']=$filterDet['maxValue'];
			if (strlen($filterDet['value'])) $reportInput['customFilters'][$filter]['value']=$filterDet['value'];
			if ($filterDet['startDate']) $reportInput['customFilters'][$filter]['startDate']=$filterDet['startDate'];
			if ($filterDet['endDate']) $reportInput['customFilters'][$filter]['endDate']=$filterDet['endDate'];
			if ($filterDet['operation']) $reportInput['customFilters'][$filter]['operation']=$filterDet['operation'];
			if (strlen($filterDet['text'])) $reportInput['customFilters'][$filter]['text']=$filterDet['text'];
			if ($filterDet['boolean']) $reportInput['customFilters'][$filter]['boolean']=$filterDet['boolean'];
			if ($filterDet['valuesList']) $reportInput['customFilters'][$filter]['valuesList']=$filterDet['valuesList'];
			if ($filterDet['minAnniv_day']) $reportInput['customFilters'][$filter]['minAnniv_day']=$filterDet['minAnniv_day'];
			if ($filterDet['minAnniv_month']) $reportInput['customFilters'][$filter]['minAnniv_month']=$filterDet['minAnniv_month'];
			if ($filterDet['maxAnniv_day']) $reportInput['customFilters'][$filter]['maxAnniv_day']=$filterDet['maxAnniv_day'];
			if ($filterDet['maxAnniv_month']) $reportInput['customFilters'][$filter]['maxAnniv_month']=$filterDet['maxAnniv_month'];
			if ($filterDet['searchMode']) $reportInput['customFilters'][$filter]['searchMode']=$filterDet['searchMode'];
		}

		// report sorting
		$reportInput['sorting']=$reportSorting;

		// pivot tables
		$reportInput['pivotTables']=$pivotTables;
		// clean pivots not selected
		if (is_array($reportInput['pivotTables'])) {
			foreach($reportInput['pivotTables'] as $idx=>$piv) {
				if (!$piv['s']) unset($reportInput['pivotTables'][$idx]);
			}
		}

		// send report by email
		if ($R['emailRecipients'])
			$reportInput['emailRecipients']=$R['emailRecipients'];

		// store generation trigger
		if ($R['triggerReport']=="programmed") {
			$reportInput['trigger']="programmed";
		} else {
			$reportInput['trigger']="manual";
		}

		// create the file and change acces mode to it ////////////////////////////////////////////
		if ( !@file_put_contents($currentReportDir.$CFG['reportsGeneration']['generation']['inputDataFileName'], serialize($reportInput)) ) {
			$OK=0;
			$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['inputFileError'];
		} else {
			if ( !@chmod($currentReportDir.$CFG['reportsGeneration']['generation']['inputDataFileName'], 0777) ) {
				$OK=0;
				$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['inputFileAccessError'];
			}
		}


	}


	///////////////////////////////////////////////////////////////////////////////////////////////
	// ALSO CREATE THE OUTPUT FILE ////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////

	if ($OK and $runningPlatform=="cli") {

		// create the file and change acces mode to it ////////////////////////////////////////////
		if ( !@file_put_contents($currentReportDir.$CFG['reportsGeneration']['generation']['outputLogFileName'], ' ') ) {
			$OK=0;
			$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['outputFileError'];
		} else {
			if ( !@chmod($currentReportDir.$CFG['reportsGeneration']['generation']['outputLogFileName'], 0777) ) {
				$OK=0;
				$showMessage['error'] = $_LANG['reportsGeneration']['startReport']['outputFileAccessError'];
			}
		}

	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// START GENERATING REPORT ////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {

		// indicates not to display any info
		$reportIsGenerating=true;

		// RUNNING IN CLI /////////////////////////////////////////////////////////////////////////
		if ($runningPlatform=="cli" and !$generationTimestamp) {

			// save current dir and change it to processReport
			$dir=getcwd();
			chdir($APP_REAL_PATH.$MODULE_PATH);

			// GET PATH TO PHP FORM CONFIGS -------------------------------------------------------
			$pathToPhp='php';

			// COLLECT DATA TO RUN THE COMMAND ----------------------------------------------------
			$mainCommand=$APP_REAL_PATH."reports/reportsGeneration/processReport/index.php";
			$outputFile=realpath($APP_REAL_PATH.$CFG['paths']['generatedReports'].$idReportGenerating.'/'.$CFG['reportsGeneration']['generation']['outputLogFileName']);
			$arguments= [$idReportGenerating, $S['global']['lang']];

			// RUN THE COMMAND --------------------------------------------------------------------
			execCommand($mainCommand, $pathToPhp, $outputFile, $R['priority'], false, $arguments);

			// go back to old dir
			chdir($dir);

		}


		// RUNNING IN CURRENT PAGE ////////////////////////////////////////////////////////////////
		if ($runningPlatform=="currentPage") {
			// the iframe will do the trick...
		}

		$userTrailItem->updateActionOld('startReportOk');

	}


}



?>