<?php

include("_config/addCfg.php");
include("_includes/addInc.php");

// reset order if category changed
if($R['idCategory']){
	if($S['reportsGen']['idCurrentCategory']!=$R['idCategory'] ){
		unset($S['reportsGen']['orderBy'],$S['reportsGen']['orderDirection']);
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// REPORTS LIST PAGE CONTROLS /////////////////////////////////////////////////////////////////////
// something set by request - for current page
///////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($R['currentPage']))
	$S['reportsGen']['currentPage']=$R['currentPage'];
if (isset($R['orderDirection']) and (strtoupper($R['orderDirection'])=='ASC' or strtoupper($R['orderDirection'])=='DESC'))
	$S['reportsGen']['orderDirection']=$R['orderDirection'];
if (isset($R['orderBy']) and $CFG['reportsGeneration']['reportsList']['allowOrder'][$R['orderBy']])
	$S['reportsGen']['orderBy']=$R['orderBy'];

// change results per page (rpp)
if ($R['resultsPerPage']) {
	if ($S['reportsGen']['resultsPerPage']!=$R['resultsPerPage']) { // if rpp changed
		\DB::startTransaction();
		\App\EntityPreference\User::getInstance()->reportsGenRpp=$R['resultsPerPage'];
		\DB::rollbackTransaction();
		$S['reportsGen']['resultsPerPage']=$R['resultsPerPage'];
		$S['reportsGen']['currentPage']=0;
	}
}

// default current page
if (!$S['reportsGen']['currentPage'] or $S['reportsGen']['currentPage']<0)
	$S['reportsGen']['currentPage']=0;
// order by
if (!$S['reportsGen']['orderBy'])
	$S['reportsGen']['orderBy']=$CFG['reportsGeneration']['reportsList']['orderByDefault'];
// order direction
if (!$S['reportsGen']['orderDirection'])
	$S['reportsGen']['orderDirection']=$CFG['reportsGeneration']['reportsList']['orderDirectionDefault'];
// get default rpp
if(!$S['reportsGen']['resultsPerPage']) {
	$userPref=\App\EntityPreference\User::getInstance()->reportsGenRpp;
	if (!$userPref)
		$S['reportsGen']['resultsPerPage']=$CFG['reportsGeneration']['reportsList']['resultsPerPageDefault'];
	else
		$S['reportsGen']['resultsPerPage']=$userPref;
}



// MANAGE ID CATEGORY /////////////////////////////////////////////////////////////////////////////

if ($R['idCategory']) {
	// set report category from request
	$idCategory=$R['idCategory'];
	$S['reportsGen']['idCurrentCategory']=$idCategory;
} else {
	// mark into session the current category
	$idCategory=$S['reportsGen']['idCurrentCategory'];
}

// display message if no categories
if (!$idCategory) {
	$showMessage['info'] = $_LANG['reportsGeneration']['reportsList']['noCategoryChosen'];
}



///////////////////////////////////////////////////////////////////////////////////////////////////
// GET DATA TO BE DISPLAYED ///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if ($idCategory) {

	///////////////////////////////////////////////////////////////////////////////////////////////
	// GET CATEGORY NAME //////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////
	$categoryDetailsSQL="SELECT id, name FROM `$DBTReportsCategories` WHERE id='".$idCategory."'";
	$categoryDetails=$db->GetRow($categoryDetailsSQL);
	// show error on sql failure
	if (!is_array($categoryDetails)) {
		writeLog("Could not get category name. SQL: ".$categoryDetailsSQL, 'events', 8);
	}


	///////////////////////////////////////////////////////////////////////////////////////////////
	// GET REPORTS LIST ///////////////////////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////////////////////////

	$reportsListSQL="
		SELECT SQL_CALC_FOUND_ROWS
			rep.id, rep.source, rep.name, rep.description,
			rep.idAddUser, rep.addTime, rep.idUpdateUser, rep.lastUpdateTime, rep.updatesCount
		FROM `$DBTReports` AS rep, `$DBTReportsAccess` AS acc
		WHERE rep.idCategory='".$idCategory."' AND !rep.deleted AND rep.id=acc.idReport AND acc.idUser='".$S['auth']['idUser']."'
		ORDER BY rep.".$S['reportsGen']['orderBy']." ".$S['reportsGen']['orderDirection']."
		LIMIT ".($S['reportsGen']['currentPage']*$S['reportsGen']['resultsPerPage']).",".$S['reportsGen']['resultsPerPage']."
	";
	$reportsList=$db->GetAll($reportsListSQL);
	// show error on sql failure
	if (!is_array($reportsList)) {
		$showMessage['error'] = $_LANG['reportsGeneration']['reportsList']['reportsListBad'];
	}
	else {

		$repCountSQL="SELECT FOUND_ROWS() AS totalResults";
		$repCountArr=$db->GetRow($repCountSQL);
		$countResults=$repCountArr['totalResults'];

		// display message if no results
		if (!count($reportsList) and !$countResults) {
			$showMessage['warning'] = $_LANG['reportsGeneration']['reportsList']['noReportsToShow'];
		}
	}

	// ADD EXTRA INFO TO REPORTS LIST /////////////////////////////////////////////////////////////
	if (is_array($reportsList)) {
		foreach($reportsList as $id=>$thisReport) {

			// add user
			$addUser=getUserDetails($thisReport['idAddUser']);
			$reportsList[$id]['addUserName']=$addUser['name'];

			// last update user
			$lastUpdateUser=getUserDetails($thisReport['idUpdateUser']);
			$reportsList[$id]['updateUserName']=$lastUpdateUser['name'];

			// GET REPORTS THAT ARE NOT VIEWED FOR CURRENT USER -----------------------------------
			$getActiveReportsSQL="SELECT id, status, viewed, startTime FROM `$DBTReportsGenerating` WHERE idReport='".$thisReport['id']."' AND idUser='".$S['auth']['idUser']."' AND viewed=0 ORDER BY id DESC";
			$activeReports=$db->GetAll($getActiveReportsSQL);
			if (!is_array($activeReports)) {
				writeLog("Could not get active reports. SQL: ".$getActiveReportsSQL, 'events', 10);
			} else {
				$reportsList[$id]['notViewedReports']=$activeReports;
			}

		}
	}


}


###################################################################################################
## SMARTY #########################################################################################
###################################################################################################

$smarty->assign('categoryDetails', $categoryDetails);

// the list of reports
$smarty->assign('reportsList', $reportsList);

$smarty->assign('orderBy', $S['reportsGen']['orderBy']);
$smarty->assign('orderDirection', $S['reportsGen']['orderDirection']);

// page controls
$smarty->assign("pages",
	[
		'currentPage'=>		$S['reportsGen']['currentPage'],
		'countResults'=>	$countResults,
		'resultsPerPage'=>	$S['reportsGen']['resultsPerPage'],
		'resultsPerPageSelector'=>$CFG['reportsGeneration']['reportsList']['resultsPerPageSelector'],
		'ajax'=>1,
		'ajaxDiv'=>'reportsListDiv',
		'ajaxURI'=>'reportsList.php',
		'loadingMask' =>true,
		'onSubmit'=>'',
	]
);


// DISPLAY TEMPLATE -------------------------------------------------------------------------------
$smarty->display("reportsList.tpl");

?>