<?php

class Trainingssystem_Plugin_Module_Coaching_Overview
{

    /**
     * Initialize the class and set its properties.
     *
     */
    public function __construct()
    {
    }

	public function showCoachingOverview($atts){

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

		$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()]);
		}
		
		$heading = isset($atts['titel']) ? $atts['titel'] : 'Coaching-Übersicht';
		
		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

		$numberTableCells = 9;
		
		$showUserID = true;
		if(isset($settings['hide_coaching_overview_user_id'])){
			$showUserID = false;
			$numberTableCells--;
		}

		$showStudyID = true;
		if(isset($settings['hide_coaching_overview_studien_id'])){
			$showStudyID = false;
			$numberTableCells--;
		}

		$showTrainingsCoaching = true;
		if(isset($settings['hide_coaching_overview_trainings_coaching'])){
			$showTrainingsCoaching = false;
			$numberTableCells--;
		}

		$showLastLogin = true;
		if(isset($settings['hide_coaching_overview_last_login'])){
			$showLastLogin = false;
			$numberTableCells--;
		}

		$showRegistrationDate = true;
		if(isset($settings['hide_coaching_overview_registration_date'])){
			$showRegistrationDate = false;
			$numberTableCells--;
		}

		$showFeedbackStatus = true;
		if(isset($settings['hide_coaching_overview_feedback_status'])){
			$showFeedbackStatus = false;
			$numberTableCells--;
		}

		$showUserActivity = true;
		if(isset($settings['hide_coaching_overview_user_activity'])){
			$showUserActivity = false;
			$numberTableCells--;
		}

		$showNotes = true;
		if(isset($settings['hide_coaching_overview_notes'])){
			$showNotes = false;
		}
		
		$url = get_permalink();
		$search = isset($_GET['search']) ? $_GET['search'] : "";
        $column = isset($_GET['column']) ? $_GET['column'] : "all";
    	$rows = isset($_GET['rows']) ? $_GET['rows'] : 25;
        $page = isset($_GET['page_pag']) ? $_GET['page_pag'] : "1";
        $start=  ($rows != "Alle") ? ($page-1) * $rows : 0;
        $links = [];
		$arrayAllLimits = array(25, 50, 100, 250,'Alle');
		$searchableColumns = [];
		$searchableColumns["all"] = "Alle Spalten";
		if($showUserID){
			$searchableColumns["userid"] = "ID";
		}
		if($showStudyID){
			$searchableColumns["studienid"] = "Studien-TN-ID";
		}
		$searchableColumns["username"] = "User-Name";
		if($showTrainingsCoaching){
			$searchableColumns['training'] = "Trainings mit Coaching";
		}
		
		$showSupervisorView = false;
		$showCoachView = false;

		$userInformation = $this->getUserInformation();
		$coachUser = $this->getUsersByCoaches();
		$trainingTitles = $this->getTrainingTitles();

		// Alle Vorlagenuser
		$allVorlagenuser = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
		$allVorlagenuserIds = array_column($allVorlagenuser, 'ID');

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

		$allCoachesInformation = array();
		$thisCoachUsers = array();
		$allUsersWithoutCoach = array();
		$detailpageslinks = array();

		$coachingNotes = array();

		// SICHT COACH
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverview"))
		{	
			$thisCoachId = wp_get_current_user()->ID;
			$userTrainingCoachingModes = $this->getUserTrainingCoachingModes();

			$tempUserIds = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getEligibleUserIdsCoach($search, $column, $showUserID, $showStudyID, $showTrainingsCoaching);
			$usersLen = sizeof($tempUserIds);

			$totalPages = ($rows == "Alle") ? 1 : ceil($usersLen / $rows);

			if($page == 1 || $page == 2){
				for($i = 1; $i <= $totalPages; $i++){
					array_push($links, $i);
					if ($i == 5){break;}
				}
			}else if($page == $totalPages || $page == $totalPages-1){
				for($i = $totalPages-4; $i <= $totalPages; $i++){
					if($i>0){
						array_push($links, $i);
					}
				}
			}else {
				for($i = $page-2; $i <= $totalPages; $i++){
					array_push($links, $i);
					if ($i == $page + 2){break;}
				}
			}
			$lastPagePag = $totalPages;

			$userIdsCoach = array();

			foreach($tempUserIds as $tempUserId){
				$userIdsCoach[] = $tempUserId['userid'];
			}
			
			$userIdsToDisplay = array();
            if($rows != "Alle") {
				for($i = $start; $i < ($start+$rows); $i++) {
					if(isset($userIdsCoach[$i])) {
						$userIdsToDisplay[] = $userIdsCoach[$i];
					}
				}
			} else {
				$userIdsToDisplay = $userIdsCoach;
			}

			// TEILNEHMENDE COACH
			$thisCoachUsers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(false, $userIdsToDisplay);

			foreach($thisCoachUsers as $thisCoachUser){
				
				$detailpageslinks[$thisCoachUser->getId()] = add_query_arg("userid", $thisCoachUser->getId(), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list_detail"]));
				$thisCoachUserTrainings = $thisCoachUser->getTrainings();
				$thisCoachUserNewTrainings = array();
				foreach($thisCoachUserTrainings as $thisCoachUserTraining){

					if(isset($userTrainingCoachingModes[$thisCoachUser->getId()][$thisCoachUserTraining->getId()])){
						if($userTrainingCoachingModes[$thisCoachUser->getId()][$thisCoachUserTraining->getId()] == "1" || $userTrainingCoachingModes[$thisCoachUser->getId()][$thisCoachUserTraining->getId()] == "2"){
							$thisCoachUserNewTrainings[$thisCoachUserTraining->getId()] = $thisCoachUserTraining;							
						}
					}
					
				}
				$thisCoachUser->setTrainings($thisCoachUserNewTrainings);

				$userInactivityDays = $settings['globalInactivity'] ?? 8;
				$resetUserActivity = $settings['reset_userInactivity'] ?? false;
				$userCustomInactivityDays = get_user_meta( $thisCoachUser->getId(), 'userInactivity', true );
				if(!$resetUserActivity && !empty($userCustomInactivityDays) && is_numeric($userCustomInactivityDays)) {
					$userInactivityDays = intval($userCustomInactivityDays);
				}
				$thisCoachUser->setActivityDays($userInactivityDays);
				$userInactiveSeconds = $userInactivityDays * 24 * 60 * 60;
				
				foreach($thisCoachUserNewTrainings as $training) {
					if($training->getFin() < 100) {
						$seitenids = Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getSeitenIdsByTraining($training->getid());

						$eventData = Trainingssystem_Plugin_Database::getInstance()->UserEvent->getEventsForUserByPosts($thisCoachUser->getId(), $seitenids, 1);

						if(count($eventData) === 0 && !($thisCoachUser->getActivity() instanceof DateTime) && !is_bool($thisCoachUser->getActivity())) {
							$thisCoachUser->setActivity(null);
						} elseif(count($eventData) > 0) {
							$today = new DateTime();
							$eventDate = new DateTime($eventData[0]->getDate(), new DateTimeZone("Europe/Berlin"));
							if($today->getTimestamp() - $eventDate->getTimestamp() > $userInactiveSeconds) {
								if(is_null($thisCoachUser->getActivity()) || !($thisCoachUser->getActivity() instanceof DateTime) || $thisCoachUser->getActivity() < $eventDate) {
									$thisCoachUser->setActivity($eventDate);
								}
							} else {
								$thisCoachUser->setActivity(true);
								break;
							}
						}
					}
				}
				
				// Alle Trainings beendet => keine Aktivität nötig
				$finished = true;
				foreach($thisCoachUserNewTrainings as $training) {
					if($training->getFin() < 100) {
						$finished = false;
					}
				}
				if($finished) {
					$thisCoachUser->setActivity("trainings finished");
				}

				// Alle Trainings noch nicht gestartet => Hinweis
				$notStarted = true;
				foreach($thisCoachUserNewTrainings as $training) {
					if($training->getFin() > 0) {
						$notStarted = false;
					}
				}
				if($notStarted) {
					$thisCoachUser->setActivity("trainings not started");
				}

				if(!$finished && !$notStarted){

					$notInProgress = true;
					foreach($thisCoachUserNewTrainings as $training) {
						if($training->getFin() > 0 && $training->getFin() < 100) {
							$notInProgress = false;
						}
					}

					if($notInProgress){
						$thisCoachUser->setActivity("trainings not in progress");
					}
				}

			}

			$showCoachView = true;

			// Coaching Notes
			$queryArgs = array(
				'meta_key' => 'coaching_notes',
				'include' => $userIdsCoach
			);

			$user_query = get_users( $queryArgs );
			foreach($user_query as $user_q){
				$coachingNotes[$user_q->ID] = $user_q->coaching_notes;
			}
		}
		
		// SICHT SUPERVISOR - USER OHNE COACH | ALLE COACHES
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverviewsupervisor"))
		{

			// TEILNEHMENDE MIT COACHING-BEDARF
			$usersWithoutCoach = $this->getUsersWithoutCoach();

			if(isset($usersWithoutCoach)){
				foreach($usersWithoutCoach as $uwcId => $uwcMode ){

					$thisUserWithoutCoach = array();
					$thisUserWithoutCoach["userID"] = $uwcId;
					$thisUserWithoutCoach["userLogin"] = $userInformation[$uwcId]["user_login"];
					$thisUserWithoutCoach["displayName"] = $userInformation[$uwcId]["display_name"];
					$thisUserWithoutCoach["userStudID"] = $userInformation[$uwcId]["studienid"];

					$thisUserWithoutCoach["trainings"] = array();

					foreach($uwcMode as $tid => $tmode){
						if(isset($trainingTitles[$tid])){
							$thisUserWithoutCoach["trainings"][$tid]['trainingID'] = $tid;
							$thisUserWithoutCoach["trainings"][$tid]['trainingTitle'] = $trainingTitles[$tid];
							$thisUserWithoutCoach["trainings"][$tid]['coachingMode'] = $tmode;
						}
						
					}
					
					if(!empty($thisUserWithoutCoach['trainings'])){
						$allUsersWithoutCoach[$uwcId] = $thisUserWithoutCoach;
					}
				}
			}

			// COACHES
			$allCoaches = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainer();

			if(isset($allCoaches)){
				foreach($allCoaches as $coach){
					
					if(!isset($allCoachesInformation[$coach->ID])){
						$allCoachesInformation[$coach->ID] = array();
					}
					$allCoachesInformation[$coach->ID]["coachID"] = $coach->ID;
					$allCoachesInformation[$coach->ID]["coachUserLogin"] = $userInformation[$coach->ID]["user_login"];
					$allCoachesInformation[$coach->ID]["coachDisplayName"] = $userInformation[$coach->ID]["display_name"];

					$allCoachesInformation[$coach->ID]["users"] = array();
					if(isset($coachUser[$coach->ID]["users"])){
						foreach($coachUser[$coach->ID]["users"] as $cuser){
							
							if(!in_array($cuser, $allVorlagenuserIds) && !in_array($cuser, $demouserids)){
								if(!isset($allCoachesInformation[$coach->ID]["users"][$cuser])){
									$allCoachesInformation[$coach->ID]["users"][$cuser] = array();
								}
								$allCoachesInformation[$coach->ID]["users"][$cuser]["userID"] = $cuser;
								$allCoachesInformation[$coach->ID]["users"][$cuser]["userLogin"] = $userInformation[$cuser]["user_login"];
								$allCoachesInformation[$coach->ID]["users"][$cuser]["userDisplayName"] = $userInformation[$cuser]["display_name"];
								$allCoachesInformation[$coach->ID]["users"][$cuser]["userStudID"] = $userInformation[$cuser]["studienid"];
							}
						}
					}
				}
			}

			$showSupervisorView = true;

			$users = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getAllNutzer(true, false, false);
			foreach($users as $user) {
				$detailpageslinks[$user->getId()] = add_query_arg("userid", $user->getId(), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list_detail"]));
			}
		}

		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverview")||Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverviewsupervisor"))
		{
			
			return $twig->render('coaching-overview/coaching-overview-dashboard.html', [
				'usersWithoutCoach' => $allUsersWithoutCoach, 
				'coaches' => $allCoachesInformation, 
				'usersOfCoach' => $thisCoachUsers, 
				'urlM' => add_query_arg('action', 'userlist', get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"])), // anpassen, wenn benötigt!
				'postid' => get_the_ID(), 
				'detail_page_links' => $detailpageslinks,
				'showSupervisorView' => $showSupervisorView,
				'showCoachView' => $showCoachView,
				'heading' => $heading,
				'showUserDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetails"),
				'coachingNotes' => $coachingNotes,
				'showUserID' => $showUserID,
				'showStudyID' => $showStudyID,
				'showTrainingsCoaching' => $showTrainingsCoaching,
				'showLastLogin' => $showLastLogin,
				'showRegistrationDate' => $showRegistrationDate,
				'showFeedbackStatus' => $showFeedbackStatus,
				'showUserActivity' => $showUserActivity,
				'showNotes' => $showNotes,
				"searchableColumns" => $searchableColumns,
				"arrayAllLimits" => $arrayAllLimits,
				"search" => $search,
                "column" => $column,
				"rows" => $rows,
				'page' => $page,
                'links' => $links,
				'url' => $url,
				'usersLen' => $usersLen,
				"lastPagePag" => $lastPagePag,
				"numberTableCells" => $numberTableCells
			]);
		}
		else{
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}
	}

	public function assignCoach(){
		
		$userID = $_POST['userID'];
		$coachID = $_POST['coachID'];

		// Rufe ab, ob für den aktuellen einen Eintrag für den Meta-Key "coachid" gibt
		$entryThisUser = get_user_meta($userID, 'coachid', false);

		// Eintrag exisitert bereits für aktuellen User
		if(!empty($entryThisUser)){
			update_user_meta($userID, 'coachid', $coachID, '');
		}
		// Eintrag exisitert nicht für den aktuellen User
		else{
			add_user_meta($userID, 'coachid', $coachID);
		}

		echo '1';
		wp_die();
	}

	public function multiAssignCoach() {
		if(isset($_POST['users']) && is_array($_POST['users']) && count($_POST['users']) > 0 && isset($_POST['coach']) && is_numeric($_POST['coach'])) {

			foreach($_POST['users'] as $user) {
				if(is_numeric($user) && $user > 0) {
					update_user_meta($user, 'coachid', $_POST['coach'], '');
				}
			}
			echo "1";

		} else {
			echo "invalid data";
		}
		wp_die();
	}

	public function saveCoachingNotes(){

		if(isset($_POST['userid']) && is_numeric($_POST['userid']) &&
		isset($_POST['coachingNotes'])){

			$userid = sanitize_text_field($_POST['userid']);
			$coachingNotes = wp_kses($_POST['coachingNotes'], wp_kses_allowed_html( 'strip' ));
			update_user_meta($userid, 'coaching_notes', $coachingNotes);
			echo "1";
		}
		else{
			echo "0";
		}
		wp_die();
	}

	/*
	* |-> coach
	*	|-> users
	*		|-> entry
	*		...
	*/
	private function getUsersByCoaches(){

		global $wpdb;
		$table_name_usermeta = $wpdb->prefix . "usermeta";

		$sql = "SELECT meta_value AS coach, user_id 
				FROM $table_name_usermeta 
				WHERE meta_key = 'coachid' AND meta_value <> ''";

		$result = $wpdb->get_results($sql);

		$ret = array();

		if($result){

			foreach($result as $row){
				if(!isset($ret[$row->coach]["users"])){
					$ret[$row->coach]["users"] = array();
				}
				$ret[$row->coach]["users"][] = $row->user_id;
			}
		}

		return $ret;
	}

	private function getUserTrainingCoachingModes(){

		global $wpdb;
		$table_name_usermeta = $wpdb->prefix . "usermeta";

		$sql = "SELECT user_id, meta_value AS coaching_needed
				FROM $table_name_usermeta
				WHERE meta_key = 'coaching_needed'";

		$result = $wpdb->get_results($sql);

		$ret = array();

		if($result){

			foreach($result as $row){

				$coachingModes = (array)json_decode($row->coaching_needed);

				foreach($coachingModes as $tid => $mode){

					if($mode == "1" || $mode == "2"){
						if(!isset($ret[$row->user_id])){
							$ret[$row->user_id] = array();
						}
						$ret[$row->user_id][$tid] = $mode;
					}

				}
			}
		}

		return $ret;
	}

	/**
	 * |-> user_id
	 * 		|-> trainings_id
	 * 			|-> mode
	 * 				|-> entry	
	 */
	private function getUsersWithoutCoach(){

		$ret = array();

		$argsCoachingNeeded = array(
			'meta_key' => 'coaching_needed'
		);
		$usersCoachingNeeded = get_users($argsCoachingNeeded);

		$argsCoachid = array(
			'meta_key' => 'coachid'
		);
		$usersCoaches = get_users($argsCoachid);
		
		$vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
		$vorlagennutzerids = array_column($vorlagennutzer, 'ID');
		 
		$demouser = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getDemoUserRaw();
		$demouserids = array_column($demouser, 'ID');

		foreach($usersCoachingNeeded as $user){

			if(!in_array($user->ID, $vorlagennutzerids) && !in_array($user->ID, $demouserids)){
				$coachingModes = (array)json_decode($user->coaching_needed);
				
				foreach($coachingModes as $tid => $mode){
	
					if($mode == "1" || $mode == "2"){
						if(in_array($user, $usersCoaches)){
							if(empty($user->coachid)){
								if(!isset($ret[$user->ID])){
									$ret[$user->ID] = array();
								}
								$ret[$user->ID][$tid] = $mode;
							}
						}
						else{
							if(!isset($ret[$user->ID])){
								$ret[$user->ID] = array();
							}
							$ret[$user->ID][$tid] = $mode;
						}
					}
				}
			}

			
		}
		
		return $ret;
	}

	private function getUserInformation(){
		global $wpdb;
		$table_name_usermeta = $wpdb->prefix . "usermeta";

		$sql = "SELECT user_id, meta_value
				FROM $table_name_usermeta
				WHERE meta_key = 'studienid'";

		$result = $wpdb->get_results($sql);

		$allUser = get_users();

		$ret = array();

		foreach($allUser as $user){

			if(!isset($ret[$user->ID])){
				$ret[$user->ID] = array();
			}
			$ret[$user->ID]["id"] = $user->ID;
			$ret[$user->ID]["display_name"] = $user->display_name;
			$ret[$user->ID]["user_login"] = $user->user_login;
			$ret[$user->ID]["studienid"] = "";

			foreach($result as $row){

				if($row->meta_value == ""){
					$ret[$row->user_id]["studienid"] = ""; 
				}
				else{
					$ret[$row->user_id]["studienid"] = $row->meta_value; 
				}
			}

			
		}

		return $ret;
	}

	private function getTrainingTitles(){

		global $wpdb;
		$table_name_trainings = $wpdb->prefix . "md_trainingsmgr_tranings_lektionen";
		$table_name_posts = $wpdb->prefix . "posts";

		$sql = "SELECT DISTINCT t.training_id, p.post_title
				FROM $table_name_trainings t 
				INNER JOIN $table_name_posts p ON t.training_id = p.ID";

		$result = $wpdb->get_results($sql);

		$ret = array();

		foreach($result as $row){

			$ret[$row->training_id] = $row->post_title;
		}	

		return $ret;
	}
}
