<?php

/**
 * The functionality of the module.
 *
 * @package    Exercise
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Exercise {
    
    /**
	 * BACKEND
	 * Restructure Columns for Uebungen List Table (Coulmn Post_type is removed via CSS)
	 */
	function exercise_manage_columns($columns) {
		$columns = array(
			'cb' => $columns['cb'],
			'uebungen_id' => 'ID',
			'title' => __('Title'),
            'uebungen_favorites' => 'Anzahl der Favorisierungen',
			'date' => __('Date'),
		);
		return $columns;
	}

	/**
	 * BACKEND
	 * Add Content to ID and count favorites columns
	 */
	function exercise_manage_custom_columns($column, $post_id) {
		if ( 'uebungen_id' === $column ) {
			echo '<a href="' . get_edit_post_link($post_id) . '">' . $post_id . '</a>';
		}

        if( 'uebungen_favorites' === $column) {
            echo Trainingssystem_Plugin_Database::getInstance()->Exercise->countExerciseFavorite($post_id);
        }
	}

	/**
	 * BACKEND
	 * Make ID and count favorites columns sortable
	 */
	function exercise_manage_sortable_columns($columns) {
		$columns['uebungen_id'] = 'uebungen_id';
        $columns['uebungen_favorites'] = 'uebungen_favorites';
  		return $columns;
	}

	/**
	 * BACKEND 
	 * If search for Exercise and search string is numeric, call additional filter
	 */
	function exercise_custom_search( $query ) {
		if(get_query_var("post_type") == "uebungen") {
			// Bail if we are not in the admin area
			if ( ! is_admin() ) {
				return;
			}
		
			// Bail if this is not the search query.
			if ( ! $query->is_main_query() && ! $query->is_search() ) {
				return;
			}

			if(!isset($_GET['orderby'])) {
				$query->set('orderby', 'ID');
				$query->set('order', 'DESC');
			}
		
			// Get the value that is being searched.
			$search_string = get_query_var( 's' );
		
			// Bail if the search string is not an integer.
			if ( ! filter_var( $search_string, FILTER_VALIDATE_INT ) ) {
				return;
			}
		
			add_filter('posts_where', array($this, 'exercise_custom_search_where'));
			$query->set( 'ID', $search_string );
		}
	}

    /**
	 * BACKEND
	 * Adds the additional Where Parameter to search for ID and PostType Uebungen as well
	 */
	function exercise_custom_search_where($where = '') {
		$search_string = intval(get_query_var( 's' ));

		$where .= " OR `ID` = '" . $search_string . "' AND `post_type` = 'uebungen'";

		return $where;
	}

    /**
    * BACKEND
    * Adding the meta boxes to the edit page
    */
   public function add_exercise_meta_box() {
       if(isset($_GET['post'])) {
           add_meta_box("ts-exercise-option-meta-box", "Übungs-Optionen", array($this, "custom_ts_exercise_options_meta_box_markup"), "uebungen", "normal", "high", null);
           add_meta_box("ts-exercise-pages-meta-box", "Übung wird verwendet in:", array($this, "custom_exercise_pages_meta_box_markup"), "uebungen", "normal", "high", null);
           add_meta_box("ts-exercise-export-meta-box", "&nbsp;", array($this, "custom_ts_exercise_export_meta_box_markup"), "uebungen", "side", "high", null);
       } else {
           add_meta_box("ts-exercise-titlefirst-meta-box", "Bitte einen Titel vergeben", array($this, "custom_ts_exercise_titlefirst_meta_box_markup"), "uebungen", "normal", "high", null);
       }
   }

   /**
    * BACKEND
    * Add the warning box if a newly created exercise has not yet been saved
    */
   public function custom_ts_exercise_titlefirst_meta_box_markup() {
       $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

       echo $twig->render('exercise/backend-exercise-titlefirst.html');
   }

   /**
	 * BACKEND
	 * Add the exercise options box
	 */
   public function custom_ts_exercise_options_meta_box_markup() {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        global $post;
		$id = $post->ID;
        $exerciseHeadline = json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_headline', true)));
        $exerciseShowBackground = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) : 1;
        $exerciseShowFavButton = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) : 1;

        echo $twig->render('exercise/backend-exercise-options.html', [
                                                    'exerciseHeadline' => $exerciseHeadline,
                                                    'exerciseShowBackground' => $exerciseShowBackground,
                                                    'exerciseShowFavButton' => $exerciseShowFavButton,
                                                    'exercise_id' => $id, 
                                                    'count' => Trainingssystem_Plugin_Database::getInstance()->Exercise->countExerciseFavorite($id)
                                                ]);
   }

    /**
    * BACKEND
    * Function to save the options for an exercies
    */

    public function saveExerciseOptions(){

        if(isset($_POST['postid']) && is_numeric($_POST['postid']) && 
            isset($_POST['exerciseHeadline']) && strlen(trim($_POST['exerciseHeadline'])) > 1){

            $postid = $_POST['postid'];
            $exerciseHeadlineStr = $_POST['exerciseHeadline'];
            $exerciseShowBackground = $_POST['exerciseShowBackground'];
            $exerciseShowFavButton = $_POST['exerciseShowFavButton'];
            $exerciseHeadline = json_decode(stripslashes($exerciseHeadlineStr), true);

            if(is_string(get_post_status($postid)) && json_last_error() === JSON_ERROR_NONE){
                update_post_meta($postid, 'tspv2_exercies_headline', json_encode($exerciseHeadline));  
                update_post_meta($postid, 'tspv2_exercies_showBackground', json_encode($exerciseShowBackground));  
                update_post_meta($postid, 'tspv2_exercies_showFavButton', json_encode($exerciseShowFavButton));  
            }
        }
        wp_die();
    }


   /**
	 * BACKEND
	 * Add the box in the sidebar with export/duplicate buttons
	 */
	public function custom_ts_exercise_export_meta_box_markup() {

		global $post;

		echo '<div class="wrapper-admin-backend"><button type="button" class="btn btn-secondary backend-export-ts-exercise" data-exerciseid="' . $post->ID . '"><i class="fas fa-file-export"></i>&nbsp;Übung exportieren</button></div>';
		echo '<div class="wrapper-admin-backend"><button type="button" class="btn btn-secondary backend-duplicate-ts-exercise mt-3" data-exerciseid="' . $post->ID . '"><i class="fas fa-clone"></i>&nbsp;Übung duplizieren</button></div>';
	}

	/**
	 * BACKEND/ADMIN
	 * Adds an import button to the subsubsub menu of the exercise-table
	 */
	public function backendAddImportAction($views) {
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$views['import_exercise'] = $twig->render("exercise/backend-exercise-import.html") . '<style>#the-list td.column-post_type, .table-view-list th.column-post_type { display: none; } </style>';

		return $views;
	}

    /**
	 * BACKEND
	 * Add the box that displays on which pages the exercise is being used when requested
	 */
	public function custom_exercise_pages_meta_box_markup() {
		global $post;

		$id = $post->ID;

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

		echo $twig->render('exercise/backend-exercise-pages.html', ["id" => $id]);
	}

    /**
	 * BACKEND
	 * Returns a list with pages the exercise is used in
	 */
	public function getPagesWithExercise() {
		global $wpdb;

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

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

			$id = sanitize_text_field($_POST['exerciseid']);

			$sql = "SELECT `ID`, `post_title`, `post_type` FROM $wpdb->posts WHERE `post_content` REGEXP '[ts_exercise id=[\']?" . $id . "[\']?]' AND `post_status` = 'publish' ORDER BY `post_title` ASC";
			$result = $wpdb->get_results($sql);
			
			$pages = array();
			$i = 0;
			if($result) {
				foreach($result as $row) {
					$pages[$i]['id'] = $row->ID;
					$pages[$i]['title'] = $row->post_title;
					$pages[$i]['type'] = ucfirst($row->post_type);
					$pages[$i]['url'] = get_permalink($row->ID);
					$pages[$i]['edit_url'] = get_edit_post_link($row->ID);
					$i++;
				}
			}
	
			echo $twig->render('exercise/backend-exercise-pages-list.html', ["pages" => $pages]);

		}
		wp_die();
	}


    /**
     * BACKEND
     * 
     * Fires when exercise is deleted, deletes all exercises referenced in the ts_exercise database table
     */
    public function backendDeleteExercise($postid) {
        if(strtolower(get_post_type($postid)) === "uebungen") {
			Trainingssystem_Plugin_Database::getInstance()->Exercise->deleteAllExercises($postid);
		}
    }

    /**
	 * BACKEND/ADMIN
	 * Adds an export and duplicate button to each exercise row action list
	 */
	public function backendAddExportAction($actions, $post) {
		
		if(strtolower($post->post_type) === "uebungen") {
			$actions['export_link'] = '<div class="wrapper-admin-backend" style="display:inline"><button type="button" class="btn btn-secondary btn-sm backend-export-ts-exercise" data-exerciseid="' . $post->ID . '">Export</button></div>';
			$actions['duplicate_link'] = '<div class="wrapper-admin-backend" style="display:inline"><button type="button" class="btn btn-secondary btn-sm backend-duplicate-ts-exercise" data-exerciseid="' . $post->ID . '">Duplizieren</button></div>';
		}

		return $actions;
	}

	/**
	 * BACKEND/ADMIN
	 * Exports an exercise as a json file and returns this content to the browser
	 */
	public function backendExportExercise() {

		if(isset($_POST['exerciseid']) && is_numeric($_POST['exerciseid']) && strtolower(get_post_type($_POST['exerciseid'])) === "uebungen") {
			$filename = "Übungsexport-" . current_time("d-m-Y-H-i-s") . ".json";

			header('Content-type: application/json; charset=utf-8');
			header('Content-disposition: attachment; filename="' . utf8_decode(htmlspecialchars_decode($filename)) . '"');

			echo $this->exportExercise($_POST['exerciseid']);
		} else {
			echo "0";
		}
		wp_die();
	}

	/**
	 * BACKEND/ADMIN
	 * Duplicates an exercise with the helper ex-/import funtions and returns a link to the edit page of the new exercise
	 */
	public function backendDuplicateExercise() {
		if(isset($_POST['exerciseid']) && is_numeric($_POST['exerciseid']) && strtolower(get_post_type($_POST['exerciseid'])) === "uebungen") {
			
			$export = $this->exportExercise($_POST['exerciseid']);

			$importdata = json_decode($export, true);

			if(isset($importdata['title'])) {
				$importdata['title'] .= " Kopie";
			}

			$import = $this->importExercise($importdata);
			if($import != null && is_numeric($import)) {
				echo get_edit_post_link($import, "");
			}
		}
		wp_die();
	}

	/**
	 * BACKEND/ADMIN
	 * Imports an exercise of a json file and returns the edit link to the newly created exercise
	 */
	public function backendImportExercise() {
		$countfiles = sizeof($_FILES['file']['name']);
		
		for($i = 0; $i < $countfiles; $i++) {
			if(!isset($_FILES['file']['name'][$i]) ||
					$_FILES['file']['error'][$i] != UPLOAD_ERR_OK ||
					!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
					{
						wp_die();
					}
		}
		
		for($i = 0; $i < $countfiles; $i++) {
			$filecontent = file_get_contents($_FILES['file']['tmp_name'][$i]);

			$import = $this->importExercise($filecontent);

			if($import != null && is_numeric($import)) {
				$editlink = get_edit_post_link($import, "");
			} else {
				wp_die();
			}
		}

		if($countfiles > 1) {
			echo "edit.php?post_type=uebungen";
		} else {
			echo $editlink;
		}
		wp_die();
	}

    /**
     * FRONTEND
     * 
     * Shortcode [ts_exercise id='']
     * Displays Exercise content and has buttons for favorite/unfavorite
     */
    public function showExercise($atts) {

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

		if(isset($atts['id']) && is_numeric($atts['id']) && strtolower(get_post_type($atts['id'])) === "uebungen") {

			$exerciseid = $atts['id'];

			
            $post = get_post($exerciseid);
            $content = $post->post_content;
            $exerciseHeadline = (json_decode(stripslashes(get_post_meta($exerciseid, 'tspv2_exercies_headline', true))) != null) ? json_decode(stripslashes(get_post_meta($exerciseid, 'tspv2_exercies_headline', true))) : "h3";
            $exerciseShowBackground = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) : 1;
            $exerciseShowFavButton = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) : 1;
     
            if(!has_shortcode($content, 'ts_exercise')) { 

                $usermodus = false;
                $uid = get_current_user_id();
                $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
                if ($selectui != '') {
                    $uid = $selectui;
                    $usermodus = true;
                }
                
                $trainingsID = isset($_GET['idt1']) ? htmlspecialchars(preg_replace('/[^0-9]/', '', $_GET['idt1'])) : '';
                $lektionID = isset($_GET['idt2']) ? htmlspecialchars(preg_replace('/[^0-9]/', '', $_GET['idt2'])) : '';
                $seitenID = '';
                if(isset($_GET['seiten'])) {
                    $seitenPost = get_posts(["name" => $_GET['seiten'], "post_type" => 'seiten', "post_status" => "publish"]);
                    if(isset($seitenPost[0]) && null !== $seitenPost[0])
                        $seitenID = $seitenPost[0]->ID;
                }

                $isFavorite = Trainingssystem_Plugin_Database::getInstance()->Exercise->exerciseIsFavorite($exerciseid, $uid);

                return $twig->render("exercise/exercise.html", ["usermodus" => $usermodus, 
                                                                "exercise_id" => $exerciseid, 
                                                                "exercise_title" => $post->post_title,
                                                                "content" => do_shortcode($content),
                                                                "trainingid" => $trainingsID,
                                                                "lektionid" => $lektionID,
                                                                "seitenid" => $seitenID,
                                                                "url" => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
                                                                "isFavorite" => $isFavorite,
                                                                "showSource" => false,
                                                                "favoritePage" => false,
                                                                "exerciseHeadline" => $exerciseHeadline,
                                                                "exerciseShowBackground" => $exerciseShowBackground,
                                                                "exerciseShowFavButton" => $exerciseShowFavButton,
                                                            ]);
            } else {
                return $twig->render("exercise/exercise-error-recursion.html");
            }
		} else {
			return $twig->render("exercise/exercise-error.html");
		}
    }

    /**
     * 
     * AJAX/FRONTEND
     * 
     * Called when a user clicks the favorite/unfavorite button on the frontend
     */
    public function handleFavoriteClicked() {
        if(isset($_POST['mode']) && ($_POST['mode'] == "favorite" || $_POST['mode'] == "unfavorite") &&
            isset($_POST['exerciseid']) && is_numeric($_POST['exerciseid']) && get_post_type($_POST['exerciseid']) == "uebungen" &&
            isset($_POST['trainingid']) && ((is_numeric($_POST['trainingid']) && get_post_type($_POST['trainingid']) == "trainings") || trim($_POST['trainingid']) == "") &&
            isset($_POST['lektionid']) && ((is_numeric($_POST['lektionid']) && get_post_type($_POST['lektionid']) == "lektionen") || trim($_POST['lektionid']) == "") &&
            isset($_POST['seitenid']) && ((is_numeric($_POST['seitenid']) && get_post_type($_POST['seitenid']) == "seiten") || trim($_POST['seitenid']) == "") &&
            isset($_POST['url']) && trim($_POST['url']) != "") {

                $userid = get_current_user_id();
                $exerciseid = $_POST['exerciseid'];
                $trainingid = trim($_POST['trainingid']) == "" ? null : $_POST['trainingid'];
                $lektionid = trim($_POST['lektionid']) == "" ? null : $_POST['lektionid'];
                $seitenid = trim($_POST['seitenid']) == "" ? null : $_POST['seitenid'];
                $url = $_POST['url'];

                if($_POST['mode'] == "favorite") {
                    if(Trainingssystem_Plugin_Database::getInstance()->Exercise->favoriteExercise($exerciseid, $userid, $trainingid, $lektionid, $seitenid, $url)) {
                        echo "1";
                    } else {
                        echo "0";
                    }
                } else {
                    if(Trainingssystem_Plugin_Database::getInstance()->Exercise->unfavoriteExercise($exerciseid, $userid)) {
                        echo "1";
                    } else {
                        echo "0";
                    }
                }

            }
        wp_die();
    }

    /**
     * FRONTEND
     * 
     * Shows a users favorite exercises on one page
     */
    public function showFavoriteExercises($atts) {

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

        $uid = get_current_user_id();

        if(0 !== $uid) {
            $usermodus = false;
            $selectui = '' . get_user_meta(wp_get_current_user()->ID, 'coach_select_user', true);
            if ($selectui != '') {
                $uid = $selectui;
                $usermodus = true;
            }
            
            $orderby = null;
            if(isset($atts['orderby']) && strlen(trim($atts['orderby'])) > 0) {
                $orderby = $atts['orderby'];
            }

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

            $favoriteExercises = Trainingssystem_Plugin_Database::getInstance()->Exercise->getFavoriteExerciseByUser($uid, $orderby);
            $options = array();

            foreach($favoriteExercises as $fe) {
                $fe->setContent(do_shortcode($fe->getContent()));
                $options['exerciseHeadline'] = (json_decode(stripslashes(get_post_meta($fe->getExercise_id(), 'tspv2_exercies_headline', true))) != null) ? json_decode(stripslashes(get_post_meta($fe->getExercise_id(), 'tspv2_exercies_headline', true))) : "h3";
                $options['exerciseShowBackground'] = (json_decode(stripslashes(get_post_meta($fe->getExercise_id(), 'tspv2_exercies_showBackground', true))) != null) ? json_decode(stripslashes(get_post_meta($fe->getExercise_id(), 'tspv2_exercies_showBackground', true))) : 1;
                $fe->options = $options;
            }


            return $twig->render('exercise/favorite-exercise.html', [
                                                                    "heading" => $heading,
                                                                    "favoriteExercises" => $favoriteExercises,
                                                                    "usermodus" => $usermodus,
                                                                    "trainings" => Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingTitle(),
                                                                    "lektionen" => array(), // currently not used, but prepared: Trainingssystem_Plugin_Database::getInstance()->LektionDao->getLektionTitle(),
                                                                    "seiten" => array(), // currently not used, but prepared: Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getSeitenTitle()
                                                                ]);

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

    /**
	 * HELPER
	 * Exports an Exercise to migrate within multiple platforms, either as JSON or as PHP Array
	 * 
	 * @param int exercise ID
	 * @param boolean return JSON encoded, default true
	 * 
	 * @return String Exercise with tsforms (optional) and settings as JSON or PHP Array
	 */
	public function exportExercise($exerciseid, $jsonencoded = true) {
		$ret = array();

		if(strtolower(get_post_type($exerciseid)) === "uebungen") {

			$post = get_post($exerciseid);

            $ret['title'] = $post->post_title;
            $ret['headline'] = (json_decode(stripslashes(get_post_meta($exerciseid, 'tspv2_exercies_headline', true))) != null) ? json_decode(stripslashes(get_post_meta($exerciseid, 'tspv2_exercies_headline', true))) : "h3";
            $ret['showBackground'] = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showBackground', true))) : 1;
            $ret['showFavButton'] = (json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) != null) ? json_decode(stripslashes(get_post_meta($post->ID, 'tspv2_exercies_showFavButton', true))) : 1;
     
			$ret['tsforms'] = array();

            $tsFormsModule = new Trainingssystem_Plugin_Module_TS_Forms();

            $regex = "/\[[\wöäüßÖÄÜ0-9-_?! :.,;\/{}()=\"'…\n\r]+\]?/";
            preg_match_all($regex, $post->post_content, $matches);
            $all_shortcodes_list = array();
            $s_index = 0;
            foreach ($matches[0] as $match) {
                if (!$this::startsWith($match, "[/")) { // no closing tags here
                    $all_shortcodes_list[$s_index]['original_shortcode'] = $match;
                    if (strpos($match, " ") !== false) {
                        $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strpos($match, " "));
                        $all_shortcodes_list[$s_index] = array_merge($all_shortcodes_list[$s_index], array_slice(shortcode_parse_atts(substr($match, 1, strlen($match) - 2)), 1));
                    } else {
                        $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strlen($match) - 2);
                    }
                    $s_index++;
                }
            }

            $replace_shortcodes = array();
            $rs_index = 0;
            foreach ($all_shortcodes_list as $shortcode) {
                switch (trim($shortcode['shortcode_name'])) {

                    case "coach_output_format_data":
                    case "tspv2_coach_output_format_data":
                    case "coach_output_list_data":
                    case "tspv2_coach_output_list_data":

                        if (isset($shortcode['id']) && strtolower(get_post_type($shortcode['id'])) == "formulare") {
                            $tsforms_valid = true;
                            if (!isset($ret['tsforms'][$shortcode['id']])) {
                                $export = $tsFormsModule->exportForm($shortcode['id'], false);
                                if(!empty($export)) {
                                    $ret['tsforms'][$shortcode['id']]['uid'] = bin2hex(random_bytes(32));
                                    $ret['tsforms'][$shortcode['id']]['export'] = $export;
                                } else {
                                    $tsforms_valid = false;
                                }
                            }
                            if($tsforms_valid) {
                                $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                                $replace_shortcodes[$rs_index]['new'] = preg_replace("/id=[\"']?" . $shortcode['id'] . "[\"']?/", "id='" . $ret['tsforms'][$shortcode['id']]['uid'] . "'", $shortcode['original_shortcode']);
                                $rs_index++;
                            }
                        }
                        break;
                    case "ts_forms":
                        if (isset($shortcode['id'])) {
                            $tsforms_valid = true;
                            if (!isset($ret['tsforms'][$shortcode['id']])) {
                                $export = $tsFormsModule->exportForm($shortcode['id'], false);
                                if(!empty($export)) {
                                    $ret['tsforms'][$shortcode['id']]['uid'] = bin2hex(random_bytes(32));
                                    $ret['tsforms'][$shortcode['id']]['export'] = $export;
                                } else {
                                    $tsforms_valid = false;
                                }
                            }
                            if($tsforms_valid) {
                                $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                                $replace_shortcodes[$rs_index]['new'] = preg_replace("/id=[\"']?" . $shortcode['id'] . "[\"']?/", "id='" . $ret['tsforms'][$shortcode['id']]['uid'] . "'", $shortcode['original_shortcode']);
                                $rs_index++;
                            }
                        }
                        break;
                    case "ts_forms_conditional":
                    case "ts_forms_conditional-inner1":
                    case "ts_forms_conditional-inner2":
                    case "ts_forms_conditional-inner3":
                        if (isset($shortcode['tsformid'])) {
                            $tsforms_valid = true;
                            if (!isset($ret['tsforms'][$shortcode['tsformid']])) {
                                $export = $tsFormsModule->exportForm($shortcode['tsformid'], false);
                                if(!empty($export)) {
                                    $ret['tsforms'][$shortcode['tsformid']]['uid'] = bin2hex(random_bytes(32));
                                    $ret['tsforms'][$shortcode['tsformid']]['export'] = $export;
                                } else {
                                    $tsforms_valid = false;
                                }
                            }
                            if($tsforms_valid) {
                                $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                                $replace_shortcodes[$rs_index]['new'] = preg_replace("/tsformid=[\"']?" . $shortcode['tsformid'] . "[\"']?/", "tsformid='" . $ret['tsforms'][$shortcode['tsformid']]['uid'] . "'", $shortcode['original_shortcode']);
                                $rs_index++;
                            }
                        }
                        break;
                }
            }

            $replace = array();
            $rep_index = 0;
            foreach ($replace_shortcodes as $rep_a_val) {
                $found = false;

                foreach ($replace as $rep_n_val) {
                    if ($rep_a_val['old'] === $rep_n_val['old'] &&
                        $rep_a_val['new'] === $rep_n_val['new']) {
                        $found = true;
                        break;
                    }
                }

                if (!$found) {
                    $replace[$rep_index]['old'] = $rep_a_val['old'];
                    $replace[$rep_index]['new'] = $rep_a_val['new'];
                    $rep_index++;
                }
            }

            $ret['content'] = $this->replaceShortcodeIds($post->post_content, $replace);
			
		}

		if($jsonencoded) {
			return json_encode($ret);
		} else {
			return $ret;
		}
	}

    /**
	 * HELPER
	 * Imports an exercise
	 * 
	 * @param Array|String data: if data is not an array, we try to json_deocde it, otherwise this function won't do anything
	 * 
	 * @return null|int Returns the int of the newly created exercise on success or null if anything went wrong
	 */
	public function importExercise($data) {

		if(!is_array($data)) {
			$jsondata = json_decode($data, true);
			if(json_last_error() == JSON_ERROR_NONE) {
				$data = $jsondata;
			}
		}

		if(is_array($data) && isset($data['title']) && isset($data['content']) && isset($data['tsforms'])) {

            $replace_uid_fid = array();
            $rp_index = 0;

            $tsFormsModule = new Trainingssystem_Plugin_Module_TS_Forms();

            foreach($data['tsforms'] as $import_tsform) {
                $newtsid = $tsFormsModule->importForm($import_tsform['export']);

                if($newtsid != null && is_numeric($newtsid)) {
                    $replace_uid_fid[$rp_index]['old'] = $import_tsform['uid'];
                    $replace_uid_fid[$rp_index]['new'] = $newtsid;
                    $rp_index++;
                } else {
                    echo "Fehler bei TS Forms Import";
                    wp_die();
                }
            }
            
            if(count($data['tsforms']) === count($replace_uid_fid)) {

                $wp_exercise = array(
                    "post_title" => $data['title'],
                    "post_status" => "publish",
                    "post_type" => "uebungen",
                    "post_content" => $this->replaceShortcodeIds($data['content'], $replace_uid_fid)
                );

                $wp_exercise_id = wp_insert_post($wp_exercise);

                if(!is_wp_error($wp_exercise_id)) {

                    update_post_meta($wp_exercise_id, 'tspv2_exercies_headline', json_encode($data['headline']));  
                    update_post_meta($wp_exercise_id, 'tspv2_exercies_showBackground', json_encode($data['showBackground']));  
                    update_post_meta($wp_exercise_id, 'tspv2_exercies_showFavButton', json_encode($data['showFavButton']));  

                    return $wp_exercise_id;

                } else {
                    return null;
                }
            } else {
                return null;
            }

		} else {
			return null;
		}
	}

    public function replaceShortcodeIds($text, $replacearray = array())
    {
        $ret = $text;
        if (strlen(trim($text)) > 0) {
            foreach ($replacearray as $replace) {
                $ret = str_replace($replace['old'], $replace['new'], $ret);
            }
        }
        return $ret;
    }

    public function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }

    public function endsWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }
}