<?php
class Trainingssystem_Plugin_Module_Register_Key {

    public function __construct()
    {

    }

    /**
     * Function to add the registercode field to the WP Registration form
     *
     * @return HTML Code
     */
    function crf_registration_form() {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        $code = '';
        if(isset($_GET['code']) && is_numeric($_GET['code'])) {
            $code = intval($_GET['code']);
            setcookie('register_code', $code);
        } else if(isset($_COOKIE['register_code']) && is_numeric($_COOKIE['register_code'])) {
            $code = intval($_COOKIE['register_code']);
        }
        $label = esc_html__( 'Zugangscode', 'crf' );

        $codeDetail = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);

        if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'])){
            $privacy_terms_URL = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'];
        }
        else{
            $privacy_terms_URL = "";
        }
        if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['register_problem'])){
            $register_problem = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['register_problem'];
        }
        else{
            $register_problem = "";
        }
        if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['register_solution'])){
            $register_solution = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['register_solution'];
        }
        else{
            $register_solution = "";
        }
        if(!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['register_redeem_code_manually'])){
            $redeemCodeManually = true;
        }
        else{
            $redeemCodeManually = false;
        }

        $company = null;
        $companygroup = null;
        $groups = array();
        if($codeDetail != null){
            $company = $codeDetail->getCompany();
            $companygroup = $codeDetail->getCompanygroup();

            if(isset($company)) {
                $groups = Trainingssystem_Plugin_Database::getInstance()->CompanygroupDao->getAllGroupsByCompanyId($company->getId());
            }
        }

        echo $twig->render("user-register-key/register-key-registration-field.html", [
            'code'  => $code,
            'label' => $label,
            'groups' => $groups,
            'company' => $company,
            'companygroup' => $companygroup,
            'admin_mail' => get_option('admin_email'),
            'privacy_terms_URL' => $privacy_terms_URL,
            'register_problem' => $register_problem,
            'register_solution' => $register_solution,
            'redeemCodeManually' => $redeemCodeManually,
            'website_name' => get_bloginfo()

        ]);
        
    }

    /**
     * Function to Check the registerkey for errors
     */
    function crf_registration_errors( $errors, $sanitized_user_login, $user_email ) {
        if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'])){
            if ( empty( $_POST['privacy_terms_checkbox'] ) ) {
                $errors->add( 'privacy_terms_error', __( '<strong>Fehler</strong>: Stimmen Sie den Teilnahmebedingungen zu, um fortzufahren.', 'crf' ) );
            }
        }
        if ( empty( $_POST['code'] ) ) {
            $errors->add( 'code_error', __( '<strong>Fehler</strong>: Bitte geben Sie einen Freischaltcode ein.', 'crf' ) );
        }
        else{
            $code = sanitize_text_field($_POST['code']);
            if(!Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeExists($code)){
                $errors->add( 'code_error', __( '<strong>Fehler</strong>: Bitte geben Sie einen gültigen Freischaltcode ein', 'crf' ) );
            } else {
                // Check the group is in company!
                $codeDetail = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);
                $company = $codeDetail->getCompany();
                $companygroup = $codeDetail->getCompanygroup();
                if(isset($company) && !isset($companygroup) && (empty($_POST['group_id']) || $_POST['group_id'] === 0)) {
                    $errors->add( 'code_error', __( '<strong>Fehler</strong>: Bitte ein gültiges Team auswählen.', 'crf' ) );
                } else if(isset($company) && isset($companygroup) && $_POST['group_id'] != $companygroup->getId()) {
                    $errors->add( 'code_error', __( '<strong>Fehler</strong>: Bitte das vorgegebene Team auswählen.', 'crf' ) );
                }
            }
        }

        return $errors;
    }

    function adjustRegisterUrl($url) {
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
        
        if(isset($settings["open_register_code"]) && trim($settings['open_register_code']) != "") { 
            $code = $settings["open_register_code"];
            $registerCode = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code, false); // MUST use false as 2nd param, else deadlock!
            if($registerCode->getCountCode() < $registerCode->getMaxCount()){
                return add_query_arg("code", $settings["open_register_code"], $url);
            }
        }
        return $url;
    }

    /**
     * Function to redeem the Registercode to the user
     */
    function crf_user_register( $user_id ) {
        if (!empty( $_POST['code'])) {
            if(isset($_COOKIE['register_code'])) {
                setcookie('register_code', '', time() - 3600);
            }
            $code = sanitize_text_field($_POST['code']);

            //if group is given, add user to group
            $group_id = sanitize_text_field($_POST['group_id']);
            if($group_id !== 0){
                Trainingssystem_Plugin_Database::getInstance()->CompanygroupUserDao->addUserToGroup($user_id, $group_id);
            }

            $this->redeemRegisterkey($user_id, $code, true);
            if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['privacy_terms_URL'])){
                update_user_meta($user_id, 'privacy_terms_confirmed', date("d.m.Y"));
            }
            $codeDetail = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);
            if(!is_null($codeDetail->getCreatorUserId())){
                update_user_meta($user_id, 'created_by', $codeDetail->getCreatorUserId());
            }
        }
    }

    /**
     * Display the Table with Registerkeys
     *
     * @return HTML Code of Registerkey Table
     */
    public function showRegisterkeyList(){
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{
            $vorlagen = [];
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
            {
                $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
            }
            elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
            {
                $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
            }
            
            $registerKeys = [];
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyall")) 
            {
                $registerKeys = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getAll();
            } 
            elseif(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyown")) 
            {
                $registerKeys = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getMy();
            }

            return $twig->render('user-register-key/register-key-table.html', [
                'data' =>  $registerKeys,
                'vorlagen' => $vorlagen,
                'settings' => $settings,
            ]);
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    /**
     * Display a form to add a new Registerkey to the Database
     *
     * @return HTML code
     */
    public function showNewRegisterKeyForm($atts){

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

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

        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{
            ob_start();

            $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG.'submitregkey';
            $noncefield = 'regkey';

            $vorlagen = [];
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
            {
                $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
            }
            elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
            {
                $vorlagen = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
            }

            $companies = [];
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall")) 
            {
                $companies =Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(false, false, false);
            }
            elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")) 
            {
                $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanies(get_current_user_id());
            }

            echo $twig->render('user-register-key/register-key-new.html', [
                'submitnonce'   =>  wp_nonce_field($nonceaction,$noncefield,true,false),
                'vorlagen'      =>  $vorlagen,
                'companies'     =>  $companies,
                'heading'       =>  $heading,
            ] );

            return ob_get_clean();
        }
        return "";
    }


    /**
     * V2: Optimierte Ajax function to add a new registerkey
     * Verwendet codeExists() statt getAll() für bessere Performance
     * 
     * @return 0 on error, 1 on success, "duplicate" if code already exists
     */
    function addRegisterkeyV2() {
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{
            $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG.'submitregkey';
            $noncefield = 'regkey';

            $vorlagenids = [];
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
            {
                $vorlagenids = array_column(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw(), 'ID');
            }
            elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
            {
                $vorlagenids = array_column(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUserRaw(), 'ID');
            }

            if (isset( $_POST[$noncefield] ) &&
                isset($_POST['code']) && is_numeric($_POST['code']) && $_POST['code'] >= 0 &&
                isset($_POST['max_count']) && ($_POST['max_count'] == "" || is_numeric($_POST['max_count']) && $_POST['max_count'] > 0) &&
                wp_verify_nonce($_POST[$noncefield], $nonceaction))
                {
                    $code = sanitize_text_field($_POST['code']);
                    $vorlage_id = 0;
                    if (isset($_POST['vorlage_id']) && is_numeric($_POST['vorlage_id']) && ($_POST['vorlage_id'] == 0 || in_array($_POST['vorlage_id'], $vorlagenids))) {
                        $vorlage_id = sanitize_text_field($_POST['vorlage_id']);
                    }

                    $vorlage_id_optional = 0;
                    if (isset($_POST['vorlage_id_optional']) && is_numeric($_POST['vorlage_id_optional']) && ($_POST['vorlage_id_optional'] == 0 || in_array($_POST['vorlage_id_optional'], $vorlagenids))) {
                        $vorlage_id_optional = sanitize_text_field($_POST['vorlage_id_optional']);
                    }

                    $creator_user_id = get_current_user_id();
                    $count_code = 0;
                    $max_count = sanitize_text_field($_POST['max_count']);
                    if($max_count == "") {
                        $max_count = PHP_INT_MAX;
                    }
                    $display_name = wp_get_current_user()->display_name;

                    $companies = [];
                    if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall")) 
                    {
                        $companies =Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllCompanies(false, false, false);
                    }
                    elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")) 
                    {
                        $companies = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getMyCompanies(get_current_user_id());
                    }

                    $company_id = 0;
                    $selected_company = null;
                    if(isset($_POST['company_id']) && $_POST['company_id'] != 0) {
                        $company_id = sanitize_text_field($_POST['company_id']);

                        foreach($companies as $c) {
                            if($c->getId() == $company_id) {
                                $selected_company = $c;
                                break;
                            }
                        }

                        if(is_null($selected_company)) {
                            echo "access company denied";
                            wp_die();
                        }
                    }

                    $companygroup_id = 0;
                    $selected_companygroup = null;
                    if(isset($_POST['companygroup_id']) && $_POST['companygroup_id'] != 0) {
                        $companygroup_id = sanitize_text_field($_POST['companygroup_id']);

                        foreach($selected_company->getGroups() as $g) {
                            if($g->getId() == $companygroup_id) {
                                $selected_companygroup = $g;
                                break;
                            }
                        }

                        if(is_null($selected_companygroup)) {
                            echo "access group denied";
                            wp_die();
                        }
                    }

                    $studygroupid = isset($_POST['studiengruppenid']) ? sanitize_text_field($_POST['studiengruppenid']) : null;
                    if(strlen($studygroupid) == 0) {
                        $studygroupid = null;
                    }

                    // Effiziente Duplikat-Prüfung mit codeExists() statt getAll()
                    if(!Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeExists($code)) {
                        if(Trainingssystem_Plugin_Database::getInstance()->RegisterKey->addCode($code, $vorlage_id, $vorlage_id_optional, $creator_user_id, $count_code, $max_count, $company_id, $companygroup_id, $studygroupid)) {
                            echo "1";
                        } else {
                            echo "0";
                        }
                    } else {
                        echo "duplicate";
                    }

            } else {
                if(isset($_POST[$noncefield])) {
                    echo "0";
                }
            }
        }
        wp_die();
    }

    /** 
     * Ajax function to delete a registerkey
     * 
     * @return 0 on error, 1 on success
     */
    function deleteRegisterkey() {
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{
            if(isset($_POST['registerkey']) && trim($_POST['registerkey']) != "" && is_numeric($_POST['registerkey'])) {
                $code = sanitize_text_field($_POST['registerkey']);

                $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
                if(isset($settings['demologin_registerkey']) && $settings['demologin_registerkey'] == $code) {
                    echo "registerkey-demologin";
                } else {

                    $registerKey = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);

                    if(!is_null($registerKey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyall") || 
                        !is_null($registerKey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyown") && get_current_user_id() == $registerKey->getCreatorUserId()) 
                    {
                        if(Trainingssystem_Plugin_Database::getInstance()->RegisterKey->deleteCode($code)) {
                            echo "1";
                        } else {
                            echo "0";
                        }
                    } else {
                        echo "access denied";
                    }
                }
            } else {
                echo "0";
            }
        }
        wp_die();
    }

    /**
     * Ajax function to update a registerkey
     * atm only maxCoutn value
     * 
     * @return 0 on error, 1 on success
     */
    function updateRegisterkey() {
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{
            if(isset($_POST['registerkey']) && trim($_POST['registerkey']) != "" && is_numeric($_POST['registerkey']) &&
                isset($_POST['maxcount']) && (trim($_POST['maxcount']) == "" || trim($_POST['maxcount']) != "" && is_numeric($_POST['maxcount']))) {

                $code = sanitize_text_field($_POST['registerkey']);
                $maxCount = sanitize_text_field($_POST['maxcount']);
                if($maxCount == "") {
                    $maxCount = PHP_INT_MAX;
                }

                $registerkey = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);

                if(!is_null($registerkey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyall") || 
                    !is_null($registerkey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyown") && get_current_user_id() == $registerkey->getCreatorUserId()) 
                {
                    if($registerkey->getCountCode() <= $maxCount) {
                        if(Trainingssystem_Plugin_Database::getInstance()->RegisterKey->updateCode($code, $maxCount)) {
                            echo "1";
                        } else {
                            echo "0";
                        }
                    } else {
                        echo "toolow";
                    }
                } else {
                    echo "access denied";
                }
            } else {
                echo "0";
            }
        }
        wp_die();
    }

    /**
     * Ajax function to update a registerkey's vorlage
     * 
     * @return 0 on error, 1 on success     
     */
    function updateVorlage() {
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkey"))
		{

            if(isset($_POST['registerkey']) && trim($_POST['registerkey']) != "" && is_numeric($_POST['registerkey']) &&
                isset($_POST['vorlage']) && trim($_POST['vorlage']) != "" && is_numeric($_POST['vorlage'])) {

                $code = sanitize_text_field($_POST['registerkey']);
                $vorlage = sanitize_text_field($_POST['vorlage']);

                $registerkey = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);
                
                $vorlagenids = [];
                if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
                {
                    $vorlagenids = array_column(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw(), 'ID');
                }
                elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
                {
                    $vorlagenids = array_column(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUserRaw(), 'ID');
                }

                if((
                    !is_null($registerkey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyall") || 
                    !is_null($registerkey) && Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("registerkeyown") && get_current_user_id() == $registerkey->getCreatorUserId()
                    ) 
                    && (in_array($vorlage, $vorlagenids) || $vorlage == "0")) 
                {
                    if(Trainingssystem_Plugin_Database::getInstance()->RegisterKey->updateCodeVorlage($code, $vorlage)) {
                        echo "1";
                    } else {
                        echo "0";
                    }

                } else {
                    echo "0";
                }

            } else {
                echo "0";
            }
        }
        wp_die();
    }

    /**
     * Ajax function to redeem a registerkey
     *
     * @return 0 on error, 1 on success
     */
    public function userRedeemRegisterkey(){
        
        $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG.'submitregkey';
        $noncefield = 'regkey';


        if (isset($_POST[$noncefield]) &&
            isset($_POST['code']) && is_numeric($_POST['code']) && $_POST['code'] >= 0 &&
            wp_verify_nonce($_POST[$noncefield], $nonceaction))
        {
            $user_id = get_current_user_id();
            $code = sanitize_text_field($_POST['code']);

            if(!Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeExists($code)) {
                echo "invalid";
            } else {
                if($this->redeemRegisterkey($user_id, $code)) {
                    echo "1";
                } else {
                    echo "0";
                }
            }
        } else {
            echo "invalid";
        }
        wp_die();
    }

    /**
     * Redeem a Registerkey to a user, copy the registerkey's trainings to the user
     *
     * @param user_id The ID of the user that will get the trainings
     * @param code The Code which shall be redeemed
     *
     * @return true/false succeeded or not
     */
    public function redeemRegisterkey($user_id, $code, $addTrainer = false){
        $codeDetail = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getCodeDetails($code);
        if($codeDetail != null) {
            $company = $codeDetail->getCompany();

            if(isset($company)) {
                add_user_meta($user_id, "company_id", $company->getId());
            }

            $vorlageId = $codeDetail->getVorlageid();
            if ($codeDetail->getVorlageidOptional() > 0) {
                if (random_int(0, 1) > 0) {
                    $vorlageId = $codeDetail->getVorlageidOptional();
                }
            }

            $coaching_needed = get_user_meta($user_id,'coaching_needed',false);
            $newCoachingVals = [];
            if(!empty($coaching_needed) && isset($coaching_needed[0])) {
                $newCoachingVals = json_decode($coaching_needed[0], true);
            }

            $vorlagenUserCoachingNeeded = get_user_meta($vorlageId,'coaching_needed',false);
            $vorlagenUserCoachingValues = [];
            if(!empty($vorlagenUserCoachingNeeded) && isset($vorlagenUserCoachingNeeded[0])) {
                $vorlagenUserCoachingValues = json_decode($vorlagenUserCoachingNeeded[0], true);
            }
            
            $trainingNames = "";
            $vorlageTrainings = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($vorlageId);
            foreach ($vorlageTrainings as $training ){
                $copytraining = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingCopy($training);

                $trainingNames .= $training->getTitle() . "“, „";

                if(isset($copytraining["lektionen"][0]["auto"])) {
                    if(($copytraining["lektionen"][0]["auto"] == "0" || $copytraining["lektionen"][0]["auto"] == "1") && 
                        (isset($vorlagenUserCoachingValues[$copytraining["id"]]) && $vorlagenUserCoachingValues[$copytraining["id"]] == "1")) {
                        $newCoachingVals[$copytraining["id"]] = 1;
                    } elseif(isset($vorlagenUserCoachingValues[$copytraining["id"]]) && $vorlagenUserCoachingValues[$copytraining["id"]] == "2") {
                        $newCoachingVals[$copytraining["id"]] = 2;
                    } else {
                        $newCoachingVals[$copytraining["id"]] = 0;
                    }
                }

                Trainingssystem_Plugin_Database::getInstance()->NutzerDao->setTrainingByUserId($user_id, $copytraining);
            }
            update_user_meta($user_id,'coaching_needed', json_encode($newCoachingVals));

            $trainingsDateVorlage = Trainingssystem_Plugin_Database::getInstance()->TrainingDate->getTrainingDateByUser($vorlageId);
            if(count($trainingsDateVorlage) > 0) {
                foreach($trainingsDateVorlage as $trainingDate) {
                    Trainingssystem_Plugin_Database::getInstance()->TrainingDate->insertTrainingDate($trainingDate->getTrainingId(), $trainingDate->getTrainingMode(), $trainingDate->getEcoachingEnable(), $trainingDate->getLektionSettings(), $user_id, $trainingDate->getAssignDatetime(), $trainingDate->getRedirect(), $vorlageId);
                }
                $trMgr = new Trainingssystem_Plugin_Module_Coach_User_Training_Mgr_Public();
                $trMgr->assignTrainingsDate();
            }

            $trainingDepVorlage = Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getTrainingDepByUser($vorlageId);
            if(count($trainingDepVorlage) > 0) {
                foreach($trainingDepVorlage as $trainingDep) {
                    Trainingssystem_Plugin_Database::getInstance()->TrainingDep->insertTrainingDep($trainingDep->getTrainingId(), $trainingDep->getTrainingMode(), $trainingDep->getEcoachingEnable(), $trainingDep->getLektionSettings(), $user_id, $trainingDep->getTimeAdd(), $trainingDep->getTimeMultiplier(), $trainingDep->getDependentTrainings(), $trainingDep->getDependentCondition(), $trainingDep->getRedirect(), $vorlageId);
                }
                $trMgr = new Trainingssystem_Plugin_Module_Coach_User_Training_Mgr_Public();
                $trMgr->check_for_dependent_trainings(null, null, $user_id);
            }

            $trainingNames = substr($trainingNames, 0, strlen($trainingNames)-5); 
            if(sizeof($vorlageTrainings) > 1) {
                $trainingNames = $this->str_lreplace(",", " und", $trainingNames);
            }

            if($addTrainer) {
                $vorlageCoachId = get_user_meta($codeDetail->getVorlageid(), 'coachid', true);
                if($vorlageCoachId != "") {
                    update_user_meta($user_id, 'coachid', $vorlageCoachId);
                }
                else{
                    update_user_meta($user_id, 'coachid', "");
                }
            }

            if(!is_null($codeDetail->getStudygroupid())) {
                if(trim($codeDetail->getStudygroupid()) != ""){
                    update_user_meta($user_id, 'studiengruppenid', $codeDetail->getStudygroupid());
                }
                
            }

            $redirectTraining = get_user_meta($codeDetail->getVorlageid(), 'redirectTraining', true);
            if(trim($redirectTraining) != "") {
                update_user_meta($user_id, 'redirectTraining', $redirectTraining);
            }
            
            // User Event
            $title = "Freischaltcode erfolgreich eingelöst";
            $subtitle = "";
            if(count($vorlageTrainings) == 1) {
                $subtitle = "Sie haben damit das Training „" .  $trainingNames . " freigeschalten";
            } elseif(count($vorlageTrainings) > 1) {
                $subtitle = "Sie haben damit die Trainings „" .  $trainingNames . " freigeschalten";
            }
            $url = isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"]) ? get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["trainings_overview"]) : null;
            // Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
            Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, $url, "registerkey", "important");

            return Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeUsed($code);
        }
        return false;
    }

    public function maybeRemoveRegisterLink($value) {
        $script = basename(parse_url($_SERVER['SCRIPT_NAME'], PHP_URL_PATH));
        
        $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

        // Disable register when setting is set and page is login-page
        if ($script == 'wp-login.php' && isset($settings['disable_register_link']) && $settings['disable_register_link'] == "1") {
            $value = false;
             // Enable Registration when Register Form with code displayed
            if(isset($_GET['code']) && !empty($_GET['code']) && Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeExists($_GET['code'])) {
                $value = true;
            }
            // Enable Registration when Register Form ist post'ed 
            if(isset($_POST['code']) && !empty($_POST['code']) && Trainingssystem_Plugin_Database::getInstance()->RegisterKey->codeExists($_POST['code'])) {
                $value = true;
            }
        }
    
        return $value;
    }

    /**
	 * HELPER
	 * 
	 * Replace the last occurance of search with replace in subject
	 * 
	 * @source https://stackoverflow.com/questions/3835636/replace-last-occurrence-of-a-string-in-a-string
	 */
	private function str_lreplace($search, $replace, $subject) {
		$pos = strrpos($subject, $search);

		if($pos !== false)
		{
			$subject = substr_replace($subject, $replace, $pos, strlen($search));
		}

		return $subject;
	}
}