<?php

///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// COLLECTS REPORT SUMMARY DATA (TO BE LATER INCLUDED IN THE REPORT FILE) /////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

// IF NO COLUMNS CHOSEN - REPORT WILL NOT BE EXPORTED, SO NO SUMMARY MUST BE CREATED //////////////
if (!$columnTypes) return;

// IF NO SUMMARY CONFIGURED AT ALL ////////////////////////////////////////////////////////////////
if (!$reportExport['summary']) return ;

// IF NO COMPONENTS OF THE SUMMARY SET ////////////////////////////////////////////////////////////
$reportSummaryConfig=unserialize($reportExport['summary']);
if (!$reportSummaryConfig) return ;


// LOAD LANG FILES CONTAINING THE ORIGINAL NAMES OF COLUMNS ///////////////////////////////////////
@include($thisCurrentDir.$MODULE_REL_PATH."_lang/".$S['global']['lang']."/_customLoad/reports/".$reportSource."/filters.lang.php");


///////////////////////////////////////////////////////////////////////////////////////////////////
// COLLECT DATA INTO $reportSummary ARRAY /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////

$reportSummary= [];

// REPORT SUMMARY - FILE //////////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['file']) {
	$reportSummary['file']=$reportOutput['report']['reportName'];
}


// REPORT SUMMARY - NAME //////////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['name']) {
	$reportSummary['name']=$reportExport['name'];
}


// REPORT SUMMARY - CATEGORY //////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['category']) {
	// get category name from db
	$repCatSQL="SELECT name FROM `$DBTReportsCategories` WHERE id='{$reportExport['idCategory']}'";
	$repCat=$db->GetRow($repCatSQL);
	if ($db->ErrorNo()) killReport("Could not get report category for summary. SQL:".$repCatSQL);
	// assign category
	$reportSummary['category']=$repCat['name'];
}


// REPORT SUMMARY - DESCRIPTION ///////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['description']) {
	$reportSummary['description']=$reportExport['description'];
}


// REPORT SUMMARY - SOURCE ////////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['source']) {
	$reportSummary['source']=$_LANG['reports']['source']['name'][$reportSource];
}


// REPORT SUMMARY - TIME //////////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['time']) {
	$reportSummary['time']=TIMESTAMP;
}


// REPORT SUMMARY - USER //////////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['user']) {
	// get user id
	$reportUserSQL="SELECT idUser FROM `$DBTReportsGenerating` WHERE id='".$idReportGenerating."'";
	$reportUser=$db->GetRow($reportUserSQL);
	if ($db->ErrorNo()) killReport("Could not get report user. SQL: ".$reportUserSQL);
	// assign user name
	if ($reportUser['idUser']) {
		$reportSummary['user']=\Entity\User::select($reportUser['idUser'])->name;
	}
}


// REPORT SUMMARY - FILTERS ///////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['filters']) {

	// ADD NORMAL FILTERS /////////////////////////////////////////////////////////////////////////

	// load filters configurations
	loadReportConfigs($reportSource, 'filters', $thisCurrentDir);
	$reportFiltersCfg=$CFG['reportsManagement']['adminReport']['filtersList'][$reportSource];

	// scan filters and obtain their values
	$reportSummary['filters']= [];
	if ($reportFilters) { // TODO: it looks like not all filters are correctly added to the summary
		foreach($reportFilters as $filterCode=>$filterDet) {

			// CHECK THE TYPE OF THE FILTER ///////////////////////////////////////////////////////
			switch($reportFiltersCfg[$filterCode]['type']) {
				// filter type = dateInterval -----------------------------------------------------
				case 'dateInterval':
					if ($filterDet['startDateMysql'] or $filterDet['endDateMysql']) { // TODO: this is old format of storing filters data
						$reportSummary['filters'][$filterCode]['value']=$filterDet['startDate'].' - '.$filterDet['endDate'];
					} elseif ($filterDet['startDate'] or $filterDet['endDate']) {
						$reportSummary['filters'][$filterCode]['value'] = $filterDet['startDate'].' - '.$filterDet['endDate'];
					}
					break;
				// filter type = autocomplete -----------------------------------------------------
				case 'autocomplete':
					switch ($reportFiltersCfg[$filterCode]['data']) {
						case 'officesAndUsers':
							if ($filterDet['idUser']) {
								$reportSummary['filters'][$filterCode]['value'] = \Entity\User::select($filterDet['idUser'])->name;
							} elseif ($filterDet['idOffice']) {
								$reportSummary['filters'][$filterCode]['value'] = \Entity\Office::select($filterDet['idOffice'])->name;
							}
						break;
						case 'location' :
							if ($filterDet['cityId']) {
								$reportSummary['filters'][$filterCode]['value'] = \Entity\City::select($filterDet['cityId'])->nameStandard;
							} elseif ($filterDet['countryCode']) {
								$reportSummary['filters'][$filterCode]['value'] = \Entity\Country::select($filterDet['countryCode'])->nameStandard;
							}
						break;
						case 'customer':
							$reportSummary['filters'][$filterCode]['value'] = \Entity\Customer::select($filterDet)->name;
						break;
						case 'supplier':
							$reportSummary['filters'][$filterCode]['value'] = \Entity\Supplier::select($filterDet)->alias;
						break;
						case 'corporate':
							$reportSummary['filters'][$filterCode]['value'] = \Entity\Corporate::select($filterDet)->alias;
						break;
						case 'miceProject':
							$reportSummary['filters'][$filterCode]['value'] = \Entity\MiceProject::select($filterDet)->name;
						break;
					}

					// fallback to the old way of presenting autocomplete values (by their stored value)
					if (!$reportSummary['filters'][$filterCode]['value'] and is_array($filterDet) and $filterDet['value']) {
						$reportSummary['filters'][$filterCode]['value'] = $filterDet['value'];
					}
					break;
				// filter type = text -------------------------------------------------------------
				case 'text':
					if ($filterDet)
						$reportSummary['filters'][$filterCode]['value']=$filterDet;
					break;
				// filter type = servicesSimple ---------------------------------------------------
				case 'servicesSimple':
					// if some checked values
					if ($filterDet) {
						// get services names
						$servNames=servicesCfg_servicesTranslations();
						// create filter value
						$filterVal='';
						foreach($filterDet as $servCode=>$act) {
							if ($act) {
								if ($filterVal) $filterVal.=", ";
								$filterVal.=$servNames[$servCode];
							}
						}
						// associate filter value
						if ($filterVal)
							$reportSummary['filters'][$filterCode]['value']=$filterVal;
					}
					break;
				// filter type = checkbox ---------------------------------------------------------
				case 'checkbox':
					if ($filterDet) {
						$filterVal='';
						foreach($filterDet as $elem=>$act) {
							if ($act) {
								if ($filterVal) $filterVal.=", ";
								switch($reportFiltersCfg[$filterCode]['data']) {
									case 'corporateType':
										$filterVal.=$_LANG['generalData']['companyTypes'][$elem];
										break;
									case 'clientType': case 'clientTypeWithBlank':
										if ($elem=='DC') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['directClients'];
										elseif ($elem=='0') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['clientType']['0'];
										else $filterVal.=$_LANG['generalData']['companyTypes'][$elem];
										break;
									case 'locked':
										if ($elem) $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['locked'];
										else $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['notLocked'];
										break;
									case 'personTitle':
										$filterVal.=$_LANG['generalData']['personTitles'][$elem];
										break;
									case 'personType':
										$filterVal.=$_LANG['generalData']['personTypes'][$elem];
										break;
									case 'formOfPayment': // TODO: not used
										$filterVal .= $_LANG['offers']['formOfPayment'][$elem]; // TODO: rhis is not even correct
										break;
									case 'offerFormOfPaymentWithBlank':
										if ($elem=='0') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['noOfferFop'];
										else $filterVal = $_LANG['offers']['formOfPayment'][$elem];
										break;
									case 'cashedStatus':
										if ($elem=='n') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['notCashed'];
										elseif ($elem=='p') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['partialCashed'];
										elseif ($elem=='t') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['totalCashed'];
										elseif ($elem=='o') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['overCashed'];
										break;
									case 'supplierInvoiceFinStatus':
										if ($elem=='n') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['notCashed'];
										elseif ($elem=='p') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['partialCashed'];
										elseif ($elem=='t') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['totalCashed'];
									break;
										case 'paymentDocTypes':
										$filterVal.=\App\Config\PaymentDocuments::getInstance()->getName($elem);
										break;
									case 'boolean':
										if ($elem) $filterVal.=$_LANG['yes'];
										else $filterVal.=$_LANG['no'];
										break;
									case 'balancedSimple':
										if ($elem=='n') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['notBalanced'];
										elseif ($elem=='t') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['totalBalanced'];
										break;
									case 'serviceStatusOp':
										if ($elem=='00') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['noOpStatus'];
										else $filterVal.=$_LANG['reservationServices']['statusOpName'][$elem];
										break;
									case 'serviceStatusFin': case 'serviceStatusFinWithBlank':
										if ($elem=='00') $filterVal.=$_LANG['reportsManagement']['admin']['filters']['checkboxes']['noFinStatus'];
										else $filterVal.=$_LANG['reservationServices']['statusFinName'][$elem];
										break;
									case 'orderStatusOp':
										$filterVal.=$_LANG['reservations']['statusOpName'][$elem];
										break;
									case 'orderStatusFin':
										$filterVal.=$_LANG['reservations']['statusFinName'][$elem];
										break;
									case 'cashingDocTypes':
										$filterVal.=\App\Config\CashingDocuments::getInstance()->getName($elem);
										break;
									case 'ticketAndRefundOps':
										$filterVal.=$elem;
										break;
									case 'taskStatus':
										$filterVal.=$_LANG['tasks']['statusName'][$elem];
										break;
									case 'documentType':
										$filterVal.=\App\Config\IssueDocuments::getInstance()->getDocTypeName($elem);
										break;
								}
							}
						}
						// associate filter code
						if ($filterVal) {
							$reportSummary['filters'][$filterCode]['value']=$filterVal;
						}
					}
					break;

				// filter type = select ------------------------------------------------------------
				case 'select':
					if ($filterDet) {
						$reportSummary['filters'][$filterCode]['value']=$filterDet;
					}
					break;
			}

			// ASSOCIATE FILTER NAME --------------------------------------------------------------
			if ($reportSummary['filters'][$filterCode]['value']) {
				$reportSummary['filters'][$filterCode]['name']=$_LANG['reports']['filterNames'][$reportSource][$filterCode];
			}

		}
	}


	// ADD CUSTOM FILTERS /////////////////////////////////////////////////////////////////////////
	if ($reportCustomFilters) {
		foreach($reportCustomFilters as $column=>$filterDetails) {
			$filterValue='';
			// CHECK FILTER TYPE ------------------------------------------------------------------
			switch ($columnsConfig[$column]['type']) {
				case 'boolean': {
					if ($filterDetails['boolean'][0]) $filterValue.=$_LANG['no'];
					if ($filterDetails['boolean'][0] and $filterDetails['boolean'][0]) $filterValue.=', ';
					if ($filterDetails['boolean'][1]) $filterValue.=$_LANG['yes'];
					break;
				}
				case 'price': case 'numeric': {
					// values list
					if ($filterDetails['valuesList']) {
						foreach($filterDetails['valuesList'] as $elem) {
							if ($elem['checked']) {
								if ($filterValue) $filterValue.=", ";
								$filterValue.=$elem['element'];
							}
						}
					}
					// no values list
					else {
						if (isset($filterDetails['minValue'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_min'].' '.$filterDetails['minValue'];
						if (isset($filterDetails['minValue']) and isset($filterDetails['maxValue'])) $filterValue.="; ";
						if (isset($filterDetails['maxValue'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_max'].' '.$filterDetails['maxValue'];
					}
					break;
				}
				case 'percent' : {
					if (isset($filterDetails['minValue'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_min'].' '.$filterDetails['minValue'].'%';
					if (isset($filterDetails['minValue']) and isset($filterDetails['maxValue'])) $filterValue.="; ";
					if (isset($filterDetails['maxValue'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_max'].' '.$filterDetails['maxValue'].'%';
					break;
				}
				case 'string' : {
					// values list
					if ($filterDetails['valuesList']) {
						foreach($filterDetails['valuesList'] as $elem) {
							if ($elem['checked']) {
								if ($filterValue) $filterValue.=", ";
								$filterValue.=$elem['element'];
							}
						}
					}
					// no values list
					else {
						$filterValue.=$_LANG['reports']['process']['reportSummary']['oper_'.$filterDetails['operation']].' `'.$filterDetails['text'].'`';
					}
					break;
				}
				case 'date': case 'yearMonth': case 'year': case 'datetime': {
					// date and 'anniversary'
					if ($columnsConfig[$column]['type']=="date" and $filterDetails['searchMode']=="anniversary") {
						$filterValue.='('.$_LANG['reports']['process']['reportSummary']['numeric_aniv'].') ';
						if ($filterDetails['minAnniv_day']) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_min'].' '.$filterDetails['minAnniv_day'].'-'.$_LANG['date']['month']['short'][(int)$filterDetails['minAnniv_month']];
						if ($filterDetails['minAnniv_day'] and $filterDetails['maxAnniv_day']) $filterValue.="; ";
						if ($filterDetails['maxAnniv_day']) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_max'].' '.$filterDetails['maxAnniv_day'].'-'.$_LANG['date']['month']['short'][(int)$filterDetails['maxAnniv_month']];
					}
					// others
					else {
						if (isset($filterDetails['startDate'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_min'].' '.$filterDetails['startDate'];
						if (isset($filterDetails['startDate']) and isset($filterDetails['endDate'])) $filterValue.="; ";
						if (isset($filterDetails['endDate'])) $filterValue.=$_LANG['reports']['process']['reportSummary']['numeric_max'].' '.$filterDetails['endDate'];
					}
					break;
				}
			}
			// associate filter value
			if ($filterValue) {
				$reportSummary['filters']['CUSTOM_'.$column]['value']=$filterValue;
				$reportSummary['filters']['CUSTOM_'.$column]['name']=$_LANG['reports']['columnNames'][$reportSource][$column];
			}
		}
	}

}

// REPORT SUMMARY - COLUMNS ///////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['columns']) {
	$reportSummary['columns']='';
	foreach($reportColumnsNames as $col=>$colName) {
		if ($reportSummary['columns']) $reportSummary['columns'].=", ";
		$reportSummary['columns'].=$colName;
	}
}


// REPORT SUMMARY - SORTING ///////////////////////////////////////////////////////////////////////
if ($reportSummaryConfig['sorting']) {
	if ($reportSorting['mainCriterionColumn']) {
		$reportSummary['sorting']['main']['column']=$_LANG['reports']['columnNames'][$reportSource][$reportSorting['mainCriterionColumn']];
		$reportSummary['sorting']['main']['order']=$_LANG['reports']['process']['reports']['ordering'][$reportSorting['mainCriterionOrderDirection']];
		if ($reportSorting['groupBy']=="main") $reportSummary['sorting']['main']['groupBy']=true;
	}
	if ($reportSorting['secCriterionColumn']) {
		$reportSummary['sorting']['sec']['column']=$_LANG['reports']['columnNames'][$reportSource][$reportSorting['secCriterionColumn']];
		$reportSummary['sorting']['sec']['order']=$_LANG['reports']['process']['reports']['ordering'][$reportSorting['secCriterionOrderDirection']];
		if ($reportSorting['groupBy']=="sec") $reportSummary['sorting']['sec']['groupBy']=true;
	}
	if ($reportSorting['thirdCriterionColumn']) {
		$reportSummary['sorting']['third']['column']=$_LANG['reports']['columnNames'][$reportSource][$reportSorting['thirdCriterionColumn']];
		$reportSummary['sorting']['third']['order']=$_LANG['reports']['process']['reports']['ordering'][$reportSorting['thirdCriterionOrderDirection']];
		if ($reportSorting['groupBy']=="third") $reportSummary['sorting']['third']['groupBy']=true;
	}
}


?>