<?php

/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Coach_User_Remover
 * @subpackage Coach_User_Remover/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    Coach_User_Remover
 * @subpackage Coach_User_Remover/public
 * @author     Markus Domin, Helge Nissen <markus.domin@fh-luebeck.de>
 */
class Trainingssystem_Plugin_Module_User_Create
{

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

    }

    /**
     * Display the HTML form to create a user manually
     * 
     * @return HTML Code
     */
    public function showCreateUserForm($atts) {
       
        $heading = isset($atts['titel']) ? $atts['titel'] : 'Teilnehmende manuell hinzufügen'; 

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

        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzernew")) {

            $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG . 'submit';
            $noncefield = 'user-manual-create';
            ob_start();

            $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 {

                //volagen nutzer holen
                $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();
                }
                // var_dump($vorlagen);

                $trainer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainer();
                
                echo $twig->render('user-create/create-user-manually.html', [
                    "vorlagen" => $vorlagen,
                    "trainers" => $trainer,
                    'userCanGivePermissions' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissions"),
                    'userCanGivePermissionsAll' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsall"),
                    'userCanGivePermissionsBoss' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsboss"),
                    'userCanGivePermissionsTeamleader' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsteamleader"),
                    'userCanGivePermissionskAdmin' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionskAdmin"),
                    'submitnonce' => wp_nonce_field($nonceaction, $noncefield, true, false),
                    'heading' => $heading,
                    'roles' => Trainingssystem_Plugin_Database::getInstance()->PermissionRole->getAllRoles(),
                ]);

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

    /**
     * Ajax Request Function to add user manually
     * 
     * @return 1 on success; 0 on failure
     */
    public function create_user_manually()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzernew")) {

            $nonceaction = TRAININGSSYSTEM_PLUGIN_SLUG . 'submit';
            $noncefield = 'user-manual-create';
        
            if (isset($_POST[$noncefield]) &&
                wp_verify_nonce($_POST[$noncefield], $nonceaction) &&
                trim($_POST['username']) != '' && trim($_POST['email']) != '' && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {

                $user_name = isset($_POST['username']) ? sanitize_text_field($_POST['username']) : ""; //$_POST['username'];
                $email = isset($_POST['email']) ? strtolower(sanitize_text_field($_POST['email'])) : ""; //$_POST['email'];
                $check_mail = isset($_POST['check-mail']) ? sanitize_text_field($_POST['check-mail']) : "";

                $password = wp_generate_password(10, true, true);
                $creation = wp_create_user(sanitize_text_field($user_name), $password, sanitize_email($email));
                if (is_wp_error($creation)) {
                    echo $creation->get_error_message();
                } else {
                    if ($check_mail == 'true') {
                        //send mail!
                        wp_new_user_notification($creation, null, 'both');
                    }
                    $useridtmp = $creation;
                    if (isset($_POST['selectbox-trainer']) && $_POST['selectbox-trainer'] != "") {
                        $trainerid = intval(sanitize_text_field($_POST['selectbox-trainer']));
                        update_user_meta($useridtmp, 'coachid', $trainerid);
                    }

                    if (isset($_POST['studienid']) && trim($_POST['studienid']) != "") {
                        $studienId = sanitize_text_field($_POST['studienid']);
                        update_user_meta($useridtmp, 'studienid', $studienId);
                    }

                    if (isset($_POST['studiengruppenid']) && trim($_POST['studiengruppenid']) != "") {
                        $studiengruppenid = sanitize_text_field($_POST['studiengruppenid']);
                        update_user_meta($useridtmp, 'studiengruppenid', $studiengruppenid);
                    }

                    if(isset($_POST['permissions']) && is_array($_POST['permissions']) && sizeof($_POST['permissions']) > 0) {
                        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissions")) 
                        {
                            $permissions_un = $_POST['permissions'];
                            $permissions = array();
                            foreach($permissions_un as $p_u) {
                                $permissions[] = sanitize_text_field($p_u);
                            }
                            $allroles = Trainingssystem_Plugin_Database::getInstance()->PermissionRole->getAllRoles();

                            $allrolesvalid = true;
                            foreach($permissions as $p) {
                                $found = false;
                                foreach($allroles as $role) {
                                    if($role->getId() == $p) {
                                        $found = true;
                                    }
                                }
                                if(!$found) {
                                    $allrolesvalid = false;
                                    break;
                                }
                            }

                            if($allrolesvalid) {
                                $userCanGivePermissionsAll = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsall");
                                $userCanGivePermissionsBoss = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsboss");
                                $userCanGivePermissionsTeamleader = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionsteamleader");
                                $userCanGivePermissionskAdmin = Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissionskAdmin");

                                $allowedToGiveRoles = true;

                                foreach($permissions as $p) {
                                    if($userCanGivePermissionsAll || ($userCanGivePermissionsBoss && $p == "boss") || ($userCanGivePermissionsTeamleader && $p == "teamLeader") || ($userCanGivePermissionskAdmin && $p == "kAdmin")) {
                                        continue;
                                    } else {
                                        $allowedToGiveRoles = false;
                                        break;
                                    }
                                }

                                if($allowedToGiveRoles) {
                                    if(!update_user_meta($useridtmp, TRAININGSSYSTEM_PLUGIN_USER_HAS_ROLES, $permissions)) {
                                        echo "Fehler beim Anlegen der Berechtigungen!";
                                    }
                                } else {
                                    echo "access denied for roles";
                                }
                            }
                        }
                    }

                    if (isset($_POST['selectbox-profil']) && $_POST['selectbox-profil'] != "") {
                        $vorlagennutzer = [];
                        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
                        {
                            $vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUserRaw();
                        }
                        elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
                        {
                            $vorlagennutzer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUserRaw();
                        }
                        $vorlagennutzerids = count($vorlagennutzer) > 0 ? array_column($vorlagennutzer, 'ID') : [];
                        
                        $vorlagenid = intval(sanitize_text_field($_POST['selectbox-profil']));

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

                        if(in_array($vorlagenid, $vorlagennutzerids)) {

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

                            $getvorlageUserTraining = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($vorlagenid);
                            foreach ($getvorlageUserTraining as $training) {
                                $copytraining = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainingCopy($training);
                                
                                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;
                                    }
                                }

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

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

                            $trainingDepVorlage = Trainingssystem_Plugin_Database::getInstance()->TrainingDep->getTrainingDepByUser($vorlagenid);
                            if(count($trainingDepVorlage) > 0) {
                                foreach($trainingDepVorlage as $trainingDep) {
                                    Trainingssystem_Plugin_Database::getInstance()->TrainingDep->insertTrainingDep($trainingDep->getTrainingId(), $trainingDep->getTrainingMode(), $trainingDep->getEcoachingEnable(), $trainingDep->getLektionSettings(), $useridtmp, $trainingDep->getTimeAdd(), $trainingDep->getTimeMultiplier(), $trainingDep->getDependentTrainings(), $trainingDep->getDependentCondition(), $trainingDep->getRedirect(), $vorlagenid);
                                }
                                $trMgr = new Trainingssystem_Plugin_Module_Coach_User_Training_Mgr_Public();
                                $trMgr->check_for_dependent_trainings(null, null, $useridtmp);
                            }
                        } else {
                            echo "Sie haben keine Berechtigung diese Vorlage zu verwenden. Der/Die Teilnehmende wurde ohne Vorlage angelegt.";
                            wp_die();
                        }
                    }

                    echo "1";
                }
            }
        }
        wp_die();
    }

    public function saveUserMetaCreatedBy($user_id){
        $current_user = wp_get_current_user();
        return update_user_meta($user_id, 'created_by', $current_user->ID);
    }

}
