<?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_Backend_Trainings_Mgr {

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

	}

	/**
	 *
	 *
	 * @since    1.0.0
	 */
	public function custom_training_mgr_meta_box_markup() {
		global $post;
        $id = $post->ID;

		$lektionendata=Trainingssystem_Plugin_Database::getInstance()->LektionDao->getLektion2($id);
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		echo $twig->render('admin-backend-trainings-mgr/admin-backend-trainings-mgr.html',[
			 'lektionen'=>$lektionendata,
			 'multipleUsedLektionen' => Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getMultipleUsedLektionIds(),
			 'multipleUsedSeiten' => Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getMultipleUsedSeitenIds(),
			]);
	}

	public function custom_training_mgr_options_meta_box_markup() {
		global $post;
		$id = $post->ID;
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		$contentPlacement = "top";
		$contentPlacementMeta = get_post_meta($id, 'contentPlacement', true);
		if(!empty($contentPlacementMeta)){
			$contentPlacement = $contentPlacementMeta;
		}

		$showTrainingNameMeta = get_post_meta($id, 'showTrainingName', false);
		if(!empty($showTrainingNameMeta)){
			$showTrainingName = $showTrainingNameMeta[0];
		}
		else{
			$showTrainingName = "1";
		}

		$showLektionslisteMeta = get_post_meta($id, 'showLektionsliste', false);
		if(!empty($showLektionslisteMeta)){
			$showLektionsliste = $showLektionslisteMeta[0];
		}
		else{
			$showLektionsliste = "1";
		}

		$showLektionenButtonMeta = get_post_meta($id, 'showLektionenButton', false);
		if(!empty($showLektionenButtonMeta)){
			$showLektionenButton = $showLektionenButtonMeta[0];
		}
		else{
			$showLektionenButton = "1";
		}

		$showNavigationMeta = get_post_meta($id, 'showNavigation', false);
		if(!empty($showNavigationMeta)){
			$showNavigation = $showNavigationMeta[0];
		}
		else{
			$showNavigation = "1";
		}

		$showPaginationMeta = get_post_meta($id, 'showPagination', false);
		if(!empty($showPaginationMeta)){
			$showPagination = $showPaginationMeta[0];
		}
		else{
			$showPagination = "1";
		}

		$skipDashboardMeta = get_post_meta($id, 'skipDashboard', false);
		if(!empty($skipDashboardMeta)){
			$skipDashboard = $skipDashboardMeta[0];
		}
		else{
			$skipDashboard = "0";
		}

		$disableUserEventsMeta = get_post_meta($id, 'disableUserEvents', false);
		if(!empty($disableUserEventsMeta)){
			$disableUserEvents = $disableUserEventsMeta[0];
		}
		else{
			$disableUserEvents = "0";
		}

		$calendarTrainingMeta = get_post_meta($id, 'calendarTraining', false);
		if(!empty($calendarTrainingMeta)){
			$calendarTraining = $calendarTrainingMeta[0];
		}
		else{
			$calendarTraining = "0";
		}

		// Prüfung: Hat dieses Training bereits Kalender-Seiten?
		$hasCalendarPages = $this->checkTrainingHasCalendarPages($id);
		$calendarTrainingDisabled = $hasCalendarPages;
		$calendarTrainingConflictMessage = $hasCalendarPages ? 
			"<div class='alert alert-warning mt-2'><small><i class='fas fa-exclamation-triangle'></i> <strong>Hinweis:</strong> Dieses Training enthält bereits Seiten, die als Kalender-Seiten markiert sind. Ein Training kann nicht gleichzeitig als Kalender-Training verwendet werden und als Kalender-Seiten markierte Seiten enthalten.</small></div>" : 
			"";

		$showAppSleepSingleSaveMeta = get_post_meta($id, 'showAppSleepSingleSave', false);
		if(!empty($showAppSleepSingleSaveMeta)){
			$showAppSleepSingleSave = $showAppSleepSingleSaveMeta[0];
		}
		else{
			$showAppSleepSingleSave = "0";
		}

		$showAppSleepMultiSaveMeta = get_post_meta($id, 'showAppSleepMultiSave', false);
		if(!empty($showAppSleepMultiSaveMeta)){
			$showAppSleepMultiSave = $showAppSleepMultiSaveMeta[0];
		}
		else{
			$showAppSleepMultiSave = "0";
		}

		$rest_activated = false;
        if(isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['rest_activated']) && get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['rest_activated']) {
            $rest_activated = true;
        }

		$trainingNavigationType = "all";
		$trainingNavigationTypeMeta = get_post_meta($id, 'trainingNavigationType', false);
		if(!empty($trainingNavigationTypeMeta)) {
			$trainingNavigationType = $trainingNavigationTypeMeta[0];
		}

		echo $twig->render('admin-backend-trainings-mgr/admin-backend-trainings-mgr-options.html',[
			'contentPlacement'=> $contentPlacement,
			'showTrainingName'	=> $showTrainingName,
			'showLektionsliste' => $showLektionsliste,
			'skipDashboard' => $skipDashboard,
			'showLektionenButton' => $showLektionenButton,
			'showNavigation' => $showNavigation,
			'disableUserEvents' => $disableUserEvents,
			'calendarTraining' => $calendarTraining,
			'calendarTrainingDisabled' => $calendarTrainingDisabled,
			'calendarTrainingConflictMessage' => $calendarTrainingConflictMessage,
			'showPagination' => $showPagination,
			'showAppSleepSingleSave' => $showAppSleepSingleSave,
			'showAppSleepMultiSave' => $showAppSleepMultiSave,
			'rest_activated' => $rest_activated,
			'navigationType' => $trainingNavigationType,
		]);
	}


	/**
	 *
	 *
	 * @since    1.0.0
	 */
	public function add_training_mgr_meta_box() {
		add_meta_box("training-mgr-meta-box", "Training zusammenstellen", array($this, "custom_training_mgr_meta_box_markup"), "trainings", "normal", "high", null);
		add_meta_box("training-mgr-options-meta-box", "Trainings-Optionen", array($this, "custom_training_mgr_options_meta_box_markup"), "trainings", "side", "high", null);
	}


	public function backend_trainings_mgr_gettraining_lektionen(){

		$lektionendata=Trainingssystem_Plugin_Database::getInstance()->LektionDao->getAllLektionenUnused();
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		echo $twig->render('admin-backend-trainings-mgr/admin-backend-trainings-mgr-lektionen-modal.html',[
			 'lektionen'=>$lektionendata
			]);


		wp_die();

	}

	public function backend_trainings_mgr_add_lektionen(){
		if (isset($_POST['trainingid']) && isset($_POST['lektionen']) && is_array($_POST['lektionen'])) {
			
			$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
			
			foreach($_POST['lektionen'] as $lektionId) {
				$lektion=Trainingssystem_Plugin_Database::getInstance()->LektionDao->getLektionByID(intval(sanitize_text_field($lektionId)));
				
				echo $twig->render('admin-backend-trainings-mgr/admin-backend-trainings-mgr-lektion.html',[
					'lektion'=>$lektion
					]);
			}
		}
		wp_die();

	}

	public function backend_trainings_mgr_delete_lektion() {
		if (isset($_POST['lektionId']) && is_numeric($_POST['lektionId']) && isset($_POST['trainingId']) && is_numeric($_POST['trainingId'])) {
			if(Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeLektionFromUsers($_POST['lektionId'], $_POST['trainingId']) && 
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeLektionFromDatabase($_POST['lektionId'], $_POST['trainingId'])) {
				echo "1";
			}
		}
		wp_die();
	}

	public function backend_trainings_mgr_gettraining_seiten(){

		if (isset($_POST['lektionid'])) {
			$seiten=Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getAllUnusedSeitenIDs();
			$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
			echo $twig->render('admin-backend-trainings-mgr/admin-backend-trainings-mgr-seiten-modal.html',[
				 'seiten'=>$seiten,'lektionid'=>intval(sanitize_text_field($_POST['lektionid']))
				]);

		}
		wp_die();

	}


	public function backend_trainings_mgr_delete_seite() {
		if (isset($_POST['seitenId']) && is_numeric($_POST['seitenId']) && isset($_POST['lektionId']) && is_numeric($_POST['lektionId']) && isset($_POST['trainingId']) && is_numeric($_POST['trainingId'])) {
			if(Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeSeiteFromDatabase($_POST['seitenId'], $_POST['lektionId'], $_POST['trainingId'])) {
				echo "1";
			}
		}
		wp_die();
	}

	public function backend_trainings_mgr_save_training(){
		if (isset($_POST['trainingid'])&&isset($_POST['lektionen'])) {
			$trainingid = intval(sanitize_text_field($_POST['trainingid']));
			$lektionenraw = json_decode(stripslashes(sanitize_text_field($_POST['lektionen'])),true);
			//var_dump($lektionenraw);

			$t_old = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById($trainingid);
			$lektionsids = array();

			foreach ($lektionenraw as $lektion_key => $lektion_value) {
				$lektionsids[$lektion_value['id']] = $lektion_value['id'];
			}
			if($t_old instanceof Trainingssystem_Plugin_Database_Training) {
				foreach($t_old->getLektionsliste() as $t_old_lektion) {
					if(!isset($lektionsids[$t_old_lektion->getId()])) {
						Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeLektionFromUsers($t_old_lektion->getId());
					}
				}
			}

			$lektionen= array();

			$lektionindex=0;
			foreach ($lektionenraw as $lektion_key => $lektion_value) {
				//var_dump($lektion_value);
				$seiten= array();

				$seitenindex=0;
				foreach ($lektion_value['seiten'] as $seiten_key => $seiten_value) {
					$seiten[]= new Trainingssystem_Plugin_Database_Trainingseite(array(
										'id' => $seiten_value['id'],
										'trainingid' => $trainingid,
										'lektionid' => $lektion_value['id'],
										'index' => $seitenindex
								));
					$seitenindex++;
				}

				$lektionen[] = new Trainingssystem_Plugin_Database_Lektion($lektion_value['id'],
												null, null, null, null,null,null,null,$seiten,null);
				$lektionindex++;
			}

			$trainingclear=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->clearTrainingyById($trainingid);
			$trainingadd=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->saveTrainingyById($trainingid,$lektionen);

			echo "1";
		}
		wp_die();
	}

	public function backend_trainings_mgr_save_options(){
		
		if(isset($_POST['trainingid']) && isset($_POST['showLektionsliste']) && isset($_POST['contentPlacement']) && isset($_POST['showTrainingName']) && isset($_POST['skipDashboard']) && isset($_POST['showNavigation']) && isset($_POST['showLektionenButton']) && isset($_POST['disableUserEvents']) && isset($_POST['showPagination']) && isset($_POST['calendarTraining'])) {

			$trainingid = intval(sanitize_text_field($_POST['trainingid']));
			$showLektionsliste = strval(sanitize_text_field($_POST['showLektionsliste']));
			$showNavigation = strval(sanitize_text_field($_POST['showNavigation']));
			$showLektionenButton = strval(sanitize_text_field($_POST['showLektionenButton']));
			$showPagination = strval(sanitize_text_field($_POST['showPagination']));
			$contentPlacement = strval(sanitize_text_field($_POST['contentPlacement']));
			$showTrainingName = strval(sanitize_text_field($_POST['showTrainingName']));
			$skipDashboard = strval(sanitize_text_field($_POST['skipDashboard']));
			$disableUserEvents = strval(sanitize_text_field($_POST['disableUserEvents']));
			$showAppSleepMultiSave = strval(sanitize_text_field($_POST['showAppSleepMultiSave']));
			$showAppSleepSingleSave = strval(sanitize_text_field($_POST['showAppSleepSingleSave']));
			$navigationType = strval(sanitize_text_field($_POST['navigationType']));
			$calendarTraining = strval(sanitize_text_field($_POST['calendarTraining']));

			
			update_post_meta($trainingid, 'showLektionsliste', $showLektionsliste);
			update_post_meta($trainingid, 'showNavigation', $showNavigation);
			update_post_meta($trainingid, 'showLektionenButton', $showLektionenButton);
			update_post_meta($trainingid, 'showPagination', $showPagination);
			update_post_meta($trainingid, 'contentPlacement', $contentPlacement);
			update_post_meta($trainingid, 'showTrainingName', $showTrainingName);
			update_post_meta($trainingid, 'skipDashboard', $skipDashboard);
			update_post_meta($trainingid, 'disableUserEvents', $disableUserEvents);
			update_post_meta($trainingid, 'calendarTraining', $calendarTraining);

			update_post_meta($trainingid, 'showAppSleepMultiSave', $showAppSleepMultiSave);
			update_post_meta($trainingid, 'showAppSleepSingleSave', $showAppSleepSingleSave);

			update_post_meta($trainingid, 'trainingNavigationType', $navigationType);
		}
		wp_die();
	}

	public function backend_trainings_mgr_trash_post($postid) {

		switch(get_post_type( $postid )) {
			case 'trainings':
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeTrainingFromUsers($postid);
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeTrainingFromDatabase($postid);
				break;
			case 'lektionen':
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeLektionFromUsers($postid);
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeLektionFromDatabase($postid);
				break;
			case 'seiten':
				Trainingssystem_Plugin_Database::getInstance()->TrainingDao->removeSeiteFromDatabase($postid);
				break;
		}
	}

	/**
	 * Prüft ob ein Training bereits Kalender-Seiten hat
	 * 
	 * @param int $trainingId Training ID
	 * @return bool True wenn Kalender-Seiten vorhanden sind
	 */
	private function checkTrainingHasCalendarPages($trainingId) {
		global $wpdb;
		
		// Alle Lektionen des Trainings holen
		$lektionTable = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_LEKTIONEN;
		$lektionRows = $wpdb->get_results($wpdb->prepare(
			"SELECT lektion_id FROM $lektionTable WHERE training_id = %d",
			$trainingId
		));
		
		if (!$lektionRows) {
			return false;
		}
		
		$lektionIds = array_map(function($row) { return $row->lektion_id; }, $lektionRows);
		
		// Alle Seiten dieser Lektionen holen
		$seitenTable = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_SEITEN;
		$lektionPlaceholders = implode(',', array_fill(0, count($lektionIds), '%d'));
		$seitenRows = $wpdb->get_results($wpdb->prepare(
			"SELECT seiten_id FROM $seitenTable WHERE lektion_id IN ($lektionPlaceholders)",
			$lektionIds
		));
		
		if (!$seitenRows) {
			return false;
		}
		
		$seitenIds = array_map(function($row) { return $row->seiten_id; }, $seitenRows);
		
		// Prüfen ob eine der Seiten als Kalender-Seite markiert ist
		foreach ($seitenIds as $seitenId) {
			$calendarId = get_post_meta($seitenId, 'calendar_id', true);
			if (!empty($calendarId)) {
				return true;
			}
		}
		
		return false;
	}

}
