<?php
/**
 * Dashboard
 * 
 * @author      Helge Nissen <helge.nissen@th-luebeck.de> 
 *              Max Sternitzke <max.sternitzke@th-luebeck.de>
 * 				Tim Mallwitz  <tim.mallwitz@th-luebeck.de>
 *              
 * @package     Dashboard
 */

class Trainingssystem_Plugin_Module_Dashboard {


	public function __construct() {

	}

	/**
	 * Funktion zeigt das Dashboard mit Informationen und Inhalten aus den Einstellungen an
	 *
	 * @since    2.3.7
	 */
	public function showDashboard($atts)
	{
		if(!is_array($atts)) {
			$atts = [];
		}

		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
		$userid = Trainingssystem_Plugin_Public::getTrainingUser();

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

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

			$current_user = get_user_by( "id", Trainingssystem_Plugin_Public::getTrainingUser());
			$isDemoUser = get_user_meta($userid, 'demo_user', true);

			$trainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userid);

			/** Infotext, wenn der User frisch angemeldet ist, er/sie noch keine Trainings hat und das Dashboard erst wenige Inhalte hat
			 * - holt Text aus den Einstellungen
			 * - holt URL zu Teilnahmebedingungen aus den Einstellungen
			 */
			$no_trainings_text_dashboard = "";
			if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['no_trainings_text_dashboard'])){
				$no_trainings_text_dashboard = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['no_trainings_text_dashboard'];
			}
			
			$privacy_terms_URL = "";
			if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'])){
				$privacy_terms_URL = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'];
			}

			$dashboard_hide_notrainings = false;
			if(!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['dashboard_hide_notrainings'])){
				$dashboard_hide_notrainings = true;
			}

			$items = array();
			if(isset($settings['dashboard_items']) && is_array($settings['dashboard_items'])) {
				foreach($settings['dashboard_items'] as $index => $i) {
					$items[$index] = $i;
					$items[$index]['content'] = do_shortcode($i['content']);
				}
			}

			return $twig->render("dashboard/dashboard.html", [
											"current_user" => $current_user,
											"trainings" => $trainings,
											"no_trainings_text_dashboard" => $no_trainings_text_dashboard,
											"dashboard_hide_notrainings" => $dashboard_hide_notrainings,
											"privacy_terms_URL" => $privacy_terms_URL,
											"items" => $items,
											"settings_url" => get_admin_url(null, "options-general.php?page=trainingssystem-setting-admin"),
											"isDemoUser" => $isDemoUser,
			]);
		}
	}

	/**
	 * DASHBOARD-ITEM 
	 * Checks
	 */
	public function showCheckDashboardItem($checkatts) {
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		
		$lastCheckResultsURL = "";
		if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['check_results'])){
			$lastCheckResultsURL = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['check_results']);
		}

		// Standard-Werte für Titel und Limit
		if(!isset($checkatts['titel'])) {
			$checkatts['titel'] = '';
		}
		if(!isset($checkatts['latest-limit-each'])) {
			$checkatts['latest-limit-each'] = '1';
		}

		$defaultErrorSubject = "Check-Ergebnisse";
		if(isset($checkatts['defaulterrorsubject'])) {
			$defaultErrorSubject = $checkatts['defaulterrorsubject'];
		}

		// Shortcode-String zusammenbauen
		$checkshortcode_string = "[tspv2_check_result_chart ";
		foreach($checkatts as $key => $value) {
			$checkshortcode_string .= $key . "='" . $value . "' ";
		}
		$checkshortcode_string .= "]";

		// Zusätzlichen Infotext nur anzeigen, wenn Arbeitsplatz- und Gesundheits-Ergebnisse ausgegeben werden
		if (str_contains($checkshortcode_string, 'arbeitsplatz') && str_contains($checkshortcode_string, 'gesundheit')) {
			$info = true;
		} else {
			$info = false;
		}

		//Gibt es Ergebnisse?  
		$checkResults = do_shortcode($checkshortcode_string);
		if (str_contains($checkResults, 'alert-info')) {
			$checkResults = false;
		}

		return $twig->render("dashboard/dashboard-item-checks.html", [
			"info" => $info,
			"checkResults" => $checkResults,
			"lastCheckResultsURL" => $lastCheckResultsURL,
			"defaultErrorSubject" => $defaultErrorSubject,
		]);
	}

	/**
	 * DASHBOARD-ITEM 
	 * Mitteilungen
	 * - Info über neue Inhalte (Trainings, Befragungen)
	 * - Neue Ergebnisse aus Befragungen für Rolle boss. Parameter boss_ids_c, boss_pages_c, boss_pages_s, boss_ids_s aus dem Shortcode
	 * - Neue Inhalte für Rolle kAdmin. Parameter kadmin_ids_c, kadmin_pages_c, kadmin_pages_s, kadmin_ids_s aus dem Shortcode
	 * - Neue Nachrichten
	 */
	public function showMessageDashboardItem($atts) {

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		$current_user = get_user_by( "id", Trainingssystem_Plugin_Public::getTrainingUser());
		$trainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($current_user->ID);
		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

		$defaultErrorSubject = "Mitteilungen";
		if(isset($atts['defaulterrorsubject'])) {
			$defaultErrorSubject = $atts['defaulterrorsubject'];
		}

		$unread_messages = Trainingssystem_Plugin_Database::getInstance()->NachrichtenDao->getUnreadMessagesByUser($current_user->ID);
				
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nachrichtennew") || !empty(get_user_meta( get_current_user_id(), 'coachid' , true )) ) {
			$mailboxurl = get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"]);
		}else{
			$mailboxurl = 0;
		}
			
		// Check new Content
		$usersToCheck = array();
		$bossUsers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getUsersByBossId($current_user->ID);
		$kadminUsers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllUserIdsByCreaterId($current_user->ID);
		
		$allTrainingseiten = Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getAllTrainingseiten();
		$trainingIds = array();
		foreach($trainings as $t){
			$trainingIds[] = $t->getId();
		}
		
		$newContent_boss = array();
		$newContent_kadmin = array();
		$newSurveyResults_boss = array();
		$newSurveyResults_kadmin = array();

		// Informationen für Rolle boss holen:
		if(!empty($bossUsers)){

			$pagesToCheck_boss_c = array();
			$formsToCheck_boss_c = array();

			$usersToCheck = $bossUsers;
			if(isset($atts['boss_pages_c'])){
				$bossPages = explode(",",$atts['boss_pages_c']);
				foreach($bossPages as $bossPage){
					$pagesToCheck_boss_c[] = trim($bossPage);
				}
			}

			if(isset($atts['boss_ids_c'])){
				$bossIds = explode("|", $atts['boss_ids_c']);
				foreach($bossIds as $bIds){
					$bossIdsPage = explode(",",$bIds);

					$formsBoss = array();
					foreach($bossIdsPage as $bIdsPage){
						$formsBoss[] = trim($bIdsPage);
					}

					$formsToCheck_boss_c[] = $formsBoss;
				}
			}

			for($pIndex = 0; $pIndex < count($pagesToCheck_boss_c); $pIndex++){
				$newResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewContent($usersToCheck, $formsToCheck_boss_c[$pIndex], $pagesToCheck_boss_c[$pIndex]);
				if(!empty($newResults)){

					foreach($allTrainingseiten as $trainingseite){
						if($pagesToCheck_boss_c[$pIndex] == $trainingseite->getId()){
							if(in_array($trainingseite->getTrainingid(), $trainingIds)){
								$newContent_boss[] = $trainingseite;
							}
						}
					}
				}
			}

			$pagesToCheck_boss_s = array();
			$formsToCheck_boss_s = array();

			$usersToCheck = $bossUsers;
			if(isset($atts['boss_pages_s'])){
				$bossPages = explode(",",$atts['boss_pages_s']);
				foreach($bossPages as $bossPage){
					$pagesToCheck_boss_s[] = trim($bossPage);
				}
			}

			if(isset($atts['boss_ids_s'])){
				$bossIds = explode("|", $atts['boss_ids_s']);
				foreach($bossIds as $bIds){
					$bossIdsPage = explode(",",$bIds);

					$formsBoss = array();
					foreach($bossIdsPage as $bIdsPage){
						$formsBoss[] = trim($bIdsPage);
					}

					$formsToCheck_boss_s[] = $formsBoss;
				}
			}

			for($pIndex = 0; $pIndex < count($pagesToCheck_boss_s); $pIndex++){
				$newResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewSurveyResults($usersToCheck, $formsToCheck_boss_s[$pIndex], $pagesToCheck_boss_s[$pIndex]);
				if(!empty($newResults)){

					foreach($allTrainingseiten as $trainingseite){
						if($pagesToCheck_boss_s[$pIndex] == $trainingseite->getId()){
							if(in_array($trainingseite->getTrainingid(), $trainingIds)){
								$newSurveyResults_boss[] = $trainingseite;
							}
						}
					}
				}
			}
		}

		// Informationen für Rolle kadmin holen:
		if(!empty($kadminUsers)){

			$pagesToCheck_kadmin_c = array();
			$formsToCheck_kadmin_c = array();

			$usersToCheck = $kadminUsers;
			if(isset($atts['kadmin_pages_c'])){
				$kadminPages = explode(",",$atts['kadmin_pages_c']);
				foreach($kadminPages as $kadminPage){
					$pagesToCheck_kadmin_c[] = trim($kadminPage);
				}
			}

			if(isset($atts['kadmin_ids_c'])){
				$kadminIds = explode("|", $atts['kadmin_ids_c']);
				foreach($kadminIds as $kIds){
					$kadminIdsPage = explode(",",$kIds);

					$formsKadmin = array();
					foreach($kadminIdsPage as $kIdsPage){
						$formsKadmin[] = trim($kIdsPage);
					}

					$formsToCheck_kadmin_c[] = $formsKadmin;
				}
			}

			for($pIndex = 0; $pIndex < count($pagesToCheck_kadmin_c); $pIndex++){
				$newResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewContent($usersToCheck, $formsToCheck_kadmin_c[$pIndex], $pagesToCheck_kadmin_c[$pIndex]);
				if(!empty($newResults)){

					foreach($allTrainingseiten as $trainingseite){
						if($pagesToCheck_kadmin_c[$pIndex] == $trainingseite->getId()){
							if(in_array($trainingseite->getTrainingid(), $trainingIds)){
								$newContent_kadmin[] = $trainingseite;
							}
						}
					}
				}
			}

			$pagesToCheck_kadmin_s = array();
			$formsToCheck_kadmin_s = array();

			$usersToCheck = $kadminUsers;
			if(isset($atts['kadmin_pages_s'])){
				$kadminPages = explode(",",$atts['kadmin_pages_s']);
				foreach($kadminPages as $kadminPage){
					$pagesToCheck_kadmin_s[] = trim($kadminPage);
				}
			}

			if(isset($atts['kadmin_ids_s'])){
				$kadminIds = explode("|", $atts['kadmin_ids_s']);
				foreach($kadminIds as $kIds){
					$kadminIdsPage = explode(",",$kIds);

					$formsKadmin = array();
					foreach($kadminIdsPage as $bIdsPage){
						$formsKadmin[] = trim($bIdsPage);
					}

					$formsToCheck_kadmin_s[] = $formsKadmin;
				}
			}

			for($pIndex = 0; $pIndex < count($pagesToCheck_kadmin_s); $pIndex++){
				$newResults = Trainingssystem_Plugin_Database::getInstance()->Formdata->checkNewSurveyResults($usersToCheck, $formsToCheck_kadmin_s[$pIndex], $pagesToCheck_kadmin_s[$pIndex]);
				if(!empty($newResults)){

					foreach($allTrainingseiten as $trainingseite){
						if($pagesToCheck_kadmin_s[$pIndex] == $trainingseite->getId()){
							if(in_array($trainingseite->getTrainingid(), $trainingIds)){
								$newSurveyResults_kadmin[] = $trainingseite;
							}
						}
					}
				}
			}
		}

		// Informationen für User zu neuen Trainings / Befragungen:
		$trainingsLastUpdate = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingLastUpdateByUserid($current_user->ID);
		$lastActivityBeforeLastLogin = Trainingssystem_Plugin_Database::getInstance()->UserLogs->getLastActivityBeforeLastLogin($current_user->ID);
		$newTrainings = array();
		$newTrainingsNotificationHours = 24;
		$newTrainingsNotificationSeconds = $newTrainingsNotificationHours*3600;

		$canSeeHiddenTrainings = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden");

		foreach($trainings as $t){
			if($t->getFin() == 0 && ($t->trainingEnabled()) || !$t->trainingEnabled() && $canSeeHiddenTrainings){
				if(is_null($trainingsLastUpdate[$t->getId()])){
					$newTrainings[] = $t;
				}
				else{

					if($lastActivityBeforeLastLogin <= $trainingsLastUpdate[$t->getId()]){
						$newTrainings[] = $t;
					}
					else{
						if(strtotime($lastActivityBeforeLastLogin)-strtotime($trainingsLastUpdate[$t->getId()])<= $newTrainingsNotificationSeconds){
							$newTrainings[] = $t;
						}
					}
				}
			}
		}

		$hasNewTrainings = false;
		if(!empty($newTrainings)){
			$hasNewTrainings = true;
		}

		$dashboard_add_name_profile_setting = false;
			if(!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['dashboard_add_name_profile'])){
				$dashboard_add_name_profile_setting = true;
		}

		$showAddNameInProfileMessage = false;
		if($dashboard_add_name_profile_setting){
			if($current_user->first_name == "" || $current_user->last_name == ""){
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("boss")){
					$showAddNameInProfileMessage = true;
				}
	
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("kAdmin")){
					$showAddNameInProfileMessage = true;
				}
				
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("teamLeader")){
					$showAddNameInProfileMessage = true;
				}
			}
		}
		
		return $twig->render("dashboard/dashboard-item-message.html", [
			"mailboxurl" => $mailboxurl,
			'is_boss' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("boss"),
			'is_kAdmin' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("kAdmin"),
			'is_teamLeader' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->userHasRole("teamLeader"),
			"unread_messages" => $unread_messages, 
			"newContent_boss" => $newContent_boss,
			"newContent_kadmin" => $newContent_kadmin,
			"newSurveyResults_boss" => $newSurveyResults_boss,
			"newSurveyResults_kadmin" => $newSurveyResults_kadmin,
			"profile_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]),
			'newTrainings' => $newTrainings,
			'hasNewTrainings' => $hasNewTrainings,
			"defaultErrorSubject" => $defaultErrorSubject,
			"showAddNameInProfileMessage" => $showAddNameInProfileMessage,
			'canSeeHiddenTrainings' => $canSeeHiddenTrainings,
		]);
	}
	
	/**
	 * DASHBOARD-ITEM 
	 * Favoriten
	 */
	public function showFavoriteExerciseDashboardItem($atts) {

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		$current_user = get_user_by( "id", Trainingssystem_Plugin_Public::getTrainingUser());

		$orderby= 'date_asc';
		if(isset($atts['orderby']) && isset(Trainingssystem_Plugin_Database_Exercise_Daoimple::$availableOrders[$atts['orderby']])) {
			$oderby = $atts['orderby'];
		}
		$favoriteExercises = Trainingssystem_Plugin_Database::getInstance()->Exercise->getFavoriteExerciseByUser($current_user->ID, $orderby);

		$defaultErrorSubject = "Favoriten";
		if(isset($atts['defaulterrorsubject'])) {
			$defaultErrorSubject = $atts['defaulterrorsubject'];
		}

		// Erweiterungen: optionale Parameter
		$selectMode = 'none';
		if(isset($atts['select']) && in_array($atts['select'], ['none', 'single', 'multiple'])) {
			$selectMode = $atts['select'];
		}

		$formId = null;
		if(isset($atts['id']) && is_numeric($atts['id'])) {
			$formId = intval($atts['id']);
		}

		$urlButton = false;
		if(isset($atts['url_button']) && (trim($atts['url_button']) === '1' || strtolower(trim($atts['url_button'])) === 'true')) {
			$urlButton = true;
		}

		// Falls ein Formular angegeben ist, rendere es (wird später hidden ausgegeben)
		$formHtml = null;
		if(!is_null($formId)) {
			$formHtml = do_shortcode('[ts_forms id="' . $formId . '"]');
		}

		// Eindeutige Block-ID für JS-Scope
		try {
			$blockId = bin2hex(random_bytes(8));
		} catch (Exception $e) {
			$blockId = uniqid();
		}

		return $twig->render("dashboard/dashboard-item-favorite-exercises.html", [
			"favoriteExercises" => $favoriteExercises,
			"defaultErrorSubject" => $defaultErrorSubject,
			"selectMode" => $selectMode,
			"formId" => $formId,
			"urlButton" => $urlButton,
			"blockId" => $blockId,
			"formHtml" => $formHtml,
		]);
	}

	/**
	 * DASHBOARD-ITEM 
	 * Fortschritt
	 */
	public function showProgressDashboardItem($atts) {

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		$current_user = get_user_by( "id", Trainingssystem_Plugin_Public::getTrainingUser());
		$trainingdata = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($current_user->ID);
		$notrainings = true;
		$canSeeHiddenTrainings = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden");

		$defaultErrorSubject = "Trainings in Bearbeitung";
		if(isset($atts['defaulterrorsubject'])) {
			$defaultErrorSubject = $atts['defaulterrorsubject'];
		}

		$showalltrainings = false;
        if(isset($atts['showalltrainings']) && trim($atts['showalltrainings']) != "" && $atts['showalltrainings'] == "true") {
            $showalltrainings = true;
        } elseif(isset($atts['showalltrainings'])) {
			$showalltrainings = null;
		}

		$category = null;
        $category_text = null;
        $showCategoryName = true;

		if(isset($atts['category']) && trim($atts['category']) != "") {
            $category = $atts['category'];

            if(isset($atts['category_text']) && trim($atts['category_text']) != "") {
                $category_text = $atts['category_text'];
            }

            if(isset($atts['show_category_name']) && (trim($atts['show_category_name']) == "0" || trim($atts['show_category_name']) == "false")){
                $showCategoryName = false;
            }
        }

        $groupbycategories = false;
        if(isset($atts['grouped']) && (trim($atts['grouped']) == "1" || trim($atts['grouped']) == "true")) {
            $groupbycategories = true;
        }

		$exclude = array();
		if(isset($atts['exclude']) && trim($atts['exclude']) != "") {
			$excludeAtts = explode("|",$atts['exclude']);
			foreach($excludeAtts as $excludeAtt){
				$exclude[] = trim($excludeAtt);
			}
		}
 
		$trainings_grouped = array();
		if($category != null) {
			$trainings_grouped[0] = array();
			$trainings_grouped[0]['name'] = $category;
			$trainings_grouped[0]['trainings'] = array();
			foreach($trainingdata as $training) {
				if($training->hasCategory($category) && ($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings)) {
					if($showalltrainings){
						$trainings_grouped[0]['trainings'][] = $training;
						$notrainings = false;
					}
					else{
						if(($training->getFin() >0) && ($training->getFin()<100)){
							$trainings_grouped[0]['trainings'][] = $training;
							$notrainings = false;
						}
					}
					
				}
			}
		} else if($groupbycategories) {
			$nocategories = array();
			foreach($trainingdata as $training) {
				$excludeTraining = false;
				foreach($training->getCategories() as $trainingCat){
					if(in_array($trainingCat, $exclude)){
						$excludeTraining = true;
					}
				}
				if(!$excludeTraining && ($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings)){
					$cat = $training->getCategories();
					if(sizeof($cat) > 0) {
						foreach($cat as $tr_cat) {
							
							$groupedindex = null;
							foreach($trainings_grouped as $key => $t) {
								if($t['name'] == $tr_cat) {
									$groupedindex = $key;
									break;
								}
							}

							if($groupedindex !== null) {
								if($showalltrainings){
									$trainings_grouped[$groupedindex]['trainings'][] = $training;
									$notrainings = false;
								}
								else{
									if(($training->getFin() >0) && ($training->getFin()<100)){
										$trainings_grouped[$groupedindex]['trainings'][] = $training;
										$notrainings = false;
									}
								}
							} else {
								$index = sizeof($trainings_grouped);
								$trainings_grouped[$index] = array();
								$trainings_grouped[$index]['name'] = $tr_cat;
								$trainings_grouped[$index]['trainings'] = array();
								
								if($showalltrainings){
									$trainings_grouped[$index]['trainings'][] = $training;
									$notrainings = false;
								}
								else{
									if(($training->getFin() >0) && ($training->getFin()<100)){
										$trainings_grouped[$index]['trainings'][] = $training;
										$notrainings = false;
									}
								}
							}
						}
					} else {
						$nocategories[] = $training;
					}
				}
			}

			if(sizeof($nocategories) > 0) {
				$nocatindex = sizeof($trainings_grouped);
				$trainings_grouped[$nocatindex] = array();
				$trainings_grouped[$nocatindex]['name'] = "Sonstige";
				$trainings_grouped[$nocatindex]['trainings'] = array();

				foreach($nocategories as $nocategoriesTraining){
					if($showalltrainings){
						$trainings_grouped[$nocatindex]['trainings'][] = $nocategoriesTraining;
						$notrainings = false;
					}
					else{
						if(($nocategoriesTraining->getFin() >0) && ($nocategoriesTraining->getFin()<100)){
							$trainings_grouped[$nocatindex]['trainings'][] = $nocategoriesTraining;
							$notrainings = false;
						}
					}
				}
			}
		} else {
			$trainingdata_filtered = [];
			foreach($trainingdata as $training) {
				if($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings) {
					if($showalltrainings){
						$trainingdata_filtered[] = $training;
						$notrainings = false;
					}
					else{
						if(($training->getFin() >0) && ($training->getFin()<100)){
							$trainingdata_filtered[] = $training;
							$notrainings = false;
						}
					}
				}
			}
			$trainings_grouped[0] = array();
			$trainings_grouped[0]['name'] = "";
			$trainings_grouped[0]['trainings'] = $trainingdata_filtered;
		}

		$showLektionslisteArray = array();
        $showResumeOptionArray = array();
        foreach($trainingdata as $t){
            $showLektionslisteMeta = get_post_meta($t->getId(), 'showLektionsliste', false);
            if(!empty($showLektionslisteMeta)){
                $showLektionslisteArray[$t->getId()] = $showLektionslisteMeta[0];
            }
            else{
                $showLektionslisteArray[$t->getId()] = "1";
            }

            $showResumeOptionMeta = get_post_meta($t->getId(), 'showResumeOption', false);
            if(!empty($showResumeOptionMeta)){
                $showResumeOptionArray[$t->getId()] = $showResumeOptionMeta[0];
            }
            else{
                $showResumeOptionArray[$t->getId()] = "1";
            }
        }
        foreach($trainings_grouped as $category) {
            foreach($category['trainings'] as $t) {
                if(isset($showLektionslisteArray[$t->getId()])) {
                    $t->setShowLektionsliste($showLektionslisteArray[$t->getId()]);
                }

                if(isset($showResumeOptionArray[$t->getId()])) {
                    $t->setShowResumeOption($showResumeOptionArray[$t->getId()]);
                }
            }
        }

		return $twig->render("dashboard/dashboard-item-progress.html", [
			"trainings" => $trainings_grouped,
			"defaultErrorSubject" => $defaultErrorSubject,
			"showalltrainings" => $showalltrainings,
			"category_text" => $category_text,
            "show_category_name" => $showCategoryName,
			'canSeeHiddenTrainings' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden"),
			"notrainings" => $notrainings
		]);
	}

	/**
	 * DASHBOARD-ITEM 
	 * Fortschritt Card / Badges und Zertifikate Card
	 * - holt Trainingsfortschritt 
	 * - holt Badges
	 * - holt Zertifikate	
	 */
	public function showCertDashboardItem($atts) {

		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		$current_user = get_user_by( "id", Trainingssystem_Plugin_Public::getTrainingUser());
		$isDemoUser = get_user_meta($current_user->ID, 'demo_user', true);
		$trainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($current_user->ID);

		$trainingIDs = array();
		$certificates = array();
	
		$defaultErrorSubject = "Abzeichen";
		if(isset($atts['defaulterrorsubject'])) {
			$defaultErrorSubject = $atts['defaulterrorsubject'];
		}

		$show_certificate_title = false;
		if(isset($atts['show_certificate_title']) && (trim($atts['show_certificate_title']) == "1" || trim($atts['show_certificate_title']) == "true")) {
            $show_certificate_title = true;
        }

		$show_certificate_download = true;
		if(isset($atts['show_certificate_download']) && (trim($atts['show_certificate_download']) == "0" || trim($atts['show_certificate_download']) == "false")) {
            $show_certificate_download = false;
        }

		// Badges | Certificates
		//Code aus module-abzeichen.php:
		$posts = get_posts([
			'post_type' => 'abzeichen',
			'post_status' => 'publish',
			'numberposts' => -1
			]);

		$outputarrTemp = array();
		$allCertificates = Trainingssystem_Plugin_Database::getInstance()->Certificate->getAllCertificates();
		
		foreach($trainings as $t){
			$trainingIDs[] = $t->getID();
		}
		foreach($allCertificates as $c){
			if(in_array($c->getTraining_id(), $trainingIDs)){
				$certificates[$c->getTraining_id()][] =$c;
			}
		}
		
		$postCerts = get_posts([
			'post_type' => 'zertifikate',
			'post_status' => 'publish',
			'numberposts' => -1
			// 'order'    => 'ASC'
		]);

		$certFindates = array();
		foreach($postCerts as $postCert){
			$certFindates[$postCert->ID] = $postCert->post_date;
		}
		
		foreach($posts as $abzeichen){
			$abzeichentrainingid = get_post_meta($abzeichen->ID,"training_dropdown",true);
			$abzeichenHasLektionsabzeichen = get_post_meta($abzeichen->ID, 'hasLektionsabzeichen', true) == "1";
			$abzeichenCountLektionsabzeichen = get_post_meta($abzeichen->ID,"countLektionsabzeichen",true);
			$abzeichenLektionsabzeichenStr = get_post_meta($abzeichen->ID, 'lektionsabzeichen', true);
			$abzeichenLektionsabzeichen = json_decode($abzeichenLektionsabzeichenStr, true);
			foreach($trainings as $training){
				if($training->getFin() == 100){
					if($abzeichentrainingid==$training->getID()){
						$outputTraining = array();
						$outputTraining['title'] = $training->getTitle();
						$outputTraining['id'] = $training->getID();
						$image = wp_get_attachment_image_src( get_post_thumbnail_id( $abzeichen->ID ), 'single-post-thumbnail' );
						if(!$image){
							$image = $training->getImageUrl();
						}
						else{
							$image = $image[0];
						}
						$outputTraining['imageurl'] = $image;
						$outputTraining['fin'] = $training->getFin();
						$lektionsliste = $training->getLektionsliste();
						$outputLektionsliste = array();
						foreach($lektionsliste as $lektion){
							$outputLektion = array();
							$outputLektion['title'] = $lektion->getTitle();
							$outputLektion['fin'] = $lektion->getFin();
							$outputLektion['findate'] = $lektion->getFindate();
							$outputLektion['complete_image_url'] = "";
							$outputLektion['incomplete_image_url'] = "";
							if(isset($abzeichenLektionsabzeichen[$lektion->getId()])){
								$lektionabzeichenImages = $abzeichenLektionsabzeichen[$lektion->getId()];
								$outputLektion['complete_image_url'] = $lektionabzeichenImages['lektionsabzeichenCompleteURL'];
								$outputLektion['incomplete_image_url'] = $lektionabzeichenImages['lektionsabzeichenIncompleteURL'];
							}
							
							$outputLektionsliste[] = $outputLektion;
						}
						$outputTraining['lektionsliste'] = $outputLektionsliste;
						$outputTraining['hasLektionsabzeichen'] = $abzeichenHasLektionsabzeichen;
						$outputTraining['countLektionsabzeichen'] = $abzeichenCountLektionsabzeichen;
						$outputarrTemp[] = $outputTraining; 
					}
				}
			}
		}

		$outputarr = array();
		foreach($outputarrTemp as $training){
			if($training['fin'] >= 100){
				$training['zertifikat'] = $certificates[$training['id']];
				$trainingLektionen = $training['lektionsliste'];
				$maxDate = "1970-01-01";
				foreach($trainingLektionen as $trainingLektion){								
					if(!is_null($trainingLektion['findate'])){
						if($maxDate < $trainingLektion['findate']){
							$maxDate = $trainingLektion['findate'];
						}
					}
				}
				if($maxDate != "1970-01-01"){
					foreach($certificates[$training['id']] as $certificate){
						$certFindates[$certificate->getCertificate_id()] = $maxDate;
					}
				}
			}

			
			$outputarr[] = $training;
		}

		// Prüfen, ob der User mindestens ein Training fertiggestellt hat.
		$has_abzeichen = false;
		for($i = 0; $i < count($outputarr); $i++){
			if($outputarr[$i]['fin'] == 100){
				$has_abzeichen = true; 
			}
		}

		return $twig->render("dashboard/dashboard-item-certs.html", [
			"current_user" => $current_user,
			"abzeichen" => $outputarr,
			"has_abzeichen" => $has_abzeichen,
			"certFindates" => $certFindates,
			"show_certificate_title" => $show_certificate_title,
			"show_certificate_download" => $show_certificate_download,
			"defaultErrorSubject" => $defaultErrorSubject,
			"profile_link" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]),
			"isDemoUser" => $isDemoUser
		]);
	}
}
