<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Coach_User_Remover
 * @subpackage Coach_User_Remover/admin
 */

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

	private static $trainingModes = [0, 1, 2];
	private static $depTimeValues = [0, 1, 2, 3, 4, 5, 6];
	private static $depTimeMultiplierValues = ["hours", "days", "weeks", "months"];

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		add_action('wp', array($this, 'maybe_assign_trainings'));

		add_action('tspv2_trainings_mgr_assign_trainings', array($this, 'assignTrainingsDate'));
		add_action(TRAININGSSYSTEM_PLUGIN_ACTION_TRAINING_FIN, array($this, 'check_for_dependent_trainings'), 10, 3);
	}

	public function maybe_assign_trainings()
	{
		if (!wp_next_scheduled('tspv2_trainings_mgr_assign_trainings')) {
			wp_schedule_event(current_time('timestamp'), 'hourly', 'tspv2_trainings_mgr_assign_trainings');
		}
	}

	public function coach_nutzer($atts){

		$heading = isset($atts['titel']) ? $atts['titel'] : 'Trainingszuweisung'; 

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


			$nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG.'submit';
			$noncefield = 'teststring';

			$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()]);
			}else{
				$userid = Trainingssystem_Plugin_Public::getTrainingUser();
				$alltrainings=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
				$allusers=Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllNutzer(false, false, false);

				$studiengruppen = array();
				$sg_users = get_users(array("meta_key" => 'studiengruppenid'));
				foreach($sg_users as $sg_u) {
					if(!isset($studiengruppen[$sg_u->studiengruppenid]) && trim($sg_u->studiengruppenid) != "") {
						$studiengruppen[$sg_u->studiengruppenid] = array();
					}
					if(trim($sg_u->studiengruppenid) != "") {
						$studiengruppen[$sg_u->studiengruppenid][] = $sg_u->ID;
					}
				}

				$company_and_groups = array();
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall")){
					$company_and_groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getCompanyandCompanygroups(true);
				}
				else if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")){
					$company_and_groups = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanyandCompanygroups($current_user->ID, true);
				}
				

				$selectuserid = '';
                $selectusermail= '';
				$selectusername = '';
				$selectstudienid = '';
				$selectstudiengruppenid = '';
				$selectcompany = '';
                if(isset($_POST['formuserid'])) {
                    $formuserid = sanitize_text_field($_POST['formuserid']);
                    $user = get_user_by('id', $formuserid);

                    $selectusermail = $user->user_email;
                    $selectusername = $user->display_name;
					$selectuserid = $user->ID;
					$selectstudienid = get_user_meta($user->ID, 'studienid', true);
					$selectstudiengruppenid = get_user_meta($user->ID, 'studiengruppenid', true);
					foreach($company_and_groups as $company){
						$companygroups = $company['groups'];
						foreach($company['users'] as $groupid => $groupusers){
							if(in_array($selectuserid, $groupusers)){
								$selectcompany = $company['companyname']." - ".$companygroups[$groupid];
							}
						}
					}
                }

				$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
				$global_company_name = "Unternehmen";
				if(trim($settings['user_grouper_name']) != "") {
					$global_company_name = $settings['user_grouper_name'];
				}
				echo $twig->render('coach-user-training-mgr/coach-user-training-mgr.html',[	
					"trainings"=>$alltrainings, 
					"users"=>$allusers, 
					"studiengruppen" => $studiengruppen,
					'selectuserid'=>$selectuserid, 
					'selectusermail' => $selectusermail, 
					'selectusername' =>$selectusername, 
					"selectstudienid" => $selectstudienid, 
					"selectstudiengruppenid" => $selectstudiengruppenid,
					"selectcompany" => $selectcompany,
					'hideMails' => isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']),
					'heading' => $heading,
					'global_company_name' => $global_company_name,
					'companies' => $company_and_groups,
					]);

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

		}

	}

	public function coach_user_training_mgr_gettraining(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
		  if (isset($_POST['trainingid'])) {
				$trainingid=intval(sanitize_text_field($_POST['trainingid']));
				$training=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById($trainingid);
				echo $twig->render('coach-user-training-mgr/coach-user-training-mgr-training.html',["training"=>$training, "coachingmode" => 0, "trainingEnable" => true]);
		  }
		}
		wp_die();
	}

	public function coach_user_training_mgr_gettraining_lektion(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			if (isset($_POST['trainingid'])) {
				$trainingid=intval(sanitize_text_field($_POST['trainingid']));
				$training=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById($trainingid);
				echo $twig->render('coach-user-training-mgr/coach-user-training-mgr-lektion-modal.html',["training"=>$training]);
			}
		}
		wp_die();
	}

	/**
	 * !! CURRENTLY NOT USED !! 
	 * DO NOT USE UNTIL DATE & DEP ADJUSTMENTS ARE MADE!
	 * 
	 * Funtion to reset all user trainings and maybe add new trainings
	 */
	public function coach_user_training_mgr_reset_users_training(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr"))
		{
		  if (isset($_POST['trainings'])&&isset($_POST['users'])) {
				$trainingsids=json_decode(stripslashes(sanitize_text_field($_POST['trainings'])),true);
				$usersids=json_decode(stripslashes(sanitize_text_field($_POST['users'])),true);
				$coachingmodi=json_decode(stripslashes(sanitize_text_field($_POST['coachingmodi'])),true);
				//var_dump($trainingsids);
				//var_dump($usersids);
				foreach ($usersids as $userid){
					Trainingssystem_Plugin_Database::getInstance()->NutzerDao->removeAllTrainings($userid);
					foreach ($trainingsids as $key => $trainingid) {
						Trainingssystem_Plugin_Database::getInstance()->NutzerDao->setTrainingByUserId($userid,$trainingid);
					}

					$usermetaEntryMode = get_user_meta($userid,'coaching_needed',false);
					if(!empty($usermetaEntryMode)){
						$newUsermetaEntry = $coachingmodi;
						$newUsermetaEntryEncoded = json_encode($newUsermetaEntry);
            			update_user_meta($userid, 'coaching_needed', $newUsermetaEntryEncoded);
					}
					else{
						$newUsermetaEntry = json_encode($coachingmodi);
						add_user_meta($userid, 'coaching_needed', $newUsermetaEntry);
					}
				}
			}
		}
		echo "1";
		wp_die();
	}

	/**
	 * Updates the users trainings
	 * 
	 * @return 1 on success, -1 on not unique trainings
	 */
	public function coach_user_training_mgr_save_users_training(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$accessAllowedTrainingMgr = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr");
		$accessAllowedVorlagen = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen");

		$vorlagennutzer = [];
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
		{
			$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
		}
		elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
		{
			$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUserRaw();
		}
		$vorlagennutzerids = count($vorlagennutzer) > 0 ? array_column($vorlagennutzer, 'ID') : [];

		if($accessAllowedTrainingMgr  || $accessAllowedVorlagen)
		{
		  if (isset($_POST['trainings'])&&isset($_POST['users']) && isset($_POST['datetrainings']) && isset($_POST['deptrainings'])) {
				$trainingsids = json_decode(stripslashes(sanitize_text_field($_POST['trainings'])),true);
				$usersids = json_decode(stripslashes(sanitize_text_field($_POST['users'])),true);
				$coachingmodi = json_decode(stripslashes(sanitize_text_field($_POST['coachingmodi'])),true);
				$datetrainings_tmp = json_decode(stripslashes(sanitize_text_field($_POST['datetrainings'])),true);
				$deptrainings_tmp = json_decode(stripslashes(sanitize_text_field($_POST['deptrainings'])),true);
				$redirectTraining = sanitize_text_field($_POST['redirectTraining']);

				$datetrainings = [];
				foreach($datetrainings_tmp as $t) {
					$datetrainings[] = json_decode($t, true);
				}

				$deptrainings = [];
				foreach($deptrainings_tmp as $t) {
					$deptrainings[] = json_decode($t, true);
				}
				
				// Check if every training is only selected once in regular, date and dependent trainings
				$trainings = [];
				$trainingsunique = true;
				foreach($trainingsids as $tid => $t) {
					if(!isset($trainings[$tid])) {
						$trainings[$tid] = $tid;
					} else {
						$trainingsunique = false;
					}
		  		}
				if($trainingsunique) {
					foreach($datetrainings as $t) {
						if(!isset($trainings[$t['trainingId']])) {
							$trainings[$t['trainingId']] = $t['trainingId'];
						} else {
							$trainingsunique = false;
						}
					}	
				}
				if($trainingsunique) {
					foreach($deptrainings as $t) {
						if(!isset($trainings[$t['trainingId']])) {
							$trainings[$t['trainingId']] = $t['trainingId'];
						} else {
							$trainingsunique = false;
						}
					}	
				}

				if($trainingsunique) {
					foreach ($usersids as $userid){
						if($accessAllowedTrainingMgr || 
							($accessAllowedVorlagen && in_array(intval($userid), $vorlagennutzerids))) 
						{
							Trainingssystem_Plugin_Database::getInstance()->NutzerDao->updateTrainingByUserId($userid,$trainingsids);

							if(!Trainingssystem_Plugin_Database::getInstance()->TrainingDate->updateTrainingsDateByUserId($userid, $datetrainings)) {
								echo "error updating date trainings";
							}
							
							if(!Trainingssystem_Plugin_Database::getInstance()->TrainingDep->updateTrainingsDepByUserId($userid, $deptrainings)) {
								echo "error updating dep trainings";
							}
							
							$usermetaEntryMode = get_user_meta($userid,'coaching_needed',false);
							if(!empty($usermetaEntryMode)){
								$newUsermetaEntry = $coachingmodi;
								$newUsermetaEntryEncoded = json_encode($newUsermetaEntry);
								update_user_meta($userid, 'coaching_needed', $newUsermetaEntryEncoded);
							}
							else{
								$newUsermetaEntry = json_encode($coachingmodi);
								add_user_meta($userid, 'coaching_needed', $newUsermetaEntry);
							}

							update_user_meta( $userid, "redirectTraining", $redirectTraining);

							$this->check_for_dependent_trainings(null, null, $userid); // trigger dependent trainings manually
						}
						else
						{
							echo "access denied";
							wp_die();
						}
					}
				} else {
					echo "-1";
					wp_die();
				}
			} else {
				echo "0";
				wp_die();
			}
		}
		echo "1";
		wp_die();
	}

	public function coach_user_training_mgr_gettraining_user(){
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$vorlagennutzer = [];
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
		{
			$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
		}
		elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
		{
			$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUserRaw();
		}
		$vorlagennutzerids = count($vorlagennutzer) > 0 ? array_column($vorlagennutzer, 'ID') : [];

		if(isset($_POST['userid']) && trim($_POST['userid']) != "" && is_numeric($_POST['userid']) && (
			Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || 
			(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen") && in_array(intval($_POST['userid']), $vorlagennutzerids))
			)
		) {
			$userid=intval(sanitize_text_field($_POST['userid']));
			$usertrainings=Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userid);
			$usermetaEntryCoachingModes = get_user_meta($userid,'coaching_needed',false);
			$coachingmodi = array();
			if(!empty($usermetaEntryCoachingModes)){
				$coachingmodiTemp = json_decode($usermetaEntryCoachingModes[0]);
				$coachingmodi = (array)$coachingmodiTemp;
			}
			$alltrainings = $this->getAllTrainingsIndexed();

			$usertrainingsDate = Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getTrainingDateByUser($userid);
			$usertrainingsDep = Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getTrainingDepByUser($userid);

			$usertrainingsWithDate = array();
			foreach($usertrainings as $tmp) {
				$usertrainingsWithDate[] = $tmp;	
			}
			foreach($usertrainingsDate as $tmp) {
				$usertrainingsWithDate[] = $tmp;	
			}
			foreach($usertrainingsDep as $tmp) {
				$usertrainingsWithDate[] = $tmp;	
			}
			
			$delta = array();
			foreach($alltrainings as $at) {
				$found = false;

				foreach($usertrainingsWithDate as $ut) {
					
					if(get_class($ut) == "Trainingssystem_Plugin_Database_Training" && $at->getId() == $ut->getId() ||
						get_class($ut) == "Trainingssystem_Plugin_Database_Training_Date" && $at->getId() == $ut->getTrainingId() ||
						get_class($ut) == "Trainingssystem_Plugin_Database_Training_Dep" && $at->getId() == $ut->getTrainingId() ) {
						$found = true;
						break;					
					}
				}

				if(!$found) {
					$delta[] = $at;
				}
			}

			$redirectTraining = get_user_meta($userid, "redirectTraining", true);
			echo $twig->render('coach-user-training-mgr/coach-user-training-mgr-trainings.html',[
																								"alltrainings" => $alltrainings,
																								"trainings" => $usertrainings,
																								"trainingsdate" => $usertrainingsDate,
																								"trainingsdep" => $usertrainingsDep,
																								"deltatrainings" => $delta,
																								"coachingmodi" => $coachingmodi,
																								"redirectTraining" => $redirectTraining,
																								"is_vorlage" => in_array(intval($_POST['userid']), $vorlagennutzerids),
																							]);
		}
		wp_die();
	}

	/**
	 * Function to create a new date/dep training. Returns the card for the user sortable area
	 * 
	 * @param Array $_POST
	 * 
	 * @return HTML-Code, empty String on failure
	 */
	public function coach_user_training_mgr_create_datedep() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || 
			Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			if(isset($_POST['trainings']) && trim($_POST['trainings']) != "" && trim($_POST['trainings']) != "[]" &&
				isset($_POST['mode']) && ($_POST['mode'] == "date" || $_POST['mode'] == "dependency") &&
				isset($_POST['date_date']) && isset($_POST['dep_time']) && isset($_POST['dep_timemultiplier']) && 
				isset($_POST['dep_trainings']) && isset($_POST['dep_condition'])) {

				$trainingsids = json_decode(stripslashes(sanitize_text_field($_POST['trainings'])),true);
				$deptrainingids = ($_POST['mode'] == "dependency") ? json_decode(stripslashes(sanitize_text_field($_POST['dep_trainings'])),true) : array();
					
				foreach($trainingsids as $t) {
					if(isset($t['tid']) && is_numeric($t['tid']) &&
						isset($t['mode']) && in_array($t['mode'], self::$trainingModes) &&
						isset($t['ecoaching']) && ($t['ecoaching'] == "0" || $t['ecoaching'] == "1") &&
						isset($t['ecoachinglektion']) && isset($t['redirect'])) {

							if($_POST['mode'] == "date" && preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $_POST['date_date'])) {
								
								$element = new Trainingssystem_Plugin_Database_Training_Date(null, $t['tid'], $t['mode'], $t['ecoaching'], ($t['mode'] == 2) ? $t['ecoachinglektion'] : 0, 0, $_POST['date_date'], $t['redirect'], null, null, null);
								echo $twig->render("coach-user-training-mgr/coach-user-training-mgr-training-date.html", [
														"datetraining" => $element, 
														"alltrainings" => $this->getAllTrainingsIndexed(),
														"lockedit" => true,
													]);

							} elseif($_POST['mode'] == "dependency" &&
								is_numeric($_POST['dep_time']) && in_array($_POST['dep_time'], self::$depTimeValues) &&
								in_array($_POST['dep_timemultiplier'], self::$depTimeMultiplierValues) &&
								is_array($deptrainingids) &&
								in_array($_POST['dep_condition'], ["and", "or"])
								) 
							{

								$alltrainings = $this->getAllTrainingsIndexed();

								foreach($deptrainingids as $deptid) {
									if(!isset($alltrainings[$deptid])) {
										wp_die();
									}
								}

								$element = new Trainingssystem_Plugin_Database_Training_Dep(null, $t['tid'], $t['mode'], $t['ecoaching'], ($t['mode'] == 2) ? $t['ecoachinglektion'] : 0, 0, $_POST['dep_time'], $_POST['dep_timemultiplier'], stripslashes(sanitize_text_field($_POST['dep_trainings'])), $_POST['dep_condition'], $t['redirect'], null, null);

								echo $twig->render("coach-user-training-mgr/coach-user-training-mgr-training-dep.html", [
														"deptraining" => $element, 
														"alltrainings" => $this->getAllTrainingsIndexed(),
														"lockedit" => true,
													]);
							}
							
						}
				}

			}
		}
		wp_die();
	}

	/**
	 * Returns the HTML-Code for a date/dep training edit modal
	 * 
	 * @param Array $_POST
	 * 
	 * @return HTML-Code, Empty string on failure
	 */
	public function coach_user_training_mgr_edit_datedep() {
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || 
			Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			if(isset($_POST['trainingdatedepid']) && is_numeric($_POST['trainingdatedepid']) &&
				isset($_POST['type']) && ($_POST['type'] == "date" || $_POST['type'] == "dep")) {
				$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

				if($_POST['type'] == "date") {
					$element = Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getTrainingDate($_POST['trainingdatedepid']);
				} else {
					$element = Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getTrainingDep($_POST['trainingdatedepid']);
				}

				$alltrainings = [];
				$alltrainings_tmp=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
				foreach($alltrainings_tmp as $at) {
					$alltrainings[$at->getId()] = $at;
				}
				
				echo $twig->render("coach-user-training-mgr/coach-user-training-mgr-datedep-edit-modal.html", ["type" => $_POST['type'], "alltrainings" => $alltrainings, "element" => $element]);
			}
		}
		wp_die();
	}

	/**
	 * Returns the changed Card to be displayed in the sortable list
	 * 
	 * @param $_POST-Array
	 * 
	 * @return HTML-Code on succcess, empty String else
	 */
	public function coach_user_training_mgr_change_datedep() {
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr") || 
			Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			if(isset($_POST['modal-datedep-edit-type']) && isset($_POST['trainingdatedepid']) && is_numeric($_POST['trainingdatedepid']) &&
				isset($_POST['modal-datedep-edit-training-id']) && is_numeric($_POST['modal-datedep-edit-training-id']) &&
				isset($_POST['modal-datedep-edit-training-mode']) && in_array($_POST['modal-datedep-edit-training-mode'], self::$trainingModes) && 
				isset($_POST['modal-datedep-edit-extendedecoaching']) && 
				isset($_POST['modal-datedep-edit-training-ecoaching']) && ($_POST['modal-datedep-edit-training-ecoaching'] == "0" || $_POST['modal-datedep-edit-training-ecoaching'] == "1") &&
				isset($_POST['modal-datedep-edit-training-redirect']) && ($_POST['modal-datedep-edit-training-redirect'] == "0" || $_POST['modal-datedep-edit-training-redirect'] == "1") &&
				($_POST['modal-datedep-edit-type'] == "date" && 
					isset($_POST['modal-datedep-edit-dateinput']) && preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $_POST['modal-datedep-edit-dateinput'])) ||
				($_POST['modal-datedep-edit-type'] == "dep" && 
					isset($_POST['modal-datedep-edit-dependency-time']) && in_array($_POST['modal-datedep-edit-dependency-time'], self::$depTimeValues) &&
					isset($_POST['modal-datedep-edit-dependency-timemultiplier']) && in_array($_POST['modal-datedep-edit-dependency-timemultiplier'], self::$depTimeMultiplierValues) &&
					isset($_POST['modal-datedep-edit-dependency-trainings']) && strlen(trim($_POST['modal-datedep-edit-dependency-trainings'])) > 2 && 
					isset($_POST['modal-datedep-edit-dependency-condition']) && in_array($_POST['modal-datedep-edit-dependency-condition'], ["and", "or"]))
			) {

				$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
				
				$lektionSettings = 0;
				if($_POST['modal-datedep-edit-training-mode'] == 2) {
					$lektionSettings = is_array($_POST['modal-datedep-edit-extendedecoaching']) ? json_encode($_POST['modal-datedep-edit-extendedecoaching']) : $_POST['modal-datedep-edit-extendedecoaching'];
				}

				if($_POST['modal-datedep-edit-type'] == "date") {
					$element = new Trainingssystem_Plugin_Database_Training_Date($_POST['trainingdatedepid'], $_POST['modal-datedep-edit-training-id'], $_POST['modal-datedep-edit-training-mode'], $_POST['modal-datedep-edit-training-ecoaching'], $lektionSettings, 0, $_POST['modal-datedep-edit-dateinput'], $_POST['modal-datedep-edit-training-redirect'], null, null);
					echo $twig->render("coach-user-training-mgr/coach-user-training-mgr-training-date.html", [
													"datetraining" => $element, 
													"alltrainings" => $this->getAllTrainingsIndexed(),
													"lockedit" => true,
												]);
				} else {
					$element = new Trainingssystem_Plugin_Database_Training_Dep($_POST['trainingdatedepid'], $_POST['modal-datedep-edit-training-id'], $_POST['modal-datedep-edit-training-mode'], $_POST['modal-datedep-edit-training-ecoaching'], $lektionSettings, 0, $_POST['modal-datedep-edit-dependency-time'], $_POST['modal-datedep-edit-dependency-timemultiplier'], stripslashes(sanitize_text_field($_POST['modal-datedep-edit-dependency-trainings'])), $_POST['modal-datedep-edit-dependency-condition'], $_POST['modal-datedep-edit-training-redirect'], null, null);
					
					echo $twig->render("coach-user-training-mgr/coach-user-training-mgr-training-dep.html", [
						"deptraining" => $element, 
						"alltrainings" => $this->getAllTrainingsIndexed(),
						"lockedit" => true,
					]);
				}
			}
		}
		wp_die();
	}

	/**
	 * Cron-Function:
	 * Assigns trainings at a specific date, called periodically
	 * 
	 */
	public function assignTrainingsDate() {
		$trainings_due = Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getTrainingDateDue();

		if(sizeof($trainings_due) > 0) {

			$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
			$vorlagennutzerids = array_column($vorlagennutzer, 'ID');

			$demouser = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getDemoUserRaw();
			$demouserids = array_column($demouser, 'ID');

			$trainingsAssigned = array();

			$alltrainings = [];
			$alltrainings_tmp = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
			foreach($alltrainings_tmp as $at) {
				$alltrainings[$at->getId()] = $at;
			}

			foreach($trainings_due as $t_due) {

				if(!in_array($t_due->getUserId(), $vorlagennutzerids) && !in_array($t_due->getUserId(), $demouserids)) { // No Assign to Vorlagenuser and DemoUser

					if(!Trainingssystem_Plugin_Database::getInstance()->NutzerDao->userHasTraining($t_due->getUserId(), $t_due->getTrainingId())) {

						$training_assign = $alltrainings[$t_due->getTrainingId()];
						$trainingindex = sizeof(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($t_due->getUserId()));
						
						$coaching_needed = get_user_meta($t_due->getUserId(),'coaching_needed',false);
						$newCoachingVals = [];
						if(!empty($coaching_needed) && isset($coaching_needed[0])) {
							$newCoachingVals = json_decode($coaching_needed[0], true);
						}

						if(($t_due->getTrainingMode() == "0" || $t_due->getTrainingMode() == "1") && $t_due->getEcoachingEnable() == "1") {
							$newCoachingVals[$t_due->getTrainingId()] = 1;
						} elseif($t_due->getTrainingMode() == "2") {
							$newCoachingVals[$t_due->getTrainingId()] = 2;
						} else {
							$newCoachingVals[$t_due->getTrainingId()] = 0;
						}
						
						update_user_meta($t_due->getUserId(),'coaching_needed', json_encode($newCoachingVals));

						$i = 0;
						foreach($training_assign->getLektionsliste() as $assign_lektion) {
							$trainingModeLektion = $t_due->getTrainingMode();
							if($t_due->getTrainingMode() != 0 && $t_due->lektionSettingsIsArray() && isset($t_due->getLektionSettingsJsonDecoded()[$assign_lektion->getId()])) {
								$trainingModeLektion = $t_due->getLektionSettingsJsonDecoded()[$assign_lektion->getId()];
							}
							Trainingssystem_Plugin_Database::getInstance()->NutzerDao->setLektionWithValuesByUserId($t_due->getUserId(), $training_assign->getId(), $assign_lektion->getId(), $trainingindex, $i, $trainingModeLektion, true, 0); // 2nd last param: always enable date training
							$i++;
						}

						if($t_due->getRedirect()) {
							update_user_meta( $t_due->getUserId(), 'redirectTraining', $training_assign->getId());
						}
					}

					// User Event
					$title = "Training „" . get_the_title($t_due->getTrainingId()) . "“ freigeschalten";
					$subtitle = "Es wurde Ihnen das Training „" . get_the_title($t_due->getTrainingId()) . "“ aufgrund einer zeitlichen order abhängigen Zuweisung freigeschalten";
					// Params: $title, $subtitle, $userid, $postid, $url, $type, $level, $date (= null)
					Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $t_due->getUserId(), $t_due->getTrainingId(), add_query_arg("idt1", $t_due->getTrainingId(), get_permalink($t_due->getTrainingId())), "training", "important");

					$trainingsAssigned[] = $t_due->getId();
				}
			}

			Trainingssystem_Plugin_Database::getInstance()->TrainingDate->deleteTrainingsDate($trainingsAssigned);
		}
	}

	/**
	 * AJAX
	 * Function called when TrainingDate should be applied now
	 */
	public function assignTrainingDateNow() {
		if(isset($_POST['id']) && is_numeric($_POST['id'])) {

			$trainingDate = Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getTrainingDate($_POST['id']);

			if(!is_null($trainingDate)) {
				$yesterday = new DateTime('yesterday');
				
				if(Trainingssystem_Plugin_Database::getInstance()->TrainingDate->updateDatetimeForTrainingDate($_POST['id'], $yesterday->format('Y-m-d') . '00:00:00')) {
					$this->assignTrainingsDate();
					echo "1";
				} else {
					echo "0";
				}
			} else {
				echo "404";
			}			
		}
		wp_die();
	}

	/**
	 * Action-Function as soon as a training is completed
	 * 
	 * Checking all of a user's trainings if a dependency is satisfied and then converting it to a date training
	 * finally manuelly trigger the date cronjob for dep trainings 
	 * 
	 * @param Trainingssystem_Plugin_Database_Trainingseite page - not used
	 * @param Trainingssystem_Plugin_Database_Training training that has been completed - not used
	 * @param int User-ID
	 */
	public function check_for_dependent_trainings($page, $training, $userid) {

		$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
		$vorlagennutzerids = array_column($vorlagennutzer, 'ID');

		$demouser = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getDemoUserRaw();
		$demouserids = array_column($demouser, 'ID');
		
		if(!in_array($userid, $vorlagennutzerids) && !in_array($userid, $demouserids)) { // No assign to vorlagenuser

			$usertrainings_temp = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userid);
			$usertrainings = [];

			foreach($usertrainings_temp as $ut) {
				$usertrainings[$ut->getId()] = $ut;
			}

			$depTrainings = Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getTrainingDepByUser($userid);
			$deleteDepTrainings = [];

			foreach($depTrainings as $dep_tr) {

				if($dep_tr->getDependentCondition() == "and") {

					if($dep_tr->dependentTrainingsIsArray()) {
						$fail = false;
						foreach($dep_tr->getDependentTrainingsJsonDecoded() as $d) {
							if(isset($usertrainings[$d]) && $usertrainings[$d]->getFin() < 100) {
								$fail = true;
							}
						}

						if(!$fail) {

							if(!Trainingssystem_Plugin_Database::getInstance()->NutzerDao->userHasTraining($userid, $dep_tr->getTrainingId())) {
								$assignDate = new DateTime();
								$modifystring = "+ " . $dep_tr->getTimeAdd() . " " . $dep_tr->getTimeMultiplier();
								$assignDate->modify($modifystring);

								if(Trainingssystem_Plugin_Database::getInstance()->TrainingDate->insertTrainingDate($dep_tr->getTrainingId(), $dep_tr->getTrainingMode(), $dep_tr->getEcoachingEnable(), $dep_tr->getLektionSettings(), $userid, $assignDate->format("Y-m-d H:i:s"), $dep_tr->getRedirect(), $dep_tr->getCreatedBy())) {
									$deleteDepTrainings[] = $dep_tr->getId();
								}
							} else {
								$deleteDepTrainings[] = $dep_tr->getId();
							}
						}
					}

				} elseif($dep_tr->getDependentCondition() == "or") {

					if($dep_tr->dependentTrainingsIsArray()) {
						$success = false;
						foreach($dep_tr->getDependentTrainingsJsonDecoded() as $d) {
							if(isset($usertrainings[$d]) && $usertrainings[$d]->getFin() == 100) {
								$success = true;
								break;
							}
						}

						if($success) {

							if(!Trainingssystem_Plugin_Database::getInstance()->NutzerDao->userHasTraining($userid, $dep_tr->getTrainingId())) {
								$assignDate = new DateTime();
								$modifystring = "+ " . $dep_tr->getTimeAdd() . " " . $dep_tr->getTimeMultiplier();
								$assignDate->modify($modifystring);

								if(Trainingssystem_Plugin_Database::getInstance()->TrainingDate->insertTrainingDate($dep_tr->getTrainingId(), $dep_tr->getTrainingMode(), $dep_tr->getEcoachingEnable(), $dep_tr->getlektionSettings(), $userid, $assignDate->format("Y-m-d H:i:s"), $dep_tr->getRedirect(), $dep_tr->getCreatedBy())) {
									$deleteDepTrainings[] = $dep_tr->getId();
								}
							} else {
								$deleteDepTrainings[] = $dep_tr->getId();
							}
						}
					}
				}
			}

			Trainingssystem_Plugin_Database::getInstance()->TrainingDep->deleteTrainingsDep($deleteDepTrainings);
		}

		$this->assignTrainingsDate(); // trigger cron manually
	}

	public function backendAdminOverview() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		echo $twig->render("admin-backend/admin-backend-future-trainings.html", [
			"allTrainings" => $this->getAllTrainingsIndexed(false),
			"allUsers" => Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllNutzer(false, false, false, true, true),
			"dateTrainings" => Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getAllTrainingDate("assigndate_asc"),
			"depTrainings" => Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getAllTrainingDep("id_asc"),
			"trainingModes" => [0 => "Individuell", 1 => "Sequentiell", 2 => "Begleitet"],
			"timeMultipliers" => ["hours" => "Stunde(n)", "days" => "Tag(e)", "weeks" => "Woche(n)", "months" => "Monat(e)"],
		]);
	}

	/**
	 * HELPER
	 * 
	 * Returns all Trainings with training-ID as array index
	 * 
	 * @return Array
	 */
	private function getAllTrainingsIndexed($includecategories = true) {
		$alltrainings = [];
		$alltrainings_tmp=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings($includecategories);
		foreach($alltrainings_tmp as $at) {
			$alltrainings[$at->getId()] = $at;
		}
		return $alltrainings;
	}
}
