<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 * @author     Markus Domin <markus.domin@fh-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Systemstatistics{

	public function __construct() {

	}

    /** function to show statistics
     * @return false|string
     * @throws Twig_Error_Loader
     * @throws Twig_Error_Runtime
     * @throws Twig_Error_Syntax
     */

	public function showStatistics($atts){

		$heading = isset($atts['titel']) ? $atts['titel'] : 'Systemstatistiken'; 
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{
			ob_start();

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}


			//Anlegen der Nutzer auswerten
			$usercreatedateHourraw = array();
			$usercreatedateDayraw = array();
			$usercreatedateMounthraw = array();

			$users = get_users();
			foreach( $users as $user ) {
				$udata = get_userdata( $user->ID );
				$usercreatedateHourraw =$this->getHour($usercreatedateHourraw,$udata->user_registered);
				$usercreatedateDayraw =$this->getDay($usercreatedateDayraw,$udata->user_registered);
				$usercreatedateMounthraw = $this->getMounth($usercreatedateMounthraw,$udata->user_registered);
			}


			//Letztes Login der Nutzer auswerten
			$lastloginHourraw = array();
			$lastloginDayraw = array();
			$lastloginMounthraw = array();
			$lastlogin = Trainingssystem_Plugin_Database::getInstance()->LastLoginDao->getAllLastlogin();

			foreach ($lastlogin as $key => $value) {

				$lastloginHourraw = $this->getHour($lastloginHourraw,$value[0]);
				$lastloginDayraw = $this->getDay($lastloginDayraw,$value[0]);
				$lastloginMounthraw = $this->getMounth($lastloginMounthraw,$value[0]);
			}

			//Nutzereingaben auswerten
			$inputHourraw = array();
			$inputDayraw = array();
			$inputMounthraw = array();
			$input = Trainingssystem_Plugin_Database::getInstance()->Formdata->getAllFormdataDates();

			foreach ($input as $key => $value) {

				$inputHourraw = $this->getHour($inputHourraw,$value[0]);
				$inputDayraw = $this->getDay($inputDayraw,$value[0]);
				$inputMounthraw = $this->getMounth($inputMounthraw,$value[0]);
			}


			//Lektion beendet auswählen auswerten
			$lektionHourraw = array();
			$lektionDayraw = array();
			$lektionMounthraw = array();
			$lektion = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllLektionFin();

			foreach ($lektion as $key => $value) {

				$lektionHourraw = $this->getHour($lektionHourraw,$value[0]);
				$lektionDayraw = $this->getDay($lektionDayraw,$value[0]);
				$lektionMounthraw = $this->getMounth($lektionMounthraw,$value[0]);
			}
			
			$trainingFinUserCountRaw= Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingFinUserCount();
			$trainingFinUserCountLbl=array();
			$trainingFinUserCountValues=array();
			foreach ($trainingFinUserCountRaw as $key => $value) {
				$trainingFinUserCountLbl[]=$value->title;
				$trainingFinUserCountValues[]=$value->trainingcount;
			}

			$trainingNotFinUserCountRaw= Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingNotFinUserCount();
			$trainingNotFinUserCountLbl=array();
			$trainingNotFinUserCountValues=array();
			foreach ($trainingNotFinUserCountRaw as $key => $value) {
				$trainingNotFinUserCountLbl[]=$value->title;
				$trainingNotFinUserCountValues[]=$value->trainingcount;
			}

			$usercounttrainingcountfinraw = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getUsercountTrainingcountFin();
			$usercounttrainingcountfinLbl=array();
			$usercounttrainingcountfinValues=array();
			foreach ($usercounttrainingcountfinraw as $key => $value) {
				$usercounttrainingcountfinLbl[]=$value->usercount;
				$usercounttrainingcountfinValues[]=$value->trainingscount;
			}

			$usercounttrainingcountnotfinraw = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getUsercountTrainingcountNotFin();
			$usercounttrainingcountnotfinLbl=array();
			$usercounttrainingcountnotfinValues=array();
			foreach ($usercounttrainingcountnotfinraw as $key => $value) {
				$usercounttrainingcountnotfinLbl[]=$value->usercount;
				$usercounttrainingcountnotfinValues[]=$value->trainingscount;
			}
            //Bewertung
			$seitenName =array();
			$durchschnitBewertung = array();
			$bewertung = Trainingssystem_Plugin_Database::getInstance()->Bewertungen->getRating();
            foreach ($bewertung as $key => $value) {
                $seitenName[]=$value->pageid." ".$value->post_title;
                $durchschnitBewertung[]=$value->rating;
            }
            //var_dump($bewertung);



			// Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingLektionFinUserCount();
			// Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingLektionNotFinUserCount();

			$countHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countHour();
			$sumHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumHour();
			$countWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countWeekday();
			$sumWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumWeekday();
			$countPageView= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countPageView();
			$sumPageView = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumPageView();
			$countBrowser= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countBrowser();
			$countDeviceType= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countDevice();

			// Setze für leere Labels (Ursache bisher unbekannt) den (Label-)Wert "unbekannt" für die Browser und die Gerätetypen fest
			$countBrowserLength = count($countBrowser['labels']);
			for($i=0;$i<$countBrowserLength; $i++){
				if($countBrowser['labels'][$i] == ""){
					$countBrowser['labels'][$i] = "unbekannt";
				}
			}
			
			$countDeviceTypeLength = count($countDeviceType['labels']);
			for($i=0;$i<$countDeviceTypeLength; $i++){
				if($countDeviceType['labels'][$i] == ""){
					$countDeviceType['labels'][$i] = "unbekannt";
				}
			}

			echo $twig->render('systemstatistics/systemstatistics-all.html',[
				'usercreatedatehour'=>$this->convertToJsonStr($usercreatedateHourraw),
				'usercreatedateday'=> $this->convertToJsonStr($usercreatedateDayraw),
				'usercreatedatemounth'=> $this->convertToJsonStr($usercreatedateMounthraw),
				'lastloginhour'=>$this->convertToJsonStr($lastloginHourraw),
				'lastloginday'=> $this->convertToJsonStr($lastloginDayraw),
				'lastloginmounth'=> $this->convertToJsonStr($lastloginMounthraw),
				'inputhour'=>$this->convertToJsonStr($inputHourraw),
				'inputday'=> $this->convertToJsonStr($inputDayraw),
				'inputmounth'=> $this->convertToJsonStr($inputMounthraw),
				'lektionhour'=>$this->convertToJsonStr($lektionHourraw),
				'lektionday'=> $this->convertToJsonStr($lektionDayraw),
				'lektionmounth'=> $this->convertToJsonStr($lektionMounthraw),
				'trainingfinusercountlbl'=> $this->convertToJsonLBLStr($trainingFinUserCountLbl),
				'trainingfinusercountvalues'=> $this->convertToJsonLBLStr($trainingFinUserCountValues),
				'trainingnotfinusercountlbl'=> $this->convertToJsonLBLStr($trainingNotFinUserCountLbl),
				'trainingnotfinusercountvalues'=> $this->convertToJsonLBLStr($trainingNotFinUserCountValues),
				'usercounttrainingcountfinlbl'=> $this->convertToJsonLBLStr($usercounttrainingcountfinLbl),
				'usercounttrainingcountfinvalues'=> $this->convertToJsonLBLStr($usercounttrainingcountfinValues),
				'usercounttrainingcountnotfinlbl'=> $this->convertToJsonLBLStr($usercounttrainingcountnotfinLbl),
				'usercounttrainingcountnotfinvalues'=> $this->convertToJsonLBLStr($usercounttrainingcountnotfinValues),
				//TODO
				'pageid'=>$this->convertToJsonLBLStr($seitenName),
				'bewertung'=>$this->convertToJsonLBLStr($durchschnitBewertung),
				
				'counthouractive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['labels']),
				'counthouractive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['values']),
				'sumhouractive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['labels']),
				'sumhouractive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['values']),
				'countweekdayactive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['labels']),
				'countweekdayactive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['values']),
				'sumweekdayactive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['labels']),
				'sumweekdayactive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['values']),
				'countpageactive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['labels']),
				'countpageactive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['values']),
				'sumpageactive_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['labels']),
                'sumpageactive_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['values']),
                'countbrowser_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countBrowser['labels']),
                'countbrowser_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countBrowser['values']),
                'countdevicetype_l'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countDeviceType['labels']),
				'countdevicetype_v'=> Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countDeviceType['values']),
				'heading' => $heading,
				]);

			return ob_get_clean();
		} 
		else
		{
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}
	}

	
	function getHour($datearr,$datetime){
		$datetimestr = (new DateTime($datetime))->format('Y-m-d H:00');
		return $this->addArrayTime($datearr,$datetimestr);
	}

	function getDay($datearr,$datetime){
		$datetimestr = (new DateTime($datetime))->format('Y-m-d 00:00');
		return $this->addArrayTime($datearr,$datetimestr);
	}
	
	function getMounth($datearr,$datetime){
		$datetimestr = (new DateTime($datetime))->format('Y-m-01 00:00');
		return $this->addArrayTime($datearr,$datetimestr);
	}

	function addArrayTime($datearr,$datetimestr){
		if(isset($datearr[$datetimestr])){
			$datearr[$datetimestr]=$datearr[$datetimestr]+1;
		}else{
			$datearr[$datetimestr]=1;
		}
		return $datearr;
	}

	public static function convertToJsonStr($dataraw){
		$data =array();
		foreach ($dataraw as $key => $value) {
			$data[] = array('x'=>$key, 'y'=> $value);
		}
		$data = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($data));
		return str_replace("\"","'",$data);
	}

	public static function convertToJsonLBLStr($dataraw){

		$data = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($dataraw));
		return str_replace("\"","'",$data);
	}

	// Methode, um die Datensätze der einzelnen Diagramme für ein gegebenes Intervall zu generieren
	public function setTimePeriod(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}

			$startDate = $_GET['systemstatistikenStartDate'];
			$endDate = $_GET['systemstatistikenEndDate'];
	
			if($startDate === ""){
				$startDate = null;
			}
			else{
				$startDate = $startDate . " 00:00:00";
			}
	
			if($endDate === ""){
				$endDate = null;
			}
			else{
				$endDate = $endDate . " 23:59:59";
			}

			// Auswertung: Anlegen der Nutzer
			$usercreatedateHourraw = array();
			$usercreatedateDayraw = array();
			$usercreatedateMounthraw = array();

			$users = get_users();

			foreach( $users as $user ) {
				$udata = get_userdata( $user->ID );
				
				// Keine Grenzen wurden für das Intervall gewählt
				if($startDate == null && $endDate == null){
					$usercreatedateHourraw =$this->getHour($usercreatedateHourraw,$udata->user_registered);
					$usercreatedateDayraw =$this->getDay($usercreatedateDayraw,$udata->user_registered);
					$usercreatedateMounthraw = $this->getMounth($usercreatedateMounthraw,$udata->user_registered);
				}
				// Nur die untere Grenze wurde für das Intervall angegeben
				else if($startDate != null && $endDate == null){
					if($udata->user_registered >= $startDate){
						$usercreatedateHourraw =$this->getHour($usercreatedateHourraw,$udata->user_registered);
						$usercreatedateDayraw =$this->getDay($usercreatedateDayraw,$udata->user_registered);
						$usercreatedateMounthraw = $this->getMounth($usercreatedateMounthraw,$udata->user_registered);
					}
				}
				// Nur  die obere Grenze wurde für das Intervall angegeben
				else if($startDate == null && $endDate != null){
					if($udata->user_registered <= $endDate){
						$usercreatedateHourraw =$this->getHour($usercreatedateHourraw,$udata->user_registered);
						$usercreatedateDayraw =$this->getDay($usercreatedateDayraw,$udata->user_registered);
						$usercreatedateMounthraw = $this->getMounth($usercreatedateMounthraw,$udata->user_registered);
					}
				}
				// Es wurden beide Grenzen füür das Intervall angegeben
				else if($startDate != null && $endDate != null){
					if($udata->user_registered >= $startDate && $udata->user_registered <= $endDate){
						$usercreatedateHourraw =$this->getHour($usercreatedateHourraw,$udata->user_registered);
						$usercreatedateDayraw =$this->getDay($usercreatedateDayraw,$udata->user_registered);
						$usercreatedateMounthraw = $this->getMounth($usercreatedateMounthraw,$udata->user_registered);
					}
				}
			}

			//Letztes Login der Nutzer auswerten
			$lastloginHourraw = array();
			$lastloginDayraw = array();
			$lastloginMounthraw = array();
			$lastlogin = Trainingssystem_Plugin_Database::getInstance()->LastLoginDao->getAllLastloginInterval($startDate,$endDate);
			
			foreach ($lastlogin as $key => $value) {
			
				$lastloginHourraw = $this->getHour($lastloginHourraw,$value[0]);
				$lastloginDayraw = $this->getDay($lastloginDayraw,$value[0]);
				$lastloginMounthraw = $this->getMounth($lastloginMounthraw,$value[0]);
			}

			//Nutzereingaben auswerten
			$inputHourraw = array();
			$inputDayraw = array();
			$inputMounthraw = array();
			$input = Trainingssystem_Plugin_Database::getInstance()->Formdata->getAllFormdataDates($startDate, $endDate);
			
			foreach ($input as $key => $value) {
			
				$inputHourraw = $this->getHour($inputHourraw,$value[0]);
				$inputDayraw = $this->getDay($inputDayraw,$value[0]);
				$inputMounthraw = $this->getMounth($inputMounthraw,$value[0]);
			}

			//Lektion beendet auswählen auswerten
			$lektionHourraw = array();
			$lektionDayraw = array();
			$lektionMounthraw = array();
			$lektion = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllLektionFinInterval($startDate,$endDate);
			
			foreach ($lektion as $key => $value) {
			
				$lektionHourraw = $this->getHour($lektionHourraw,$value[0]);
				$lektionDayraw = $this->getDay($lektionDayraw,$value[0]);
				$lektionMounthraw = $this->getMounth($lektionMounthraw,$value[0]);
			}

			$usercreatedateHourraw = $this->convertToJsonStr($usercreatedateHourraw);
			$usercreatedateDayraw = $this->convertToJsonStr($usercreatedateDayraw);
			$usercreatedateMounthraw = $this->convertToJsonStr($usercreatedateMounthraw);
			$lastloginHourraw = $this->convertToJsonStr($lastloginHourraw);
			$lastloginDayraw = $this->convertToJsonStr($lastloginDayraw);
			$lastloginMounthraw = $this->convertToJsonStr($lastloginMounthraw);
			$inputHourraw = $this->convertToJsonStr($inputHourraw);
			$inputDayraw = $this->convertToJsonStr($inputDayraw);
			$inputMounthraw = $this->convertToJsonStr($inputMounthraw);
			$lektionHourraw = $this->convertToJsonStr($lektionHourraw);
			$lektionDayraw = $this->convertToJsonStr($lektionDayraw);
			$lektionMounthraw = $this->convertToJsonStr($lektionMounthraw);

			$countHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countHourInterval(null,$startDate, $endDate);
			$sumHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumHourInterval(null,$startDate, $endDate);
			$countWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countWeekdayInterval(null,$startDate, $endDate);
			$sumWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumWeekdayInterval(null,$startDate, $endDate);
			$countPageView= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countPageViewInterval(null,$startDate, $endDate);
			$sumPageView = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumPageViewInterval(null,$startDate, $endDate);
			$countBrowser= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countBrowserInterval(null,$startDate, $endDate);
			$countDeviceType= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countDeviceInterval(null,$startDate, $endDate);

			// Setze für leere Labels (Ursache bisher unbekannt) den (Label-)Wert "unbekannt" für die Browser und die Gerätetypen fest
			$countBrowserLength = count($countBrowser['labels']);
			for($i=0;$i<$countBrowserLength; $i++){
				if($countBrowser['labels'][$i] == ""){
					$countBrowser['labels'][$i] = "unbekannt";
				}
			}

			$countDeviceTypeLength = count($countDeviceType['labels']);
			for($i=0;$i<$countDeviceTypeLength; $i++){
				if($countDeviceType['labels'][$i] == ""){
					$countDeviceType['labels'][$i] = "unbekannt";
				}
			}

			$trainingFinUserCountRaw= Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingFinUserCountInterval($startDate,$endDate);
			$trainingFinUserCountLbl=array();
			$trainingFinUserCountValues=array();
			foreach ($trainingFinUserCountRaw as $key => $value) {
				$trainingFinUserCountLbl[]=$value->title;
				$trainingFinUserCountValues[]=$value->trainingcount;
			}

			$dataArray["usercreatedateHourraw"] = $usercreatedateHourraw;
			$dataArray["usercreatedateDayraw"] = $usercreatedateDayraw;
			$dataArray["usercreatedateMounthraw"] = $usercreatedateMounthraw;

			$dataArray["lastloginHourraw"] = $lastloginHourraw;
			$dataArray["lastloginDayraw"] = $lastloginDayraw;
			$dataArray["lastloginMounthraw"] = $lastloginMounthraw;

			$dataArray["inputHourraw"] = $inputHourraw;
			$dataArray["inputDayraw"] = $inputDayraw;
			$dataArray["inputMounthraw"] = $inputMounthraw;

			$dataArray["lektionHourraw"] = $lektionHourraw;
			$dataArray["lektionDayraw"] = $lektionDayraw;
			$dataArray["lektionMounthraw"] = $lektionMounthraw;

			$dataArray["countHourActive"] = $countHourActive;
			$dataArray["sumHourActive"] = $sumHourActive;
			$dataArray["countWeekdayActive"] = $countWeekdayActive;
			$dataArray["sumWeekdayActive"] = $sumWeekdayActive;
			$dataArray["countPageView"] = $countPageView;
			$dataArray["sumPageView"] = $sumPageView;
			$dataArray["countBrowser"] = $countBrowser;
			$dataArray["countDeviceType"] = $countDeviceType;
			$dataArray["trainingFinUserCountLbl"] = $trainingFinUserCountLbl;
			$dataArray["trainingFinUserCountValues"] = $trainingFinUserCountValues;
			echo json_encode($dataArray);
			


		}
		wp_die();
	}

	public function setRangeOfValuesCountpage(){

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}
			
			$startDate = $_GET['systemstatistikenStartDate'];
			$endDate = $_GET['systemstatistikenEndDate'];

			if($startDate === "" || $startDate === null){
				$startDate = null;
			}
			else{
				$startDate = $startDate . " 00:00:00";
			}
	
			if($endDate === "" || $endDate === null){
				$endDate = null;
			}
			else{
				$endDate = $endDate . " 23:59:59";
			}
			
			$startValueCountpage = $_GET['startValueCountpage'];
			$endValueCountpage = $_GET['endValueCountpage'];

			if($startValueCountpage == 0){
				$startValueCountpage = null;
			}
			else{
				$startValueCountpage = intval($startValueCountpage);
			}

			if($endValueCountpage == 0){
				$endValueCountpage = null;
			}
			else{
				$endValueCountpage = intval($endValueCountpage);
			}

			if(isset($_GET['userid'])){
				$userid = $_GET['userid'];
			}
			else{
				$userid = null;
			}
			
			$countPageView= Trainingssystem_Plugin_Database::getInstance()->UserLogs->countPageViewRangeOfValues($userid,$startDate, $endDate,$startValueCountpage,$endValueCountpage);
			
			echo json_encode($countPageView);
		}

		wp_die();
	}

	public function setRangeOfValuesSumpage(){

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}
			
			$startDate = $_GET['systemstatistikenStartDate'];
			$endDate = $_GET['systemstatistikenEndDate'];

			if($startDate === "" || $startDate === null){
				$startDate = null;
			}
			else{
				$startDate = $startDate . " 00:00:00";
			}
	
			if($endDate === "" || $endDate === null){
				$endDate = null;
			}
			else{
				$endDate = $endDate . " 23:59:59";
			}
			
			$startValueSumpage = $_GET['startValueSumpage'];
			$endValueSumpage = $_GET['endValueSumpage'];

			if($startValueSumpage == 0){
				$startValueSumpage = null;
			}
			else{
				$startValueSumpage = intval($startValueSumpage);
			}

			if($endValueSumpage ==0){
				$endValueSumpage = null;
			}
			else{
				$endValueSumpage = intval($endValueSumpage);
			}

			if(isset($_GET['userid'])){
				$userid = $_GET['userid'];
			}
			else{
				$userid = null;
			}
			
			$sumPageView= Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumPageViewRangeOfValues($userid,$startDate, $endDate,$startValueSumpage,$endValueSumpage);

			echo json_encode($sumPageView);
		}

		wp_die();
	}

	public function generateLoginHistory(){

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}
		
			$loginHistoryRaw = Trainingssystem_Plugin_Database::getInstance()->UserEvent->getLoginHistory();
			$loginHistory = $this->convertLoginHistoryToJsonStr($loginHistoryRaw);
			echo $loginHistory;
		}

		wp_die();

	}

	public static function convertLoginHistoryToJsonStr($dataraw){
		$data =array();
		$datarawLength = count($dataraw);
		for($i=0; $i<$datarawLength; $i++){
			$loginDate = (new DateTime($dataraw[$i][2]))->format('H:i:s');
			$data[] = array('user_login'=>$dataraw[$i][0], 'user_id'=> $dataraw[$i][1], 'ldate' =>$loginDate);
		}
		$data = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($data));
		return str_replace("\"","'",$data);
	}

	public function reset(){

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("systemstatistiken"))
		{

			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}
		
			Trainingssystem_Plugin_Database::getInstance()->UserLogs->resetUserLogs();
			echo '1';
		}

		wp_die();
	}

}
