<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Trainingssystem_Plugin
 * @subpackage Trainingssystem_Plugin/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Trainingssystem_Plugin
 * @subpackage Trainingssystem_Plugin/public
 * @author     Markus Domin, Helge Nissen <->
 */
class Trainingssystem_Plugin_Public
{

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of the plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
        add_filter('login_redirect', array($this, 'tspv2_login_redirect'), 10, 3);

        if (isset($settings["after_registration_text"]) && $settings["after_registration_text"] != "") {
            add_filter( 'wp_login_errors', array($this,'change_registration_text'), 10, 2 );
        }

        if(isset($settings['disable_language_dropdown']) && $settings['disable_language_dropdown']) {
            add_filter( 'login_display_language_dropdown','__return_false');
        }
    }
    
    /**
     * Change text after registration
     *
     * @since    1.0.0
     */
    public function change_registration_text($errors){
        if( isset( $errors->errors['registered'])){
            $errors->errors['registered'] = array(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["after_registration_text"]);
        }  
            return $errors;
    }

    /**
     * Redirect to dashboard
     *
     * @since    1.0.0
     */
    public function tspv2_login_redirect($redirect_to, $request, $user)
    {
        if(!is_wp_error($user)) {
            $redirectTraining = get_user_meta($user->ID, 'redirectTraining', true);

            if(!empty($redirectTraining) && is_numeric($redirectTraining) && get_post_type($redirectTraining) == "trainings") {

                $training = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingByUser($redirectTraining, $user->ID);
                if($training->getFin() < 100 && count($training->getLektionsliste()) > 0 && $training->trainingEnabled()) {
                    $lastPage = $training->getLastPage();
                    
                    if(is_null($lastPage)) {
                        return $training->getLektionsliste()[0]->getFirstPageUrl();
                    } else {
                        return $lastPage->getUrl();
                    }
                } elseif($training->getFin() == 100 || count($training->getLektionsliste()) == 0) {
                    delete_user_meta($user->ID, 'redirectTraining');
                }
            }

            if(isset($_COOKIE['redirectOnce']) && trim($_COOKIE['redirectOnce']) != "") {

                $redirect = $_COOKIE['redirectOnce'];
                unset($_COOKIE['redirectOnce']);
                setcookie("redirectOnce", "", -1);

                return $redirect;
            }

            $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
            if (isset($settings["dashboard_redirect"]) && $settings["dashboard_redirect"] != "0") {
                return get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["dashboard"]);
            }
        } 
        return get_site_url();
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles()
    {
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS, []);


        // enqueue parent styles
        if(!isset($settings["block_bootstrap"]) || $settings["block_bootstrap"] != 1) {
            wp_enqueue_style($this->plugin_name . '_parent-style', plugin_dir_url(__FILE__) . '../assets/external/bootstrap-4/bootstrap.min.css');
            wp_enqueue_style($this->plugin_name . '_bs-slider-style', plugin_dir_url(__FILE__) . '../assets/external/bootstrap-4/bootstrap-slider.min.css');
        }

        if(!isset($settings["block_fontawesome"]) || $settings["block_fontawesome"] != 1) {
            wp_enqueue_style($this->plugin_name . '_fontawesome-style', plugin_dir_url(__FILE__) . '../assets/external/fontawesome-free-5.6.1-web/css/all.css');
        }
        
        if(!isset($settings["block_bootstrapTable"]) || $settings["block_bootstrapTable"] != 1) {
            wp_enqueue_style($this->plugin_name . '_bootstrap-table', plugin_dir_url(__FILE__) . '../assets/external/bootstrap-table-1.15.5/bootstrap-table.min.css');
        }

        // Flatpickr CSS (global verfügbar, CDN)
        wp_enqueue_style(
            $this->plugin_name . '_flatpickr_css',
            'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.css',
            [],
            '4.6.13'
        );
        
        wp_enqueue_style($this->plugin_name . '_style', plugin_dir_url(__FILE__) . '../assets/css/style.css');

    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS, []);

        if(!isset($settings["block_jqueryui"]) || $settings["block_jqueryui"] != 1) {
            wp_enqueue_script($this->plugin_name . '_jqueryui_js',plugin_dir_url(__FILE__) . '../assets/external/jquery-ui-1.12.1/jquery-ui.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_jqueryuiTouch_js',plugin_dir_url(__FILE__) . '../assets/external/jQueryUITouchPunch/jquery.ui.touch-punch.min.js', array('jquery'));
        }

        if(!isset($settings["block_bootstrapTable"]) || $settings["block_bootstrapTable"] != 1) {
            wp_enqueue_script($this->plugin_name . '_bootstrap-table_js',plugin_dir_url(__FILE__) . '../assets/external/bootstrap-table-1.15.5/bootstrap-table.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_bootstrap-table_filer_controll_js',plugin_dir_url(__FILE__) . '../assets/external/bootstrap-table-1.15.5/extensions/filter-control/bootstrap-table-filter-control.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_bootstrap-table_multiple-sort_js',plugin_dir_url(__FILE__) . '../assets/external/bootstrap-table-1.15.5/extensions/multiple-sort/bootstrap-table-multiple-sort.min.js', array('jquery'));
        }

        if(!isset($settings["block_jspdf"]) || $settings["block_jspdf"] != 1) {
            wp_enqueue_script($this->plugin_name . '_jspdf',plugin_dir_url(__FILE__) . '../assets/external/jspdf/jspdf.umd.min.js', array('jquery'));
        }
        
        if(!isset($settings["block_chartJS"]) || $settings["block_chartJS"] != 1) {
            wp_enqueue_script($this->plugin_name . '_moment',plugin_dir_url(__FILE__) . '../assets/external/chartjs/moment/moment.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_chartjs',plugin_dir_url(__FILE__) . '../assets/external/chartjs/chartjs/chart.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_hammerjs',plugin_dir_url(__FILE__) . '../assets/external/chartjs/hammer/hammer.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_chartjs_zoom',plugin_dir_url(__FILE__) . '../assets/external/chartjs/zoom/chartjs-plugin-zoom.min.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_adapter-moment',plugin_dir_url(__FILE__) . '../assets/external/chartjs/moment/adapter-moment.js', array('jquery'));
            wp_enqueue_script($this->plugin_name . '_chartjs-datalabels',plugin_dir_url(__FILE__) . '../assets/external/chartjs/datalabels/chartjs-plugin-datalabels.min.js', array('jquery'));
        }

        if(!isset($settings["block_bootstrap"]) || $settings["block_bootstrap"] != 1) {
            wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . '../assets/external/bootstrap-4/bootstrap.js', array('jquery'), $this->version, false);
            wp_enqueue_script($this->plugin_name . "_slider_js", plugin_dir_url(__FILE__) . '../assets/external/bootstrap-4/bootstrap-slider.min.js', array('jquery'), $this->version, false);
        }
        
        // Flatpickr JS (global verfügbar, CDN)
        wp_enqueue_script(
            $this->plugin_name . '_flatpickr_js',
            'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/flatpickr.min.js',
            [],
            '4.6.13',
            true
        );
        wp_enqueue_script(
            $this->plugin_name . '_flatpickr_de',
            'https://cdn.jsdelivr.net/npm/flatpickr@4.6.13/dist/l10n/de.js',
            [$this->plugin_name . '_flatpickr_js'],
            '4.6.13',
            true
        );

        if(!isset($settings["block_highchart"]) || $settings["block_highchart"] != 1) {
            wp_enqueue_script($this->plugin_name . "_hightcharts1", plugin_dir_url(__FILE__) . '../assets/external/highcharts/highcharts.js', array('jquery'), $this->version, false);
            wp_enqueue_script($this->plugin_name . "_hightcharts2", plugin_dir_url(__FILE__) . '../assets/external/highcharts/highcharts-more.js', array('jquery'), $this->version, false);
            wp_enqueue_script($this->plugin_name . "_hightcharts3", plugin_dir_url(__FILE__) . '../assets/external/highcharts/exporting.js', array('jquery'), $this->version, false);
        }

        wp_enqueue_script($this->plugin_name . "_script", plugin_dir_url(__FILE__) . '../assets/js/script.js', array('jquery'), $this->version, false);

        $logout_time = 15 * 60 * 1000;
        if(isset($settings['logout_time']) && is_numeric($settings['logout_time'])) {
            $logout_time = absint($settings['logout_time']) * 60 * 1000;
        }
        wp_localize_script($this->plugin_name . "_script", TRAININGSSYSTEM_PLUGIN_AJAX, array(TRAININGSSYSTEM_PLUGIN_AJAX_URL => admin_url('admin-ajax.php'), TRAININGSSYSTEM_PLUGIN_LOGOUT_TIME => $logout_time));

    }

    /**
     * Register get parameter.
     *
     * @since    1.0.0
     */
    public function add_custom_query_var($vars)
    {
        $vars[] = 'idt1';
        $vars[] = 'idt2';
        return $vars;
    }
    /**
     * [trainings_add_lektionen_footer_frontend description]
     * @param [type] $content [description]
     */
    public function trainings_add_lektionen_footer_frontend($content)
    {
        global $post;
        if ($post->post_type == 'trainings') {
            $content = '['.TRAININGSSYSTEM_PLUGIN_SHORTCODE_PREFIX.'user_training_lektionen]';
        }
        return $content;
    }
    /**
     * [seiten_add_button_footer_frontend description]
     * @param [type] $content [description]
     */
    public function seiten_add_button_footer_frontend($content)
    {
        global $post;
        if ($post->post_type == 'seiten') {
            $content = $this->check_trainings_user_seiten_permission($content);
        }
        return $content;
    }

    /**
     * [check_trainings_user_seiten_permission description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function check_trainings_user_seiten_permission($content)
    {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        $trainingsID = htmlspecialchars(preg_replace("/[^0-9]/", "", get_query_var('idt1') . ""));
        $lektionsID = htmlspecialchars(preg_replace("/[^0-9]/", "", get_query_var('idt2') . ""));
        $postID = get_the_ID();
        $userid = $this->getTrainingUser();

        // Kalenderzugriff prüfen, falls Kalender-Parameter vorhanden sind
        $calendarIdParam = isset($_GET['calendar_id']) ? sanitize_text_field($_GET['calendar_id']) : '';
        $calendarDateParam = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : '';
        if($calendarIdParam !== '' || $calendarDateParam !== ''){
            if($calendarIdParam !== '' && $calendarDateParam === ''){
                return $twig->render('training-lektion/training-lektion-access-denied.html', [
                    "home_url" => get_home_url(),
                    "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                ]);
            }
            if(!$this->isCalendarTrainingEnabled($trainingsID) || !$this->isCalendarAccessValid($trainingsID)){
                return $twig->render('training-lektion/training-lektion-access-denied.html', [
                    "home_url" => get_home_url(),
                    "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                ]);
            }
        }

        $training = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingByUser($trainingsID, $userid);
        $lektionen = $training->getLektionsliste();
        $canSeeHiddenTrainings = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden");

        $skipDashboard = false;
        $skipDashboardMeta = get_post_meta($trainingsID, 'skipDashboard', false);
        if(isset($skipDashboardMeta[0]) && !empty($skipDashboardMeta[0])) {
			$skipDashboard = true;
		}
        
        $current_user = wp_get_current_user();
        if (0 == $current_user->ID && !$skipDashboard) {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        } else if (0 == $current_user->ID && $skipDashboard) {
            $hrefAfterLogin = null;
            if($training->getFin() < 100 && ($training->trainingEnabled()) || !$training->trainingEnabled() && $canSeeHiddenTrainings) {
                $hrefAfterLogin = add_query_arg(array("idt1" => $trainingsID, "idt2" => $lektionsID), get_permalink($postID));
            }
            return $twig->render('modal-login.html', ["title" => get_bloginfo('name'), "url" => $hrefAfterLogin, "login_url" => wp_login_url(), "modalid" => uniqid()]);
        } else {

            $usercheck = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->checkpermissions($trainingsID, $userid, $postID, $canSeeHiddenTrainings);
            
            if ($usercheck || $canSeeHiddenTrainings) {
                $content .= '['.TRAININGSSYSTEM_PLUGIN_SHORTCODE_PREFIX.'user_training_lektion_bottom_nav]';

                if($canSeeHiddenTrainings && !$training->trainingEnabled() && !empty($trainingsID) && !empty($lektionsID)) {
                    $content .= $twig->render("training-lektion/training-lektion-editor-notice.html");
                }
            } else {
                return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
            }
        }
        return $content;
    }

    /**
     * [training_user_overview description]
     * @return [type] [description]
     */
    public function training_user_overview($atts)
    {
        $heading = isset($atts['titel']) ? $atts['titel'] : 'Meine Trainings'; 

        $category = null;
        $category_text = null;
        $showCategoryName = true;
        if(isset($atts['category']) && trim($atts['category']) != "") {
            $category = $atts['category'];

            if(isset($atts['category_text']) && trim($atts['category_text']) != "") {
                $category_text = $atts['category_text'];
            }

            if(isset($atts['show_category_name']) && (trim($atts['show_category_name']) == "0" || trim($atts['show_category_name']) == "false")){
                $showCategoryName = false;
            }
        }

        $groupbycategories = false;
        if(isset($atts['grouped']) && (trim($atts['grouped']) == "1" || trim($atts['grouped']) == "true")) {
            $groupbycategories = true;
        }
        
        $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()]);
        } else {
            
            $gridview=false;
            if (!get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS) || !isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["training_gridview"])) {

            } else {
                $gridview = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["training_gridview"];
            }


            $userid = $this->getTrainingUser();

            $trainingdata = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userid);

            $notrainings = true;
            $canSeeHiddenTrainings = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden");

            $exclude = array();
            if(isset($atts['exclude']) && trim($atts['exclude']) != "") {
                $excludeAtts = explode("|",$atts['exclude']);
                foreach($excludeAtts as $excludeAtt){
                    $exclude[] = trim($excludeAtt);
                }
            }
     
            $trainings_grouped = array();
            if($category != null) {
                $trainings_grouped[0] = array();
                $trainings_grouped[0]['name'] = $category;
                $trainings_grouped[0]['trainings'] = array();
                foreach($trainingdata as $training) {
                    if($training->hasCategory($category) && ($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings)) {
                        $trainings_grouped[0]['trainings'][] = $training;
                        $notrainings = false;
                    }
                }
            } else if($groupbycategories) {
                $nocategories = array();
                foreach($trainingdata as $training) {
                    $excludeTraining = false;
                    foreach($training->getCategories() as $trainingCat){
                        if(in_array($trainingCat, $exclude)){
                            $excludeTraining = true;
                        }
                    }
                    if(!$excludeTraining && ($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings)){
                        $cat = $training->getCategories();
                        if(sizeof($cat) > 0) {
                            foreach($cat as $tr_cat) {
                                
                                $groupedindex = null;
                                foreach($trainings_grouped as $key => $t) {
                                    if($t['name'] == $tr_cat) {
                                        $groupedindex = $key;
                                        break;
                                    }
                                }

                                if($groupedindex !== null) {
                                    $trainings_grouped[$groupedindex]['trainings'][] = $training;
                                    $notrainings = false;
                                } else {
                                    $index = sizeof($trainings_grouped);
                                    $trainings_grouped[$index] = array();
                                    $trainings_grouped[$index]['name'] = $tr_cat;
                                    $trainings_grouped[$index]['trainings'] = array();
                                    $trainings_grouped[$index]['trainings'][] = $training;
                                    $notrainings = false;
                                }
                            }
                        } else {
                            $nocategories[] = $training;
                        }
                    }
                }

                if(sizeof($nocategories) > 0) {
                    $nocatindex = sizeof($trainings_grouped);
                    $trainings_grouped[$nocatindex] = array();
                    $trainings_grouped[$nocatindex]['name'] = "Sonstige";
                    $trainings_grouped[$nocatindex]['trainings'] = $nocategories;
                    $notrainings = false;
                }
            } else {
                $trainingdata_filtered = [];
                foreach($trainingdata as $training) {
                    if($training->trainingEnabled() || !$training->trainingEnabled() && $canSeeHiddenTrainings) {
                        $trainingdata_filtered[] = $training;
                    }
                }
                $trainings_grouped[0] = array();
                $trainings_grouped[0]['name'] = "";
                $trainings_grouped[0]['trainings'] = $trainingdata_filtered;

                if(sizeof($trainingdata) > 0) {
                    $notrainings = false;
                }
            }

            $defaultimglink = get_header_image();
            
            $showLektionslisteArray = array();
            foreach($trainingdata as $t){
                $showLektionslisteMeta = get_post_meta($t->getId(), 'showLektionsliste', false);
                if(!empty($showLektionslisteMeta)){
                    $showLektionslisteArray[$t->getId()] = $showLektionslisteMeta[0];
                }
                else{
                    $showLektionslisteArray[$t->getId()] = "1";
                }
            }
            foreach($trainings_grouped as $category) {
                foreach($category['trainings'] as $t) {
                    if(isset($showLektionslisteArray[$t->getId()])) {
                        $t->setShowLektionsliste($showLektionslisteArray[$t->getId()]);
                    }
                }
            }

            return $twig->render($gridview ? 
                                    'training-overview/training-overview-kacheln.html' : 
                                'training-overview/training-overview.html', [
                'defaultimglink'=>$defaultimglink,
                'trainings' => $trainings_grouped,
                "url" => get_site_url(),
                "heading" => $heading,
                "notrainings" => $notrainings,
                "category_text" => $category_text,
                "show_category_name" => $showCategoryName,
                "userloggedin" => true,
                "category" => isset($atts['category']) ? $atts['category'] : "",
                'canSeeHiddenTrainings' => $canSeeHiddenTrainings,
                ]);

        }
        return "";
    }

    public function training_accordion($atts) {

        $defaultimglink = get_header_image();

        $training = array();
        $error = false;

        if(isset($atts['training']) && trim($atts['training']) != "") {
            if(is_numeric($atts['training']) && get_post_type($atts['training']) == "trainings") {

                $training[] = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById($atts['training']);

            } elseif(strpos($atts['training'], ';') !== false) {
                $exp = explode(";", $atts['training']);

                foreach($exp as $e) {
                    if(get_post_type($e) == "trainings") {
                        $training[] = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById($e);
                    } else {
                        $error = true;
                    }
                }
            }
        }
        foreach($training as $t){
            $showLektionslisteMeta = get_post_meta($t->getId(), 'showLektionsliste', false);
            if(!empty($showLektionslisteMeta)){
                $t->setShowLektionsliste($showLektionslisteMeta[0]);
            }
        }

        $trainings_grouped = array();
        $trainings_grouped[0]['trainings'] = $training;

        $userloggedin = false;
        $current_user = wp_get_current_user();
        if (0 != $current_user->ID) {
            $userloggedin = true;
        }

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

        if(sizeof($training) > 0 && !$error) {
            return $twig->render("training-overview/training-accordion.html", ["trainings" => $trainings_grouped, "defaultimglink" => $defaultimglink, "rand" => "-" . mt_rand(), "userloggedin" => $userloggedin]);
        } else {
            return $twig->render("training-overview/training-accordion-error.html");
        }
    }

    /**
     * [lektion_overview description]
     * @return [type] [description]
     */
    public function lektion_overview()
    {
        $content = get_the_content();
        
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        $trainingsID = get_the_ID();
        $userid = $this->getTrainingUser();
        $training = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingByUser($trainingsID, $userid);
        $lektionen = $training->getLektionsliste();
        $canSeeHiddenTrainings = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden");

        // Kalenderzugriff prüfen, falls Kalender-Parameter vorhanden sind
        $calendarIdParam = isset($_GET['calendar_id']) ? sanitize_text_field($_GET['calendar_id']) : '';
        $calendarDateParam = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : '';
        if($calendarIdParam !== '' || $calendarDateParam !== ''){
            if($calendarIdParam !== '' && $calendarDateParam === ''){
                return $twig->render('training-lektion/training-lektion-access-denied.html', [
                    "home_url" => get_home_url(),
                    "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                ]);
            }
            if(!$this->isCalendarTrainingEnabled($trainingsID) || !$this->isCalendarAccessValid($trainingsID)){
                return $twig->render('training-lektion/training-lektion-access-denied.html', [
                    "home_url" => get_home_url(),
                    "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                ]);
            }
        }

        $skipDashboard = false;
        $skipDashboardMeta = get_post_meta($trainingsID, 'skipDashboard', false);
        if(isset($skipDashboardMeta[0]) && !empty($skipDashboardMeta[0])) {
			$skipDashboard = true;
		}
        
        $current_user = wp_get_current_user();
        if (0 == $current_user->ID && !$skipDashboard) {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        } else if (0 == $current_user->ID && $skipDashboard) {
            if($training->getFin() < 100 && ($training->trainingEnabled()) || !$training->trainingEnabled() && $canSeeHiddenTrainings) {
                $trainingLink = get_permalink($trainingsID);
                $linkToHrefAfterLogin = $trainingLink;
            } else {
                $linkToHrefAfterLogin = get_site_url();
            }
            $linkToHrefAfterLogin = add_query_arg("skipDashboard", "1", $linkToHrefAfterLogin);
            return $twig->render('modal-login.html', ["title" => get_bloginfo('name'), "url" => $linkToHrefAfterLogin, "login_url" => wp_login_url(), "modalid" => uniqid()]);
        } else {
            
            if($training->trainingEnabled() || $canSeeHiddenTrainings) {
                $gridview=false;
                if (!get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS) || !isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["lektion_gridview"])) {

                } else {
                    $gridview = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["lektion_gridview"];
                }

                $defaultimglink = get_header_image();
                $training_title = get_the_Title();

                $contentPlacement = "top";
                $contentPlacementMeta = get_post_meta($trainingsID, 'contentPlacement', true);
                if(!empty($contentPlacementMeta)){
                    $contentPlacement = $contentPlacementMeta;
                }

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

                    $userlektionat = count($lektionen);
                    foreach($lektionen as $key => $lektion) {
                        if($lektion->getTrainingAuto() == "1") {
                            if($lektion->getFin() != 100)
                            {
                                $userlektionat = $key;
                                break;
                            }
                        } else if($lektion->getTrainingAuto() == "2") {
                            if($lektion->getFin() != 100 && !$lektion->isFeedback())
                            {   
                                $userlektionat = $key;
                                break;
                            }
                        }
                    }

                    $usercontinue = false;

                    if(isset($lektionen[$userlektionat-1]) && $lektionen[$userlektionat-1]->getTrainingAuto() == "2") {
                        if($key == 0 || (isset($lektionen[$key-1]) && $lektionen[$key-1]->isFeedback())) {
                            $usercontinue = true;
                        }
                    } else {
                        $usercontinue = true;
                    }

                    do_action('limesurvey_user', $trainingsID, $userid);

                    $preNotice = "";
                    if($canSeeHiddenTrainings && !$training->trainingEnabled()) {
                        $preNotice .= $twig->render("training-lektion/training-lektion-editor-notice.html");
                    }

                    // Kalender-Button-Logik für Training-Übersicht
                    $showZumKalenderButton = false;
                    $zumKalenderButtonLabel = '';
                    $zumKalenderButtonUrl = '';
                    
                    // Prüfe ob Kalender-Parameter vorhanden sind und Training als Kalender-Training aktiviert ist
                    if($calendarIdParam !== '' || $calendarDateParam !== '') {
                        if($this->isCalendarTrainingEnabled($trainingsID) && $this->isCalendarAccessValid($trainingsID)) {
                            // Lese calendar_options vom Kalender-Post
                            $calendarId = isset($_GET['calendar_id']) ? intval($_GET['calendar_id']) : 0;
                            $calendarOptionsRaw = null;
                            if($calendarId > 0 && get_post_type($calendarId) === 'kalender') {
                                $calendarOptionsRaw = get_post_meta($calendarId, 'calendar_options', true);
                            }
                            
                            if(!empty($calendarOptionsRaw)) {
                                if(is_string($calendarOptionsRaw)) {
                                    $decoded = json_decode($calendarOptionsRaw, true);
                                    if(json_last_error() === JSON_ERROR_NONE) {
                                        $calendarOptions = $decoded;
                                    } else {
                                        $calendarOptions = [];
                                    }
                                } else if(is_array($calendarOptionsRaw)) {
                                    $calendarOptions = $calendarOptionsRaw;
                                } else {
                                    $calendarOptions = [];
                                }
                                
                                // Prüfe ob target_url nur idt1 enthält (kein idt2)
                                if(isset($calendarOptions['target_url']) && trim($calendarOptions['target_url']) !== '') {
                                    $targetUrl = $calendarOptions['target_url'];
                                    $parts = wp_parse_url($targetUrl);
                                    if($parts !== false && isset($parts['query'])) {
                                        $targetParams = [];
                                        parse_str($parts['query'], $targetParams);
                                        
                                        $targetIdt1 = isset($targetParams['idt1']) ? $targetParams['idt1'] : '';
                                        $targetIdt2 = isset($targetParams['idt2']) ? $targetParams['idt2'] : '';
                                        
                                        // Button nur anzeigen wenn target_url nur idt1 hat (kein idt2)
                                        if($targetIdt1 !== '' && $targetIdt2 === '') {
                                            $showZumKalenderButton = true;
                                            $zumKalenderButtonLabel = isset($calendarOptions['zum_kalender_button_label']) ? $calendarOptions['zum_kalender_button_label'] : 'Zum Kalender';
                                            $zumKalenderButtonUrl = isset($calendarOptions['zum_kalender_button_url']) ? $calendarOptions['zum_kalender_button_url'] : '';
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // Kalender-Parameter zu Lektion-URLs hinzufügen
                    $lektionenList = $training->getLektionsliste();
                    $calendarId = isset($_GET['calendar_id']) ? sanitize_text_field($_GET['calendar_id']) : '';
                    $calendarDate = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : '';
                    
                    if($calendarId && $calendarDate) {
                        foreach($lektionenList as $lektion) {
                            $originalUrl = $lektion->getFirstPageUrl();
                            if($originalUrl) {
                                $newUrl = add_query_arg(array(
                                    'calendar_id' => $calendarId,
                                    'date' => $calendarDate
                                ), $originalUrl);
                                $lektion->setFirstPageUrl($newUrl);
                            }
                        }
                    }
                    
                    if($gridview){
                        return $preNotice . $twig->render('training-lektion/training-lektion-overview-kacheln.html', [
                            'defaultimglink'=>$defaultimglink,
                            'lektion_overview_list' => $lektionenList,
                            'usercontinue' => $usercontinue,
                            'userlektionat' => $userlektionat,
                            'limesurvey_status' => apply_filters('get_limesurvey_status', $trainingsID, $userid),
                            'training_title' => $training_title,
                            'content' => do_shortcode($content),
                            'contentPlacement' => $contentPlacement,
                            'showTrainingName'  => $showTrainingName,
                            'showZumKalenderButton' => $showZumKalenderButton,
                            'zumKalenderButtonLabel' => $zumKalenderButtonLabel,
                            'zumKalenderButtonUrl' => $zumKalenderButtonUrl,
                        ]);
                    }else{
                    
                        return $preNotice . $twig->render('training-lektion/training-lektion-overview.html', [
                            'defaultimglink'=>$defaultimglink,
                            'lektion_overview_list' => $lektionenList,
                            'usercontinue' => $usercontinue,
                            'userlektionat' => $userlektionat,
                            'limesurvey_status' => apply_filters('get_limesurvey_status', $trainingsID, $userid),
                            'training_title' => $training_title,
                            'content' => do_shortcode($content),
                            'contentPlacement' => $contentPlacement,
                            'showTrainingName'  => $showTrainingName,
                            'showZumKalenderButton' => $showZumKalenderButton,
                            'zumKalenderButtonLabel' => $zumKalenderButtonLabel,
                            'zumKalenderButtonUrl' => $zumKalenderButtonUrl,
                        ]);
                    }
                } else {
                    return $twig->render('training-lektion/training-lektion-access-denied.html', [
                        "home_url" => get_home_url(),
                        "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                    ]);
                }
            } else {
                return $twig->render('training-lektion/training-lektion-access-denied.html', [
                    "home_url" => get_home_url(),
                    "trainings_overview_url" => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"])
                ]);
            }
        }
        return "";
    }

    /**
     * [bottom_nav description]
     * @return [type] [description]
     */
    public function bottom_nav()
    {
        $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()]);
        } else {
            $trainingsID = htmlspecialchars(preg_replace('/[^0-9]/', '', get_query_var('idt1') . ''));
            $lektionID = htmlspecialchars(preg_replace('/[^0-9]/', '', get_query_var('idt2') . ''));
            $postID = get_the_ID();

            if($trainingsID != null && trim($trainingsID) != "" && is_numeric($trainingsID) &&
			    $lektionID != null && trim($lektionID) != "" && is_numeric($lektionID) &&
			    $postID != null && trim($postID) != "" && is_numeric($postID)) {

                $usermodus = $this->isUserModusRequest();
                $userid = $this->getTrainingUser();
                $currentpage = Trainingssystem_Plugin_Database::getInstance()->TrainingseitenDao->getTrainingsseite($trainingsID, $lektionID, $postID);
                
                Trainingssystem_Plugin_Database::getInstance()->NutzerDao->maybeUpdateLastPageOfLektion($currentpage, $userid, $usermodus);

                $training = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingByUser($trainingsID, $userid);
                $tlektion = array_filter($training->getLektionsliste(),
                    function ($e) use ($lektionID) {
                        return $e->getId() == $lektionID;
                    }
                );

                if ($tlektion != null) {

                    $trainingPost = get_post($trainingsID);
                    $saveUserEvent = true;
                    if(!empty($trainingPost->disableUserEvents) && $trainingPost->disableUserEvents == "1") {
                        $saveUserEvent = false;
                    }

                    if(!$usermodus && $saveUserEvent) {
                        // User Event
                        $title = "Seite „" . get_the_title($currentpage->getId()) . "“ besucht";
                        $subtitle = "";
                        $url = add_query_arg(array("idt1" => $trainingsID, "idt2" => $lektionID), get_permalink($postID));
                        // Params: $title, $subtitle, $userid, $postid, $url, $type, $level, $date (= null)
                        Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $userid, $postID, $url, "training", "detailed");
                    }

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

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

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

                    $Lektionen_Text="Lektionen";
                    if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['lektionen_text'])){
                        $Lektionen_Text = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['lektionen_text'];
                    }

                    $navigationTypeMeta = get_post_meta($trainingsID, 'trainingNavigationType', false);
		            if(!empty($navigationTypeMeta)){
			            $navigationType = $navigationTypeMeta[0];
		            }
		            else{
			            $navigationType = "all";
		            }

                    if($showNavigation) {
                        $useCalendarNav = $this->isCalendarTrainingEnabled($trainingsID) && $this->isCalendarAccessValid($trainingsID);
                        $templateName = $useCalendarNav
                            ? 'training-lektion/training-lektion-pages-bottom-nav-calendar.html'
                            : 'training-lektion/training-lektion-pages-bottom-nav.html';

                        // Kalender-Overrides für Button-Texte/Links
                        $calendarOverrideButtons = false;
                        $calendarOverrideLabel = '';
                        $calendarOverrideUrl = '';
                        $lektionenButtonLabel = '';
                        $lektionenButtonUrl = '';
                        $abschliessenButtonLabel = '';
                        $abschliessenButtonUrl = '';
                        $showCalendarIcon = false; // Standard-Wert setzen
                        $isSingleLesson = false; // Flag für einzelne Lektion
                        
                        // Prüfe ob es sich um eine einzelne Lektion handelt (auch außerhalb von useCalendarNav)
                        $calendarId = isset($_GET['calendar_id']) ? intval($_GET['calendar_id']) : 0;
                        $calendarOptionsRaw = null;
                        if($calendarId > 0 && get_post_type($calendarId) === 'kalender'){
                            $calendarOptionsRaw = get_post_meta($calendarId, 'calendar_options', true);
                        }
                        if(empty($calendarOptionsRaw)){
                            $calendarOptionsRaw = get_post_meta($trainingsID, 'calendar_options', true);
                        }
                        $calendarOptions = array();
                        if(is_string($calendarOptionsRaw) && trim($calendarOptionsRaw) !== ''){
                            $decoded = json_decode($calendarOptionsRaw, true);
                            if(json_last_error() === JSON_ERROR_NONE && is_array($decoded)){
                                $calendarOptions = $decoded;
                            }
                        } elseif(is_array($calendarOptionsRaw)){
                            $calendarOptions = $calendarOptionsRaw;
                        }
                        
                        // Prüfe ob target_url idt2 enthält (einzelne Lektion)
                        if(isset($calendarOptions['target_url']) && trim($calendarOptions['target_url']) !== ''){
                            $targetUrl = $calendarOptions['target_url'];
                            $parts = wp_parse_url($targetUrl);
                            if($parts !== false && isset($parts['query'])){
                                $params = array();
                                parse_str($parts['query'], $params);
                                $targetIdt2 = isset($params['idt2']) ? htmlspecialchars(preg_replace('/[^0-9]/', '', $params['idt2'] . '')) : '';
                                if($targetIdt2 !== ''){
                                    $isSingleLesson = true; // Es handelt sich um eine einzelne Lektion
                                }
                            }
                        }
                        
                        if($useCalendarNav) {

                            // Separate Button-Overrides lesen
                            $lektionenButtonLabel = isset($calendarOptions['lektionen_button_label']) ? $calendarOptions['lektionen_button_label'] : '';
                            $lektionenButtonUrl = isset($calendarOptions['lektionen_button_url']) ? $calendarOptions['lektionen_button_url'] : '';
                            $abschliessenButtonLabel = isset($calendarOptions['abschliessen_button_label']) ? $calendarOptions['abschliessen_button_label'] : '';
                            $abschliessenButtonUrl = isset($calendarOptions['abschliessen_button_url']) ? $calendarOptions['abschliessen_button_url'] : '';

                            // Icon-Logik: Kalender-Icon wenn target_url idt2 enthält (spezifische Lektion)
                            if($isSingleLesson){
                                $showCalendarIcon = true;
                                $calendarOverrideButtons = true;
                                $calendarOverrideLabel = isset($calendarOptions['calendar_button_label']) ? $calendarOptions['calendar_button_label'] : '';
                                if (trim((string)$calendarOverrideLabel) === '') { $calendarOverrideLabel = ''; }
                                $calendarOverrideUrl = $calendarOptions['target_url'];
                            }
                        }

                        return $twig->render($templateName, [
                            'current_page' => $currentpage,
                            'offset' => round((11 - count((array_values($tlektion)[0])->getPages())) / 2),
                            'training' => $training,
                            'lektion' => array_values($tlektion)[0],
                            'Lektionen_Text' => $Lektionen_Text,
                            'showPagination' => $showPagination,
                            'showLektionenButton' => $showLektionenButton,
                            'navigationType' => $navigationType,
                            // Kalender-Overrides (optional)
                            'calendarOverrideButtons' => $calendarOverrideButtons,
                            'calendarOverrideLabel' => $calendarOverrideLabel,
                            'calendarOverrideUrl' => $calendarOverrideUrl,
                            'lektionenButtonLabel' => $lektionenButtonLabel,
                            'lektionenButtonUrl' => $lektionenButtonUrl,
                            'abschliessenButtonLabel' => $abschliessenButtonLabel,
                            'abschliessenButtonUrl' => $abschliessenButtonUrl,
                            'showCalendarIcon' => $showCalendarIcon,
                            'isSingleLesson' => $isSingleLesson,
                            'calendarOptions' => $calendarOptions,
                        ]);
                    } else {
                        return "";
                    }
                }
            }
        }
        return "";
    }

    /**
     * Prüft, ob das Training als Kalender-Training markiert ist (postmeta 'calendarTraining' == "1").
     */
    private function isCalendarTrainingEnabled($trainingId)
    {
        if(empty($trainingId)) { return false; }
        $calendarTraining = get_post_meta($trainingId, 'calendarTraining', true);
        return (string)$calendarTraining === "1";
    }

    /**
     * Prüft anhand von postmeta 'calendar_options'.target_url, ob die aktuellen URL-Parameter (idt1/idt2)
     * mit dem dort hinterlegten Ziel übereinstimmen.
     *
     * Bedingungen:
     * - target_url muss idt1 enthalten und mit aktuellem idt1 übereinstimmen
     * - wenn target_url idt2 enthält, muss es ebenfalls mit aktuellem idt2 übereinstimmen
     */
    private function isCalendarAccessValid($trainingId)
    {
        if(empty($trainingId)) { return false; }

        $currentIdt1 = htmlspecialchars(preg_replace('/[^0-9]/', '', get_query_var('idt1') . ''));
        $currentIdt2 = htmlspecialchars(preg_replace('/[^0-9]/', '', get_query_var('idt2') . ''));

        // calendar_options vorzugsweise vom Kalender-Post (calendar_id), sonst Fallback: Training
        $calendarId = isset($_GET['calendar_id']) ? intval($_GET['calendar_id']) : 0;
        // calendar_options Meta kann als Array oder String gespeichert sein
        $calendarOptionsRaw = null;
        if($calendarId > 0 && get_post_type($calendarId) === 'kalender') {
            $calendarOptionsRaw = get_post_meta($calendarId, 'calendar_options', true);
        }
        if(empty($calendarOptionsRaw)) {
            // Fallback: Training (nur falls historisch so abgelegt)
            $calendarOptionsRaw = get_post_meta($trainingId, 'calendar_options', true);
        }
        if(empty($calendarOptionsRaw)) { return false; }

        if(is_string($calendarOptionsRaw)) {
            $decoded = json_decode($calendarOptionsRaw, true);
            if(json_last_error() === JSON_ERROR_NONE) {
                $calendarOptions = $decoded;
            } else {
                // Falls bereits als String ohne JSON vorliegt
                $calendarOptions = [];
            }
        } else if(is_array($calendarOptionsRaw)) {
            $calendarOptions = $calendarOptionsRaw;
        } else {
            $calendarOptions = [];
        }

        if(!isset($calendarOptions['target_url']) || trim($calendarOptions['target_url']) === '') {
            return false;
        }

        $targetUrl = $calendarOptions['target_url'];
        $parts = wp_parse_url($targetUrl);
        if($parts === false || !isset($parts['query'])) { return false; }

        $targetParams = [];
        parse_str($parts['query'], $targetParams);

        $targetIdt1 = isset($targetParams['idt1']) ? htmlspecialchars(preg_replace('/[^0-9]/', '', $targetParams['idt1'] . '')) : '';
        $targetIdt2 = isset($targetParams['idt2']) ? htmlspecialchars(preg_replace('/[^0-9]/', '', $targetParams['idt2'] . '')) : '';

        // idt1 muss vorhanden sein und matchen
        if($targetIdt1 === '' || $currentIdt1 === '' || $targetIdt1 !== $currentIdt1) {
            return false;
        }

        // idt2 nur prüfen, wenn in target_url vorhanden
        if($targetIdt2 !== '') {
            if($currentIdt2 === '' || $targetIdt2 !== $currentIdt2) {
                return false;
            }
        }

        return true;
    }

    public static function isUserModusRequest() {
        $current_user = wp_get_current_user();

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

    public static 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;
    }
}
