<?php

// TODO: [PCI-DSS] - la salvare raport (sau import) sa se verifice daca exista coloana custom pe attr. importedCreditCard_number - asta trebuie logata special

///////////////////////////////////////////////////////////////////////////////////////////////////
// SAVE REPORT ////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if ($R['saveReport']) {

	$OK=1;

	// $okToFinish will indicate if the report can be updated /////////////////////////////////////
	// $warnings - is an array of warnings - indicates why the report can't be updated ////////////
	include("index_okToFinish.php");

	if (!$okToFinish) {
		$showMessage['warning'] = $allWarnings;
		$OK=0;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// SAVE THE REPORT INTO DATABASE //////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	if ($OK) {


		// ----- report filters -----
		if ($S['adminReport']['filters'])
			$reportFiltersStr=serialize($S['adminReport']['filters']);
		else
			$reportFiltersStr='';

		// ----- report custom filters -----
		if ($S['adminReport']['customFilters'])
			$reportCustomFiltersStr=serialize($S['adminReport']['customFilters']);
		else
			$reportCustomFiltersStr='';

		// ----- report columns -----
		$reportColumnsArr=$S['adminReport']['columns'];
		if (!$reportColumnsArr) $reportColumnsArr= [];
		// clean columns with no names
		foreach($reportColumnsArr as $colKey=>$colDet) {
			if (!$colDet['n']) unset($reportColumnsArr[$colKey]['n']);
			if (!$reportColumnsArr[$colKey]) unset($reportColumnsArr[$colKey]);
		}
		if ($reportColumnsArr)
			$reportColumnsStr=serialize($reportColumnsArr);
		else
			$reportColumnsStr='';

		// ----- custom columns -----
		if ($S['adminReport']['customColumns']) {
			$reportCustomColumnsArr=$S['adminReport']['customColumns'];
			// filter the custom columns - extract remark columns
			foreach($reportCustomColumnsArr as $idx=>$col) {
				// remark cols
				if (substr($col['f'], 0, 7)=='remark:') {
					$reportCustomColumnsArr[$idx]['type']='remark'; // set the type
					$colDet=explode(':', $col['f']);
					$reportCustomColumnsArr[$idx]['rmSrc']=$colDet[1];
					$reportCustomColumnsArr[$idx]['rmVar']=$colDet[2];
					unset($reportCustomColumnsArr[$idx]['t']);
					unset($reportCustomColumnsArr[$idx]['f']);
				}
				// arrayValue cols
				elseif (substr($col['f'], 0, 11)=='arrayValue:') {
					$reportCustomColumnsArr[$idx]['type']='arrayValue'; // set the type
					$colDet=explode(':', $col['f']);
					$reportCustomColumnsArr[$idx]['arrSrc']=$colDet[1];
					$reportCustomColumnsArr[$idx]['arrKey']=$colDet[2];
					unset($reportCustomColumnsArr[$idx]['t']);
					unset($reportCustomColumnsArr[$idx]['f']);
				}
				// entity cols
				elseif (substr($col['f'], 0, 7)=='entity:') {
					list(,$entType, $idEnt, $attr)=explode(':', $col['f']);
					$reportCustomColumnsArr[$idx]['type']='entity'; // set the type
					$reportCustomColumnsArr[$idx]['entType']=$entType;
					$reportCustomColumnsArr[$idx]['idEnt']=$idEnt;
					$reportCustomColumnsArr[$idx]['attr']=$attr;
					unset($reportCustomColumnsArr[$idx]['f']);
				}
				// entity cols
				elseif (substr($col['f'], 0, 12)=='entityValue:') {
					list(,$entType, $idEnt, $attr)=explode(':', $col['f']);
					$reportCustomColumnsArr[$idx]['type']='entityValue'; // set the type
					$reportCustomColumnsArr[$idx]['entType']=$entType;
					$reportCustomColumnsArr[$idx]['idEnt']=$idEnt;
					$reportCustomColumnsArr[$idx]['attr']=$attr;
					unset($reportCustomColumnsArr[$idx]['f']);
				}
				// math cols
				else {
					$reportCustomColumnsArr[$idx]['type']='math';
				}
			}
			$reportCustomColumnsStr=serialize($reportCustomColumnsArr);
		} else {
			$reportCustomColumnsStr='';
		}

		// ----- columns order -----
		if ($S['adminReport']['columnsOrder']) {
			$reportColumnsOrderArr=$S['adminReport']['columnsOrder'];
			$reportColumnsOrderStr=serialize($reportColumnsOrderArr);
		} else {
			$reportColumnsOrderStr='';
		}

		// ----- report sorting -----
		if ($S['adminReport']['sorting'])
			$reportSortingStr=serialize($S['adminReport']['sorting']);
		else
			$reportSortingStr='';

		// ----- report pivot tables -----
		if ($S['adminReport']['pivots'])
			$reportPivotTablesStr=serialize($S['adminReport']['pivots']);
		else
			$reportPivotTablesStr='';

		// ----- email recipients -----
		if ($S['adminReport']['extraOptions']['emailRecipients'])
			$reportEmailRecipientsStr=serialize($S['adminReport']['extraOptions']['emailRecipients']);
		else
			$reportEmailRecipientsStr='';

		// ----- autoGenerate report -----
		if ($S['adminReport']['extraOptions']['autoGenerate']['active']) {
			unset($S['adminReport']['extraOptions']['autoGenerate']['active']);
			$reportAutoGenerateStr=serialize($S['adminReport']['extraOptions']['autoGenerate']);
		} else {
			$reportAutoGenerateStr='';
		}

		// ----- report summary -----
		if ($S['adminReport']['extraOptions']['reportSummary']['active']) {
			unset($S['adminReport']['extraOptions']['reportSummary']['active']);
			if ($S['adminReport']['extraOptions']['reportSummary']['options'])
				$reportSummaryStr=serialize($S['adminReport']['extraOptions']['reportSummary']['options']);
			else
				$reportSummaryStr='';
		} else {
			$reportSummaryStr='';
		}

		// auto generate
		if ($reportAutoGenerateStr) {
			$nextAutoGenTime = calculateNextAutoGenTime($S['adminReport']['extraOptions']['autoGenerate']);
		} else {
			$nextAutoGenTime = 0;
		}

		// UPDATE REPORT SQL ----------------------------------------------------------------------
		if (isset($S['adminReport']['updateIdReport']) and $S['adminReport']['updateIdReport']>0) {
			$addReportSQL="
				UPDATE `$DBTReports`
				SET
					idCategory='".$S['adminReport']['idCategory']."',
					source='".$S['adminReport']['source']."',
					name='".$S['adminReport']['name']."',
					style='".$S['adminReport']['style']."',
					format='".$S['adminReport']['format']."',
					fileNameTemplate='".$S['adminReport']['fileNameTemplate']."',
					extension='".$S['adminReport']['extension']."',
					platform='".$S['adminReport']['platform']."',
					description='".$S['adminReport']['description']."',
					filters='".$reportFiltersStr."',
					customFilters='".$reportCustomFiltersStr."',
					columns='".$reportColumnsStr."',
					customColumns='".$reportCustomColumnsStr."',
					columnsOrder='".$reportColumnsOrderStr."',
					sorting='".$reportSortingStr."',
					pivotTables='".$reportPivotTablesStr."',
					emailRecipients='".$reportEmailRecipientsStr."',
					autoGenerate='".$reportAutoGenerateStr."',
					nextAutoGenTime='{$nextAutoGenTime}',
					summary='".$reportSummaryStr."',
					idUpdateUser='".$S['auth']['idUser']."',
					lastUpdateTime='".TIMESTAMP."',
					updatesCount=updatesCount+1
				WHERE id='".$S['adminReport']['updateIdReport']."'
			";
		}

		// ADD NEW REPORT SQL ---------------------------------------------------------------------
		if (!isset($S['adminReport']['updateIdReport'])) {
			$addReportSQL="
				INSERT INTO `$DBTReports` (
					deleted, idCategory, source,
					name, description,
					format, fileNameTemplate, extension, style, platform,
					filters, customFilters, columns, customColumns, columnsOrder, sorting,
					pivotTables, emailRecipients, autoGenerate, nextAutoGenTime, summary,
					idAddUser, addTime
				) VALUES (
					'0', '".$S['adminReport']['idCategory']."', '".$S['adminReport']['source']."',
					'".$S['adminReport']['name']."', '".$S['adminReport']['description']."',
					'".$S['adminReport']['format']."', '".$S['adminReport']['fileNameTemplate']."', '".$S['adminReport']['extension']."', '".$S['adminReport']['style']."', '".$S['adminReport']['platform']."',
					'".$reportFiltersStr."', '".$reportCustomFiltersStr."', '".$reportColumnsStr."', '".$reportCustomColumnsStr."', '".$reportColumnsOrderStr."', '".$reportSortingStr."',
					'".$reportPivotTablesStr."', '".$reportEmailRecipientsStr."', '".$reportAutoGenerateStr."', '0', '".$reportSummaryStr."',
					'".$S['auth']['idUser']."', '".TIMESTAMP."'
				)
			";
		}

		// sql generated - just run the sql and test it (if everything ok - finish wizard, close page, etc)
		$addReportEx=$db->Execute($addReportSQL);

		// CHECK SQLS AND DISPLAY MESSAGE ---------------------------------------------------------
		if (!$addReportEx) {
			writeLog("Could not save report. SQL: ".$addReportSQL, 'events', 10);
			$showMessage['error'] = $_LANG['reportsManagement']['admin']['finish']['reportSaveBad'];
		} else {

			// get id report
			if (!isset($S['adminReport']['updateIdReport'])) {
				$thisReportId=$db->Insert_ID();
			} else {
				$thisReportId=$S['adminReport']['updateIdReport'];
			}

			// UPDATE REPORTS ACCESS --------------------------------------------------------------

			// --- delete old accesses (for update only) ---
			$updateReportAccessEx_delete=true;
			if (isset($S['adminReport']['updateIdReport'])) {
				$updateReportAccessSQL_delete="DELETE FROM `$DBTReportsAccess` WHERE idReport='".$thisReportId."'";
				$updateReportAccessEx_delete=$db->Execute($updateReportAccessSQL_delete);
				if (!$updateReportAccessEx_delete) writeLog("Could not delete report old accesses.", 'events', 9);
			}

			// --- add new accesses ---
			if ($updateReportAccessEx_delete) {
				// generate sql
				$updateReportAccessSQL_insert="INSERT INTO `$DBTReportsAccess` (idReport, idUser) VALUES ";
				$accessesList= [];
				foreach($S['adminReport']['accessUsers'] as $idUser=>$active) {
					$accessesList[]="('".$thisReportId."', '".$idUser."')";
				}
				$updateReportAccessSQL_insert.=implode(", ", $accessesList);
				// run sql
				$updateReportAccessEx_insert=$db->Execute($updateReportAccessSQL_insert);
				if (!$updateReportAccessEx_insert) writeLog("Could not add report new accesses.", 'events', 9);

			}

			// display success message
			$showMessage['success'] = $_LANG['reportsManagement']['admin']['finish']['reportSaveOk'];

			// indicates popup closing
			$closePopup=1;
			// indicates report saved ok
			$reportSavedOk=true;

			// trace visits
			if ($S['adminReport']['updateIdReport']) $userTrailItem->updateActionOld("reportEditOk");
			else $userTrailItem->updateActionOld("reportAddOk");
			$userTrailItem->updateEntityOld("report", $thisReportId);

			// empty session
			unset($S['adminReport']);

		}

	}

}

?>