<?php

$okToFinish=true;
$warnings= [];
$allWarnings='';

///////////////////////////////////////////////////////////////////////////////////////////////////
// CHECK STEP: 'GENERAL DATA' /////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// TEST IF REPORT CATEGORY SET --------------------------------------------------------------------
if (!$S['adminReport']['idCategory']) {
	$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['noCategory'];
	$okToFinish=false;
}

// TEST IF REPORT SOURCE SET ----------------------------------------------------------------------
if (!$S['adminReport']['source']) {
	$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['noSource'];
	$okToFinish=false;
}

// TEST IF REPORT EXTENSION ----------------------------------------------------------------------
if (!$S['adminReport']['extension']) {
	$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['noFileExtension'];
	$okToFinish=false;
}

// TEST IF REPORT NAME SET ------------------------------------------------------------------------
if (!$S['adminReport']['name']) {
	$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['noName'];
	$okToFinish=false;
}

// TEST IF REPORT NAME ALREADY EXISTS -------------------------------------------------------------
if ($S['adminReport']['name'] and $S['adminReport']['idCategory']) {
	// checking for adding report
	if (!isset($S['adminReport']['updateIdReport'])) {
		$checkReportNameSQL="SELECT id FROM `$DBTReports` WHERE idCategory='".$S['adminReport']['idCategory']."' AND name LIKE '".$S['adminReport']['name']."' AND !deleted LIMIT 1";
	}
	// checking for updating report
	else {
		$checkReportNameSQL="SELECT id FROM `$DBTReports` WHERE idCategory='".$S['adminReport']['idCategory']."' AND name LIKE '".$S['adminReport']['name']."' AND !deleted AND id!='".$S['adminReport']['updateIdReport']."' LIMIT 1";
	}
	$checkReportNameArr=$db->GetRow($checkReportNameSQL);
	if (!is_array($checkReportNameArr)) {
		$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['cantCheckSameName'];
		$okToFinish=false;
		writeLog("Could not test report name. SQL: ".$checkReportNameSQL, 'events', 10);
	} else {
		if ($checkReportNameArr['id']) {
			$warnings['general'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['reportWithSameName'];
			$okToFinish=false;
		}
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// CHECK STEP: 'CUSTOM COLUMNS' ///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if ($reportSource and is_array($S['adminReport']['customColumns']) and count($S['adminReport']['customColumns'])) {

	// GET [NUMBER] COLUMNS -----------------------------------------------------------------------
	loadReportConfigs($reportSource, 'columns');
	$priceCols= [];
	foreach($CFG['reportsManagement']['adminReport']['columnsList'][$reportSource] as $col=>$colDet) {
		// skip all disabled columns (and the ones that are not "price")
		if (!$colDet['disabled'] and ($colDet['type']=="price" or $colDet['type']=="numeric" or $colDet['type']=="percent")) {
			$priceCols[]=$col;
		}
	}
	foreach($S['adminReport']['customColumns'] as $idx=>$custCol) {
		$priceCols[]='CUSTOM_COLUMN_'.$idx;
	}

	// CHECK IF ANY OF THE COLUMNS IS NOT OK //////////////////////////////////////////////////////
	$colCnt=0;
	foreach($S['adminReport']['customColumns'] as $thisCol) {
		$colCnt++;
		// check name of the column
		if (!$thisCol['n']) {
			$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['custColWithNoName'], $colCnt);
			$okToFinish=false;
		}
		// check that column has formula
		if (!$thisCol['f']) {
			$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['custColWithNoFormula'], $colCnt);
			$okToFinish=false;
		}
		// CHECK THE FORMULA ----------------------------------------------------------------------
		// check that remark column is okay
		if (substr($thisCol['f'], 0, 7)=='remark:') {
			list(,$rmCol,$rmVar)=explodeClean(':', $thisCol['f']);
			if (!$rmVar) {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['rmCustColWithNoRmVar'], $colCnt);
				$okToFinish=false;
			}
			if (!$CFG['reportsManagement']['adminReport']['columnsList'][$reportSource][$rmCol]) {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['rmCustColNotExists'], $rmCol);
				$okToFinish=false;
			} elseif ($CFG['reportsManagement']['adminReport']['columnsList'][$reportSource][$rmCol]['content']!='remarks') {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['rmCustColNotValid'], $rmCol);
				$okToFinish=false;
			}
		}
		// check that arrayValue column is okay
		elseif (substr($thisCol['f'], 0, 11)=='arrayValue:') {
			list(,$arrCol,$arrKey)=explodeClean(':', $thisCol['f']);
			if (!$CFG['reportsManagement']['adminReport']['columnsList'][$reportSource][$arrCol]) {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['arrCustColNotExists'], $arrCol);
				$okToFinish=false;
			}
		}
		// check that entity column is okay
		elseif (substr($thisCol['f'], 0, 7)=='entity:') {
			if (!checkReportCustomColumnFormula($thisCol['f'], [])) {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['custColWithBadFormula'], $colCnt);
				$okToFinish=false;
			}
		}
		// check that entity column is okay
		elseif (substr($thisCol['f'], 0, 12)=='entityValue:') {
			if (!checkReportCustomColumnFormula($thisCol['f'], [])) {
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['custColWithBadFormula'], $colCnt);
				$okToFinish=false;
			}
		}
		// check if column is ok
		else {
			if (!checkReportCustomColumnFormula($thisCol['f'], $priceCols)) { // allow remarks to be added in the report
				$warnings['customColumns'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['custColWithBadFormula'], $colCnt);
				$okToFinish=false;
			}
		}


	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// CHECK STEP: 'PIVOT TABLES' /////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// LOOP TROUGH PIVOTS AND CHECK IF THEY ARE OK ////////////////////////////////////////////////////
if (is_array($S['adminReport']['pivots']) and count($S['adminReport']['pivots']) ) {
	$pivotCnt=0;
	foreach($S['adminReport']['pivots']['pivotsList'] as $idx=>$pivotDetails) {
		$pivotCnt++;

		// no fields selected for rows/cols
		if ( !(count($pivotDetails['rows'])+count($pivotDetails['cols'])) ) {
			$warnings['pivotTables'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['noFieldsSelectedForRowsCols'], $pivotCnt, $pivotDetails['n']);
			$okToFinish=false;
		}
		// no fields selected for data
		if ( !count($pivotDetails['data']) ) {
			$warnings['pivotTables'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['noFieldsSelectedForData'], $pivotCnt, $pivotDetails['n']);
			$okToFinish=false;
		}

	}

}


///////////////////////////////////////////////////////////////////////////////////////////////////
// CHECK STEP: 'ACCESS' ///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// TEST IF NONE OF THE USERS HAS ACCESS TO THIS REPORT --------------------------------------------
if ( !is_array($S['adminReport']['accessUsers']) or !count($S['adminReport']['accessUsers']) ) {
	$warnings['access'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['noUsersAccess'];
	$okToFinish=false;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// CHECK STEP: 'EXTRA OPTIONS' ////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// IF AUTOGENERATE REPORTS IS ACTIVE //////////////////////////////////////////////////////////////
if ($S['adminReport']['extraOptions']['autoGenerate']['active']) {
	// CHECK THAT AT LEAST ONE WEEK DAY SET -------------------------------------------------------
	if (!$S['adminReport']['extraOptions']['autoGenerate']['wday']) {
		$warnings['access'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['autoGen_noWday'];
		$okToFinish=false;
	}
	// CHECK THAT AT LEAST ONE MONTH DAY SET ------------------------------------------------------
	if (!$S['adminReport']['extraOptions']['autoGenerate']['mday']) {
		$warnings['access'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['autoGen_noMday'];
		$okToFinish=false;
	}
	// CHECK THAT AT LEAST ONE USER SET -----------------------------------------------------------
	if (!$S['adminReport']['extraOptions']['autoGenerate']['usersList']) {
		$warnings['access'][]=$_LANG['reportsManagement']['admin']['finish']['warnings']['autoGen_noUsers'];
		$okToFinish=false;
	}
	// CHECK IF ANY OF THE MANDATORY FILTERS ARE NOT SET ------------------------------------------
	if ($reportSource) {
		// load the filters configs/lang
		loadReportConfigs($reportSource, 'filters');
		@include($MODULE_REL_PATH."_lang/".$S['global']['lang']."/_customLoad/reports/".$reportSource."/filters.lang.php");
		foreach($CFG['reportsManagement']['adminReport']['filtersList'][$reportSource] as $filter=>$filterDet) {
			// if filter is not mandatory - skip it
			if (!$filterDet['mandatory']) continue;

			// filter type = dateInterval
			if ($filterDet['type']=="dateInterval") {
				if (!is_numeric($S['adminReport']['filters'][$filter]['d']['startDate']['duration']) or !$S['adminReport']['filters'][$filter]['d']['startDate']['timeUnit']) {
					$warnings['access'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['autoGen_mandFil_date_start'], $_LANG['reports']['filterNames'][$reportSource][$filter]);
					$okToFinish=false;
				}
				if (!is_numeric($S['adminReport']['filters'][$filter]['d']['endDate']['duration']) or !$S['adminReport']['filters'][$filter]['d']['endDate']['timeUnit']) {
					$warnings['access'][]=sprintf($_LANG['reportsManagement']['admin']['finish']['warnings']['autoGen_mandFil_date_end'], $_LANG['reports']['filterNames'][$reportSource][$filter]);
					$okToFinish=false;
				}
			}

		}
	}
}

// add extra validations
\Engine\Plugins\Manager::getInstance()->executeEvent("Reports-Manage-extraValidations", [ 'reportSource'=>$reportSource, 'idCategory'=>$S['adminReport']['idCategory'], 'reportName'=>$S['adminReport']['name'], 'idUsers'=>array_keys((array)$S['adminReport']['accessUsers']) ] );

///////////////////////////////////////////////////////////////////////////////////////////////////
// END CHECKING ///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// gets all the warnings to form a big message
foreach($warnings as $theseWarnings) {
	$allWarnings.=implode(' ', $theseWarnings);
}

