<?php

/**
 * The functionality of the module.
 *
 * @package    User Event
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_User_Event {

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

		add_action('tspv2_user_events_clean', array($this, 'cleanUserEvents'));
    }

	public function maybe_delete_userevents()
	{
		if (!wp_next_scheduled('tspv2_user_events_clean')) {
			wp_schedule_event(current_time('timestamp'), 'daily', 'tspv2_user_events_clean');
		}
	}

	/**
	 * FRONTEND
	 * 
	 * Shows a users latest activity
	 * 
	 * @param atts Attributes to configure
	 * 
	 * @return HTML-Code
	 */
	public function showLastEvents($atts) {

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

		$title = "Letzte Aktivität";
        if(isset($atts['titel'])) { // Allow empty title here!
            $title = $atts['titel'];
        }

        $limit = 20;
        if(isset($atts['limit']) && is_numeric($atts['limit']) && ($atts['limit'] == -1 || $atts['limit'] > 0)) {
            $limit = $atts['limit'];
        } elseif(isset($atts['limit'])) {
			$limit = null;
		}

		$alllevel = Trainingssystem_plugin_Database::getInstance()->UserEvent::$level;
		$level = 'info';
		if(isset($atts['level']) && in_array($atts['level'], $alllevel)) {
            $level = $atts['level'];
        } elseif(isset($atts['level'])) {
			$level = null;
		}

		$alltypes = Trainingssystem_Plugin_Database::getInstance()->UserEvent::$types;
		$include_types = $alltypes;
		if(isset($atts['type']) && trim($atts['type']) != "") {

			$include_types = [];

			if(strpos($atts['type'], ';') === false && in_array($atts['type'], $alltypes)) {
				$include_types[] = $atts['type'];
			} elseif(strpos($atts['type'], ';') !== false) {
				$exp = explode(";", $atts['type']);

				foreach($exp as $t) {
					if(in_array($t, $alltypes)) {
						$include_types[] = $t;
					} else {
						$include_types = [];
						break;
					}
				}
			}
			if(count($include_types) == 0) {
				$include_types = null;
			}
		}

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

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

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

		if(is_null($level) || is_null($limit) || is_null($order_asc) || is_null($newpage) || is_null($hidesubtitles) || is_null($include_types)) {
			return $twig->render("user-event/user-event-error.html", ["alllevel" => $alllevel, "alltypes" => $alltypes]);
		} else {

			// TODO: image array for all trainings with default image if training does not have one

			// $userid, $level, $limit, $types, $orderby
			$events = Trainingssystem_Plugin_Database::getInstance()->UserEvent->getUserEvents($this->getTrainingUser(), $this->getLevelGreaterThan($level), $include_types, $limit, $order_asc ? "ASC" : "DESC");
			
			// Images/Font Awesome Icons
			foreach($events as $event) {
				switch($event->getEventType()) {
					case "profile":
						$event->setFontAwesome("fas fa-user-alt");
						break;
					case "login":
						$event->setFontAwesome("fas fa-sign-in-alt");
						break;
					case "logout":
						$event->setFontAwesome("fas fa-sign-out-alt");
						break;
					case "training":
						if(get_post_type($event->getPostId()) == "trainings" && get_the_post_thumbnail_url($event->getPostId()) !== false) {
							$event->setImageUrl(get_the_post_thumbnail_url($event->getPostId()));
						} elseif(get_post_type($event->getPostId()) == "lektionen") {
							$trainingId = Trainingssystem_Plugin_Database::getInstance()->LektionDao->getTrainingByLektion($event->getPostId())[0] ?? 0;

							if(get_the_post_thumbnail_url($trainingId) !== false) {
								$event->setImageUrl(get_the_post_thumbnail_url($trainingId));
							}
						} elseif(get_post_type($event->getPostId()) == "seiten") {
							$trainingId = Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getTrainingBySeite($event->getPostId())[0] ?? 0;

							if(get_the_post_thumbnail_url($trainingId) !== false) {
								$event->setImageUrl(get_the_post_thumbnail_url($trainingId));
							}
						}
						break;
					case "registerkey":
						$event->setFontAwesome("fas fa-key");
						break;
					case "check":
						// in check v2: add image by post-id here
						$event->setFontAwesome("fas fa-check");
						break;

					// default handled in twig template
				}
			}
			
			return $twig->render("user-event/user-event-overview.html", ["title" => $title, 
																		"results" => $events,
																		"defaultimage" => get_header_image(),
																		"newpage" => $newpage,
																		"hidesubtitles" => $hidesubtitles,
																		]);
		}
	}

	/**
	 * ADMIN
	 * 
	 * Save the UserEvent Settings
	 * 
	 * @return 1 on success
	 */
	public function saveUserEventSettings() {
		if(isset($_POST['data']) && trim($_POST['data']) != "") {
			
			$data = json_decode(stripslashes(sanitize_text_field($_POST['data'])), true);

			if(json_last_error() == JSON_ERROR_NONE) {
				
				Trainingssystem_Plugin_Database::getInstance()->UserEvent->saveSettings($data);
				echo "1";
			}
		}
		wp_die();
	}

	/**
	 * ADMIN
	 * 
	 * Deletes User Events for a specific User
	 * 
	 * @return 1 on succcess
	 */
	public function deleteUserEvents() {
		if(isset($_POST['user']) && trim($_POST['user']) != "" && is_numeric($_POST['user']) && 
			isset($_POST['type']) && trim($_POST['type']) != "" && 
			isset($_POST['level']) && trim($_POST['level']) != "") {

			$user = sanitize_text_field( $_POST['user'] );
			$type = json_decode(stripslashes(sanitize_text_field($_POST['type'])), true);
			$level = json_decode(stripslashes(sanitize_text_field($_POST['level'])), true);

			if(json_last_error() == JSON_ERROR_NONE && sizeof($type) > 0 && sizeof($level) > 0) {

				if(Trainingssystem_Plugin_Database::getInstance()->UserEvent->deleteUserEvents($user, $type, $level)) {
					echo "1";
				} else {
					echo "sql";
				}

			}
		}
		wp_die();
	}

	/**
	 * CRON-FUNCTION
	 * 
	 * Called once a day to clear the user event table according to the settings
	 */
	public function cleanUserEvents() {

		$settings = Trainingssystem_Plugin_Database::getInstance()->UserEvent->getSettings();

		foreach($settings as $type => $levels) {
			foreach($levels as $level => $days) {
				if(!empty($days) and $days != 0) {
					Trainingssystem_Plugin_Database::getInstance()->UserEvent->deleteUserEventsOlderThan($type, $level, $days);
				}
			}
		}

	}

	/**
	 * Deletes User Events that are connected to a post before the psot is finally deleted
	 * 
	 * @param Integer Post-ID
	 */
	public function deleteUserEventsForPost($postid) {
		Trainingssystem_Plugin_Database::getInstance()->UserEvent->deleteUserEventsByPost($postid);
	}

	/**
	 * HELPER
	 * 
	 * Getting all levels greather or equal than the given level
	 * 
	 * @param String level to look for
	 * 
	 * @return Array of all levels greater or equal
	 */
	private function getLevelGreaterThan($levelStart) {
		$l = Trainingssystem_plugin_Database::getInstance()->UserEvent::$level;
		return array_slice($l, array_search($levelStart, $l));
	}
	
	/**
	 * HELPER
	 * 
	 * Returns the user-id for which the content is displayed
	 * 
	 * @return Int User-ID
	 */
	private function getTrainingUser()
    {
        $current_user = wp_get_current_user();
        $userid = $current_user->ID;

        $select_userid = '' . get_user_meta($current_user->ID, 'coach_select_user', true);
        if ($select_userid != '') {
            $userid = $select_userid;
        }
        
        return $userid;
    }
}