<?php

session_start();

$pathRoot = dirname(dirname(dirname(__DIR__))) . '/';
include_once($pathRoot . '.config/config_global.php');
require_once(PATH_CLS . 'rendering/viewClass.php');

/* Funktionen und Aktionen einbinden */
include_once(PATH_FNC . 'fnc_portal.php');

/* Variablen aufbereiten */
$_GET['siteId'] = '100';
$_GET['year'] = (isset ($_GET['year']) && !empty ($_GET['year']))
	? $_GET['year']
	: date('Y');
$_GET['month'] = (isset ($_GET['month']) && !empty ($_GET['month']))
	? $_GET['month']
	: date('n');
$_GET['orderBy'] = (isset ($_GET['orderBy']) && !empty ($_GET['orderBy']))
	? $_GET['orderBy']
	: 'logTS';
$_GET['orderDir'] = (isset ($_GET['orderDir']) && !empty ($_GET['orderDir']))
	? $_GET['orderDir']
	: 'DESC';
$sort = array();

/* Portal Zugriffsrechte prüfen */
include_once(PATH_INC . 'portal_rights.php');

/* Daten für Template aufbereiten */
$content = $db->query('SELECT * FROM ' . TBL_LOG . ' WHERE YEAR ( logTS ) = "' . $_GET['year'] . '" AND MONTH ( logTS ) = "' . $_GET['month'] . '" ORDER BY ' . $_GET['orderBy'] . ' ' . $_GET['orderDir'] . ';');
while ($tmp_content = $content->fetch_assoc())
{
	$tmp_content['logEntry'] = fnc_readLog($lang['log'][$tmp_content['logEntry']], $tmp_content['logParams']);
	$tmp_content['logUser'] = fnc_getUsernameById($tmp_content['logUser']);
	$tmp_content['logTS'] = fnc_getTimeByTS($tmp_content['logTS']);
	$sort[] = $tmp_content[$_GET['orderBy']];
	$data['sub_content']['main'][] = $tmp_content;
}

if ($_GET['orderBy'] === 'logUser')
{
	$order = ($_GET['orderDir'] === 'DESC')
		? SORT_DESC
		: SORT_ASC;
	array_multisort($sort, $order, $data['sub_content']['main']);
}

$year = $db->query('SELECT YEAR ( logTS ) AS firstYear FROM ' . TBL_LOG . ' ORDER BY logTS ASC LIMIT 1; ');
$tmp_year = $year->fetch_assoc();
$tmp_year = $tmp_year['firstYear'];
for ($tmp_year; $tmp_year <= date('Y'); $tmp_year++)
{
	$data['sub_content']['header']['year'][$tmp_year] = $tmp_year;
}

for ($month = 1; $month <= 12; $month++)
{
	$data['sub_content']['header']['month'][$month] = $lang['month'][$month];
}

/* Template rendern */
$render = new viewClass ();
$render->setPrefix($vC['portal']['layout']);
$render->setPathTpl(PATH_PORTAL_TPL);
$render->setConfig($vC);
$render->setTemplate('logfiles');
$render->setEditable(false);
$render->setData($data);
$render->setLang($lang['logfiles']);
$render->setFormdata(array_merge($_GET, $_POST));

$html = $render->output();
$html = str_replace(array('PHP_ROOT_PATH', 'PHP_SITE_PATH'), array(PATH_ROOT, PATH_SITE), $html);
$html = str_replace(array("\r", "\n", "\t"), array('', '', ''), $html);
echo $html;