<?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_List
{

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

    public function showuser($atts)
    {
        $heading = isset($atts['titel']) ? $atts['titel'] : 'Nutzerliste'; 

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlist")) {
            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 {
                

                $settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);
                $hideMails = isset($settings['hide_mails']);
                $showCompanyInformation = false;
                if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall") || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown")){
                    $showCompanyInformation = true;
                }

                $search = isset($_GET['search']) ? $_GET['search'] : "";
                $column = isset($_GET['column']) ? $_GET['column'] : "all";
                $rows = isset($_GET['rows']) ? $_GET['rows'] : 100;
                $page = isset($_GET['page_pag']) ? $_GET['page_pag'] : "1";
                $start=  ($rows != "Alle") ? ($page-1) * $rows : 0;
                $links = [];
                $arrayAllLimits = array(100,250,500,1000,'Alle');
                $searchableColumns = [];
                $searchableColumns["all"] = "Alle Spalten";
                $searchableColumns["userid"] = "User-ID";
                $searchableColumns["studienid"] = "Studien-TN-ID";
                $searchableColumns["username"] = "User-Name";
                if($showCompanyInformation) {
                    $searchableColumns["company"] = !empty($settings["user_grouper_name"]) ? $settings["user_grouper_name"] : "Unternehmen";
                }
                if(!$hideMails) {
                    $searchableColumns["mail"] = "E-Mail-Adresse";
                }
                $searchableColumns['training'] = "Training";
                $url = get_permalink();
                $position = [];

                $userIds = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getEligibleUserIds($search, $column, $hideMails, $showCompanyInformation);
                $usersLen = sizeof($userIds);

                $totalPages = ($rows == "Alle") ? 1 : ceil($usersLen / $rows);

                if($page == 1 || $page == 2){
                    for($i = 1; $i <= $totalPages; $i++){
                        array_push($links, $i);
                        if ($i == 5){break;}
                    }
                }else if($page == $totalPages || $page == $totalPages-1){
                    for($i = $totalPages-4; $i <= $totalPages; $i++){
                        if($i>0){
                            array_push($links, $i);
                        }
                    }
                }else {
                    for($i = $page-2; $i <= $totalPages; $i++){
                        array_push($links, $i);
                        if ($i == $page + 2){break;}
                    }
                }
                $lastPagePag = $totalPages;

                $userIdsToDisplay = array();
                if($rows != "Alle") {
                    for($i = $start; $i < ($start+$rows); $i++) {
                        if(isset($userIds[$i])) {
                            $userIdsToDisplay[] = $userIds[$i];
                        }
                    }
                } else {
                    $userIdsToDisplay = $userIds;
                }
                $users = (sizeof($userIdsToDisplay) > 0) ? Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(false, $userIdsToDisplay) : array();

                $detailpageslinks = array();
                foreach($users as $user) {
                    $detailpageslinks[$user->getId()] = add_query_arg("userid", $user->getId(), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list_detail"]));
                }

                echo $twig->render('user-list/user-list.html', [
                    "lastPagePag" => $lastPagePag,
                    "usersLen" => $usersLen,
                    "rows" => $rows,
                    "searchableColumns" => $searchableColumns,
                    "search" => $search,
                    "column" => $column,
                    "url" => $url,
                    "arrayAllLimits" => $arrayAllLimits,
                    'page' => $page,
                    'links' => $links,
                    'users' => $users,
                    'urlM' => add_query_arg('action', 'userlist', get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"])),
                    'detail_page_links' => $detailpageslinks,
                    'showNutzermodus' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("usermodus"),
                    'showUserDetails' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetails"),
                    'showCompanyInformation' => $showCompanyInformation,
                    'hideMails' => $hideMails,
                    'heading' => $heading,
                    "settings" => $settings

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

    public function showUserDetail()
    {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetails")) {
            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 {
                $userid = sanitize_text_field($_GET['userid']);

                if (self::userAccessAllowed($userid)) {
                    $user = get_userdata($userid);

                    $allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(false, array($userid));
                    if($allusers[$userid]) {
                        $userChosen = $allusers[$userid];


                        $x = new DateTime($user->user_registered, new DateTimeZone('UTC'));
                        $x->setTimeZone(new DateTimeZone('Europe/Berlin'));
                        $registeredDate = $x->format('Y-m-d H:i:s');

                        $mentorid = get_user_meta($userid, 'coachid', true);
                        $mentor  = get_userdata($mentorid);
                        $userInactivity = get_user_meta($userid, 'userInactivity', true);
                        $canSave = get_user_meta($userid, 'can_save', true);
                        $first_name = get_user_meta($userid, 'first_name', true);
                        $last_name = get_user_meta($userid, 'last_name', true);

                        $countHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countHour($userid);

                        $sumHourActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumHour($userid);


                        $countWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countWeekday($userid);

                        $sumWeekdayActive = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumWeekday($userid);


                        $countPageView = Trainingssystem_Plugin_Database::getInstance()->UserLogs->countPageView($userid);

                        $sumPageView = Trainingssystem_Plugin_Database::getInstance()->UserLogs->sumPageView($userid);

                        $trainingssystem_Plugin_Module_User_Modus = new Trainingssystem_Plugin_Module_User_Modus();

                        $mailbox = $twig->render('mailbox/mailbox.html', [
                            'ajaxurl' => admin_url('admin-ajax.php'),
                            'userid' => $userid,
                            'myid' => $current_user->ID,
                            'show_backlink' => 'false',
                            'vuejs_script_path' => plugin_dir_url(dirname(__FILE__)) . '../../assets/external/vuejs/vue.js',
                            'axios_script_path' => plugin_dir_url(dirname(__FILE__)) . '../../assets/external/vuejs/axios.min.js',
                        ]);

                        $trainers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainer();
                        
                        $user_roles = get_user_meta($userid, TRAININGSSYSTEM_PLUGIN_USER_HAS_ROLES, false);
                        if(isset($user_roles[0])) {
                            $user_roles = $user_roles[0];
                        } else {
                            $user_roles = array();
                        }
                        $allroles = Trainingssystem_Plugin_Database::getInstance()->PermissionRole->getAllRoles();
                        $roles = Trainingssystem_Plugin_Database::getInstance()->PermissionRole->getIdTitleRoles();
                        
                        $status_string = "";
                        foreach($user_roles as $u_r) {
                            if(isset($roles[$u_r])) {
                                $status_string .= $roles[$u_r] . ', ';
                            } 
                        }
                        $status_string = substr($status_string, 0, strlen($status_string)-2);
                        if(sizeof($user_roles) > 1) {
                            $status_string = $this->str_lreplace(",", " und ", $status_string);
                        }

                        $backlink = (isset($_GET['backlink']) && trim($_GET['backlink']) != "" && $_GET['backlink'] != null) ? get_permalink($_GET['backlink']) : $_SERVER["HTTP_REFERER"] ?? get_site_url();

                        $message_feedback_urls = array();
                        foreach($userChosen->getTrainings() as $training) {
                            foreach($training->getLektionsliste() as $lektion) {
                                $message_feedback_urls[$lektion->getId()] = add_query_arg(array("action" => "userlist", 
                                                                                                "type" => "feedback", 
                                                                                                "lektion" => $lektion->getId(),
                                                                                                "user" => $userChosen->getId(),
                                                                                                "subject" => "Feedback - \"" . $lektion->getTitle() . "\"",
                                                                                                "backtoorigin" => get_the_ID(), 
                                                                                                "backtouserid" => $userChosen->getId()
                                                                                            ), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"]));
                            }
                        }

                        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 = "";
                        }
                        
                        $privacy_confirmed = get_user_meta($userid, 'privacy_terms_confirmed',true);

                        if(empty($privacy_confirmed) || $privacy_confirmed == NULL){
                            $privacy_confirmed = 0;
                        }		

                        echo $twig->render('user-list/user-detail-page.html', [
                            'usermodus' => $trainingssystem_Plugin_Module_User_Modus,
                            'urlT' => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["coach_nutzer"]),
                            'message_new_url' => add_query_arg(array("action" => "userlist", "type" => "message", "user" => $userChosen->getId(), "backtoorigin" => get_the_ID(), "backtouserid" => $userChosen->getId()), get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_view"])),
                            'message_feedback_urls' => $message_feedback_urls,
                            'user' => $user,
                            'user_registered' => $registeredDate,
                            'listuser' => $userChosen,
                            'mentor' => $mentor != null ? $mentor : null,
                            'canSave' => $canSave!= null ? $canSave : 1,
                            'userInactivity' => $userInactivity,
                            'first_name' => $first_name,
                            'last_name' => $last_name,
                            'counthouractive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['labels']),
                            'counthouractive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countHourActive['values']),
                            'sumhouractive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['labels']),
                            'sumhouractive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumHourActive['values']),
                            'countweekdayactive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['labels']),
                            'countweekdayactive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countWeekdayActive['values']),
                            'sumweekdayactive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['labels']),
                            'sumweekdayactive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumWeekdayActive['values']),
                            'countpageactive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['labels']),
                            'countpageactive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($countPageView['values']),
                            'sumpageactive_l' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['labels']),
                            'sumpageactive_v' => Trainingssystem_Plugin_Module_Systemstatistics::convertToJsonLBLStr($sumPageView['values']),
                            'ajaxurl' => admin_url('admin-ajax.php'),
                            'user_list_link' => get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["user_list"]),
                            'back_link' => $backlink,
                            'mailbox' => $mailbox,
                            'postid' => get_the_ID(),
                            'edit' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("useredit"),
                            'trainers' => $trainers,
                            'user_roles' => $user_roles,
                            'allroles' => $allroles,
                            'resendRegistrationMail' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzernew"),
                            '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"),
                            'userCanSeeTrainingsProgress' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingprogress"),
                            'status_string' => $status_string,
                            'hideMails' => isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']),
                            'privacy_confirmed' => $privacy_confirmed,
                            'privacy_terms_URL' => $privacy_terms_URL,
                            'canSendMessages' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nachrichtennew"),
                            'canSeeUserModus' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("usermodus"),
                            'canSeeCoachingCard' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverview") || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("coachingoverviewsupervisor"),
                            'canAddTrainings' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingmgr"),
                            'canSeeCompanyInformationCard' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrall") || Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("companymgrown"),
                            'canSeeUserStatistics' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userdetailsstatistics"),
				            'canSeeHiddenTrainings' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden"),
                        ]);
                    } else {
                        return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
                    }   
                    
                } else {
                    return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
                }
            }
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    function saveUserDetail() {
        $hideMails = isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']);
        
        $userid = (isset($_POST['userid'])) ? intval(sanitize_text_field($_POST['userid'])) : '';
        $mail = (isset($_POST['usermail'])) ? sanitize_text_field($_POST['usermail']) : '';
        $studienid = (isset($_POST['studienid'])) ? sanitize_text_field($_POST['studienid']) : '';
        $studiengruppenid = (isset($_POST['studiengruppenid'])) ? sanitize_text_field($_POST['studiengruppenid']) : '';
        $userInactivity = (isset($_POST['userInactivity'])) ? sanitize_text_field($_POST['userInactivity']) : '';
        $coachid = (isset($_POST['coachid'])) ? sanitize_text_field($_POST['coachid']) : '';
        $canSave = (isset($_POST['canSave'])) ? sanitize_text_field($_POST['canSave']) : '';

        if(trim($userid) != "" && is_numeric($userid) && ($hideMails || (trim($mail) != "" && filter_var($mail, FILTER_VALIDATE_EMAIL)))) {
            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("useredit") && self::userAccessAllowed($userid)) {

                $user_data = null;
                if(!$hideMails) {
                    $user_data = wp_update_user( array( 'ID' => $userid, 'user_email' => $mail ) );
                }
                if(!is_wp_error($user_data) || $hideMails) {
                    if(!update_user_meta($userid, 'studienid', $studienid)) {
                        if(get_user_meta($userid, 'studienid', true) != $studienid) {
                            echo "error updating studienid";
                        }
                    } 
                    if(!update_user_meta($userid, 'studiengruppenid', $studiengruppenid)) {
                        if(get_user_meta($userid, 'studiengruppenid', true) != $studiengruppenid) {
                            echo "error updating studiengruppenid";
                        }
                    } 
                    if((is_numeric($coachid) && get_user_by('id', $coachid) != false ) || $coachid == "") {
                        if(!update_user_meta($userid, 'coachid', $coachid)) {
                            if(get_user_meta($userid, 'coachid', true) != $coachid) {
                                echo "error updating coachid";
                            }  
                        }
                    } else {
                        echo "coach not found";
                    }

                    if(is_numeric($userInactivity) || $userInactivity == ""){
                        if(!update_user_meta($userid, 'userInactivity', $userInactivity)) {
                            if(get_user_meta($userid, 'userInactivity', true) != $userInactivity) {
                                echo "error updating userInactivity";
                            }  
                        }
                    }

                    if (is_numeric($canSave)) {
                        if($canSave == 1){      
                            update_user_meta($userid, 'can_save', 1);
                        }else{
                            update_user_meta($userid, 'can_save', 0);
                        } 
                    }

                    if(isset($_POST['permissions'])) {

                        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("nutzerpermissions")) 
                        {
                        
                            delete_user_meta($userid, TRAININGSSYSTEM_PLUGIN_USER_HAS_ROLES);

                            if(is_array($_POST['permissions']) && sizeof($_POST['permissions']) > 0) {
                                $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($userid, TRAININGSSYSTEM_PLUGIN_USER_HAS_ROLES, $permissions)) {
                                            echo "Fehler beim Anlegen der Berechtigungen!";
                                        }
                                    } else {
                                        echo "access denied for roles";
                                    }
                                }
                            }
                        }
                    }
                    
                    echo "1";
                } else {
                    echo "error updating user";
                }
            } else {
                echo "access denied";
            }
        } else {
            echo "wrong data";
        }
        wp_die();
    }

    function userDelete() {
        if(isset($_POST['userid']) && is_numeric($_POST['userid'])) {

            $user_id = sanitize_text_field($_POST['userid']);

            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("useredit") && self::userAccessAllowed($user_id)) {

                $trainingssystem_Plugin_Module_User_Remover_Admin = new Trainingssystem_Plugin_Module_User_Remover_Admin();
                $trainingssystem_Plugin_Module_User_Remover_Admin->user_delete_content($user_id);

                if ( wp_delete_user( $user_id ) ) {
                    echo "1";
                }else{
                    echo "error del user";
                }

            } else {
                echo "access denied";
            }

        } else {
            echo "ungültige user-id";
        }
        wp_die();
    }

    function resendRegistration() {
        if(isset($_POST['userid']) && is_numeric($_POST['userid'])) {

            $user_id = sanitize_text_field($_POST['userid']);

            if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("useredit") && self::userAccessAllowed($user_id)) {

                if ( ! $user = get_userdata( $user_id ) ) {
                    echo "user not found";
                } else {
                    wp_new_user_notification( $user_id, null, 'both' );
                    echo "1";
                }

            } else {
                echo "access denied";
            }

        } else {
            echo "ungültige user-id";
        }
        wp_die();
    }

    /**
     * Check if a specific user with userid $user_id has a specific role $role
     * 
     * @param $role role to check
     * @param $user_id user_id to check, if null take current user
     * 
     * @return user_id has role 
     */
    function user_has_role($role, $user_id = null)
    {
        if (is_numeric($user_id)) {
            $user = get_userdata($user_id);
        } else {
            $user = wp_get_current_user();
        }
        if (!empty($user)) {
            return in_array($role, (array) $user->roles);
        } else {
            return false;
        }
    }

    /**
     * Checks if a user has access to view another user
     * 
     * @param int User-ID of user to be looked at
     * 
     * @return boolean allowed true/false
     */
    function userAccessAllowed($userid) {
        
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlistall")) {
            return true;
        }

        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlistsubscriber") && self::user_has_role("subscriber", $userid)) {
            return true;
        }

        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlistcoach")) {
            $coachuserids = array();
            $allusersbycoach = get_users(array('meta_key' => 'coachid', 'meta_value' => get_current_user_id()));
            foreach($allusersbycoach as $coachuser) {
                $coachuserids[] = $coachuser->ID;
            }
            if(in_array($userid, $coachuserids)) {
                return true;
            }
        }
        
        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlistcompany")) {
            $companyusers = Trainingssystem_Plugin_Database::getInstance()->CompanyDao->getAllUsersByCreaterId(get_current_user_id());
            $companyuserids = array();
            foreach($companyusers as $companyuser){
                $companyuserids[] = $companyuser->getId();
            }
            if(in_array($userid, $companyuserids)){
                return true;
            }
        }

        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("userlistown")) {
            $ownuserids = array();
            $alluserscreatedbycurrentuser = get_users(array('meta_key' => 'created_by', 'meta_value' => get_current_user_id()));
            foreach($alluserscreatedbycurrentuser as $ownuser) {
                $ownuserids[] = $ownuser->ID;
            }
            if(in_array($userid, $ownuserids)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Saves a user meta and checks if it was successfully added
     * 
     * @param userid Userid
     * @param metakey Key to insert
     * @param metavalue Value to insert
     * @return if new metavalue successfully inserted
     */
    function saveUserMeta($userid, $metakey, $metavalue) 
    {
        $insertvalue = $metavalue == "true" ? "1" : "";

        if(!update_user_meta($userid, $metakey, $insertvalue)) {
            $metanew = get_user_meta($userid, $metakey, true);

            if(($metavalue == "true" && $metanew == "1") ||
                $metavalue == "false" && $metanew == "") {
                    return true;
                }
                else {
                    return false;
                }
        } else {
            return true;
        }
        return false;
    }

	/**
	 * 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;
	}

}
