<?php

/**
 * Coachingmode form: Adds a form that allows users to select the form of coaching for the specified training
 * 
 * @author     Tim Mallwitz <tim.mallwitz@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Coachingmode_Form{

    public function __construct() {

    }
    
    // Show coachingmode form
    public function showCoachingmodeForm($atts, $content=null){
        
        if(0 !== get_current_user_id()) {

            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
            // Check whether the title should be displayed in the coaching mode form
            $showTitle = false;
            if(isset($atts['title'])){
                if(trim($atts['title']) == "1"){
                    $showTitle = true;
                }
            }

            // Check which coaching modes should be available for selection
            $showOpt0 = false;
            $showOpt1 = false;
            $showOpt2 = false;

            if(isset($atts['modi'])){
                if(trim($atts['modi']) != ""){
                    $coachingModi = explode(",", $atts['modi']);
                    foreach($coachingModi as $coachingModus){

                        if(strtolower(trim($coachingModus)) === "ohne"){
                            $showOpt0 = true;
                        }
                        else if(strtolower(trim($coachingModus)) === "bedarf"){
                            $showOpt1 = true;
                        }
                        else if(strtolower(trim($coachingModus)) === "umfassend"){
                            $showOpt2 = true;
                        }
                    }
                }

                if(!$showOpt0 && !$showOpt1 && !$showOpt2){
                    return $twig->render('coachingmode-form/coachingmode-form-error.html');
                }
        
            }
            else{
                $showOpt0 = true;
                $showOpt1 = true;
                $showOpt2 = true;
            }
            
            // Check whether multiple selections should be allowed in the coaching mode form
            $multiChoice = false;
            if(isset($atts['multichoice'])){
                if(trim($atts['multichoice']) == "1"){
                    $multiChoice = true;
                }
            }

            if(isset($atts['training'])){
                if(trim($atts['training']) == ""){
                    return $twig->render('coachingmode-form/coachingmode-form-error.html');
                }
                else{
                    $userID = Trainingssystem_Plugin_Public::getTrainingUser();
                    // Check whether usermode is active: The coachingmode form is disabled in usermode
                    $usermodus = Trainingssystem_Plugin_Public::isUserModusRequest();
                    $training = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getTrainingById(trim($atts['training']));
                    $trainingTitle = "";
                    if(empty($training)){
                        return $twig->render('coachingmode-form/coachingmode-form-error.html');
                    }
                    else{
                        $trainingTitle = $training->getTitle();
                    }
                    $trainingsUser = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userID);
                    $trainingsUserIds = array();
                    
                    // Get IDs of all trainings of the current user
                    foreach($trainingsUser as $uTraining){
                        $trainingsUserIds[] = $uTraining->getID();
                    }

                    // Select a preselected radio button for the coachingmode form
                    $preselectedCoaching = 0; // Coaching mode "no coaching"
                    $coachingNeededEntry = get_user_meta($userID, 'coaching_needed', true);
                    $coachingNeededEntryDecoded = json_decode($coachingNeededEntry);
                    $coachingNeededEntryDecoded = (array)$coachingNeededEntryDecoded;
                    if(array_key_exists(trim($atts['training']), $coachingNeededEntryDecoded)){
                        $preselectedCoaching = $coachingNeededEntryDecoded[trim($atts['training'])];
                    }
                    
                    // The current user doesn't have the selected training
                    if(!in_array(trim($atts['training']), $trainingsUserIds)){
                        return "";
                    }
                    // The current user has the selected training
                    else{
                        // Check whether the current user has already selected a coaching mode for the selected training
                        $coachingModeEntry = get_user_meta($userID, 'coaching_mode', true);
                        $coachingModeEntryArray = explode(",", $coachingModeEntry);
                        if(in_array(trim($atts['training']), $coachingModeEntryArray)){
                            return "";
                        }

                        return $twig->render('coachingmode-form/coachingmode-form-coachingmode-selection.html', [
                            'trainingtitle' => $trainingTitle,
                            'trainingID' => trim($atts['training']),
                            'userID' => $userID,
                            'preselectedCoaching' => $preselectedCoaching,
                            'title' => $showTitle,
                            'showOpt0' => $showOpt0,
                            'showOpt1' => $showOpt1,
                            'showOpt2' => $showOpt2,
                            'multiChoice' => $multiChoice,
                            'usermodus' => $usermodus,
                        ]);
                    }
                }
            }
            else{
                return $twig->render('coachingmode-form/coachingmode-form-error.html');
            }
        } else {
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }

    }
    public function saveCoachingMode(){

        $userID = get_current_user_id();
        $newTrainingID = $_POST['trainingsID'];
        $newCoachingMode = $_POST['coachingMode'];
        $coachingModeFormMulti = $_POST['coachingModeFormMulti'];

        // Get old coaching mode of the current user
        $oldCoachingMode = 0; // set coaching mode to "no coaching", if no coaching mode has previously been selected for the training 
        $coachingNeededEntry = get_user_meta($userID, 'coaching_needed', true);
        $coachingNeededEntryDecoded = json_decode($coachingNeededEntry);
        $coachingNeededEntryDecoded = (array)$coachingNeededEntryDecoded;
        if(array_key_exists($newTrainingID, $coachingNeededEntryDecoded)){
            $oldCoachingMode = $coachingNeededEntryDecoded[$newTrainingID];
        }

        // Check whether the training mode of the training needs to be changed
        if(($oldCoachingMode == "2" && $newCoachingMode != "2")||($oldCoachingMode != "2" && $newCoachingMode == "2")){
            $userTrainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($userID);
            $userTrainingsNew = array();
            foreach($userTrainings as $training){
                $trainingNew = array();
                $lektionsliste = $training->getLektionsliste();

                $trainingNew["id"] = $training->getId();
                $trainingNew["lektionen"] = array();
                $trainingNew["enable"] = $training->trainingEnabled();
                
                $lekid = 0;
		        foreach ($lektionsliste as $lektion) {
			        $trainingNew["lektionen"][$lekid]["id"] = $lektion->getId();
                    $trainingNew["lektionen"][$lekid]["lektionAuto"] = $lektion->getTrainingAuto();

                    if($training->getId() == $newTrainingID){
                        if($oldCoachingMode == "2" && $newCoachingMode != "2"){
                            $trainingNew["lektionen"][$lekid]["lektionAuto"] = 1;
                        }
                        else if($oldCoachingMode != "2" && $newCoachingMode == "2"){
                            $trainingNew["lektionen"][$lekid]["lektionAuto"] = 2;
                        }
                    }

			        $trainingNew["lektionen"][$lekid]["lektionEnable"] = $lektion->getEnable();
			        $lekid++;
		        }
                $trainingNew["auto"] = $trainingNew["lektionen"][0]["lektionAuto"];
                $userTrainingsNew[$training->getId()] = $trainingNew;
            }

            Trainingssystem_Plugin_Database::getInstance()->NutzerDao->updateTrainingByUserId($userID,$userTrainingsNew);
        }
        
        // Check whether multiple selections are allowed in the coaching mode form, if not: "lock" the training
        if($coachingModeFormMulti == 0){
            // Check whether an entry for the meta key "coaching_mode" exists
            $usermetaEntry = get_user_meta($userID,'coaching_mode',false);
            // Entry exists
            if(!empty($usermetaEntry)){
                $trainingIds = $usermetaEntry[0];
                $allTrainingsIds = "";
                if($trainingIds == ""){
                    $allTrainingsIds = $newTrainingID;
                }
                else{
                    $allTrainingsIds = $trainingIds.','.$newTrainingID;
                }
    
                update_user_meta($userID, 'coaching_mode', $allTrainingsIds);
            }
            else{
                add_user_meta($userID, 'coaching_mode', $newTrainingID);
            }
        }

        // Set coaching mode
        $usermetaEntryMode = get_user_meta($userID,'coaching_needed',false);
        // Entry exists
        if(!empty($usermetaEntryMode)){
            $selectedCoachingModes = json_decode($usermetaEntryMode[0]); 
            $selectedCoachingModes = (array)$selectedCoachingModes;
            $selectedCoachingModes[$newTrainingID] = $newCoachingMode;
            $selectedCoachingModesEncoded = json_encode($selectedCoachingModes);
            update_user_meta($userID, 'coaching_needed', $selectedCoachingModesEncoded);
        }
        else{
            $newUsermetaEntryMode = array();
            $newUsermetaEntryMode[$newTrainingID] = $newCoachingMode;
            $newUsermetaEntryModeEncoded = json_encode($newUsermetaEntryMode);
            add_user_meta($userID, 'coaching_needed', $newUsermetaEntryModeEncoded);
        }
        
        
        echo "1";
        wp_die();

    }

    // Reset the entry for the meta key "coaching_mode" for the selected training
    public function resetCoachingModeFormMeta(){
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr")){
            if(isset($_POST['users'])&&isset($_POST['training'])){
                $users = json_decode(stripslashes(sanitize_text_field($_POST['users'])),true);
                $training = $_POST['training'];
                foreach($users as $user){
                    $usermetaEntry = get_user_meta($user,'coaching_mode',false);
                    if(!empty($usermetaEntry)){
                        $trainingIdsArray = explode(",", $usermetaEntry[0]);
                        if(in_array($training, $trainingIdsArray)){
                            $trainingIdsArray2 = array();
                            foreach($trainingIdsArray as $thisTraining){
                                if($thisTraining != $training){
                                    $trainingIdsArray2[] = $thisTraining;
                                }
                            }
                            $newUserMetaEntry = "";
                            for($trainID = 0; $trainID < count($trainingIdsArray2); $trainID++){
                                if($trainID != 0){
                                    $newUserMetaEntry = ",".$newUserMetaEntry;
                                }
                                $newUserMetaEntry = $newUserMetaEntry.$trainingIdsArray2[$trainID];
                            }
                            update_user_meta($user, 'coaching_mode', $newUserMetaEntry);
                        }
                    }
                }
            }
        }
        echo "1";
        wp_die();
    }

}