<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Coach_User_Remover
 * @subpackage Coach_User_Remover/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Vorlagen-User
 * @author     Max Sternitzke
 */
class Trainingssystem_Plugin_Module_Vorlagen_User_Mgr_Public {

	private $vorlagennutzer_addon;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		$this->vorlagennutzer_addon = "@".get_bloginfo( 'name' ).".vorlagennutzer";
	}

	public function addUser() {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			if (isset($_POST['username']) &&
				strlen(trim($_POST['username'])) > 0) {
					$current_user = wp_get_current_user();

					$username = sanitize_text_field($_POST['username']).$this->vorlagennutzer_addon;
					$password = wp_generate_password(10, true, true);
					$email = uniqid('', true)."@".get_bloginfo( 'name' ).".vorlagennutzer";
					$result = wp_create_user($username, $password, $email);

					if (is_wp_error($result)) {
						echo $result->get_error_message();
					} else {
						add_user_meta( $result, 'vorlagenuser', true);
						add_user_meta( $result, 'vorlagenusercrearorid', $current_user->ID);
						if(isset($_POST['coach_id']) && is_numeric($_POST['coach_id']) && $_POST['coach_id'] > 0) {
							add_user_meta( $result, 'coachid', sanitize_text_field($_POST['coach_id']));
						}
						echo "1";
					}
			}
		}
		else
		{
			echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}
		wp_die();
	}

	public function vorlagen_user_grouper($atts){
	
		$heading = isset($atts['titel']) ? $atts['titel'] : 'Trainingsvorlagen'; 
		
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

		$current_user = wp_get_current_user();
		if ( 0 == $current_user->ID || !Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen")) {
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}else{
			$alltrainings=Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();
			$allusers = [];
			if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
			{
				$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
			}
			elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
			{
				$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
			}
			$trainer = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainer();
			return $twig->render('vorlagen-user-mgr/vorlagen-user-mgr.html',["trainings"=>$alltrainings,
																			"users"=>$allusers,
																			"trainers"=>$trainer,
																			"vorlagenuser_addon"=> $this->vorlagennutzer_addon,
																			"heading" => $heading,
																			"onlylist"=> !Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"),
																		]);
		}
	}

	public function getVorlagenUser() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
				//exit;
			}else{
				$allusers = [];
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
				{
					$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
				}
				elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
				{
					$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
				}
				echo $twig->render('vorlagen-user-mgr/vorlagen-user-mgr-userlist.html',["users"=>$allusers]);
			}
		}
		else
		{
			echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}
		wp_die();
	}

	public function getVorlagenUserEditModal() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			}else{
				$allusers_tmp = [];
				if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenall")) 
				{
					$allusers_tmp = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getVorlagenUser();
				}
				elseif (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagenown")) 
				{
					$allusers_tmp = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyVorlagenUser();
				}
				$allusers = [];
				foreach($allusers_tmp as $a_t) {
					$allusers[$a_t->getId()] = $a_t;
				}

				if(isset($_POST['vuserid']) && is_numeric($_POST['vuserid']) && isset($allusers[$_POST['vuserid']])) {

					echo $twig->render("vorlagen-user-mgr/vorlagen-user-mgr-update-user.html", [
								"trainers" => Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainer(),
								"trainings" => Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getTrainings($_POST['vuserid']),
								"vorlagenuser_addon"=> $this->vorlagennutzer_addon,
								"vuser" => $allusers[$_POST['vuserid']],
								]);

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

	public function updateUser() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			} else {
				if(isset($_POST['vorlagenuserid']) && trim($_POST['vorlagenuserid']) != "" && is_numeric($_POST['vorlagenuserid']) &&
					isset($_POST['vorlagenusername']) && trim($_POST['vorlagenusername']) != "" && strlen($_POST['vorlagenusername']) > 0) {
						
						$userid = sanitize_text_field($_POST['vorlagenuserid']);
						$username = sanitize_text_field($_POST['vorlagenusername']).$this->vorlagennutzer_addon;
						$trainerid = sanitize_text_field($_POST['vorlagenusertrainer']);

						$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') : [];

						if(in_array($userid, $vorlagennutzerids)) 
						{
							$success = true;
							if(Trainingssystem_Plugin_Database::getInstance()->NutzerDao->updateUsername($userid, $username)) {
								if(trim($trainerid) == "") {
									delete_user_meta($userid, 'coachid');
								} else if(is_numeric($trainerid)) {
									if(false === update_user_meta($userid, 'coachid', $trainerid)) {
										if(!get_user_meta($userid, 'coachid', true) == $trainerid) {
											$success = false;
										}
									}
								}
							} 

							if($success) {
								echo "1";
							} else {
								echo "0";
							}
						}
						else 
						{
							echo "access denied";
						}
				}
			}
		}
		wp_die();
	}

	public function deleteUser() {
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		if(Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("vorlagen"))
		{
			$current_user = wp_get_current_user();
			if ( 0 == $current_user->ID ) {
				echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			} else {
				if(isset($_POST['vorlagenuserid']) && trim($_POST['vorlagenuserid']) != "" && is_numeric($_POST['vorlagenuserid']) &&
					isset($_POST['deleteregisterkeys']) && ($_POST['deleteregisterkeys'] == "true" || $_POST['deleteregisterkeys'] == "false")) {

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

						$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') : [];

						if(in_array($userid, $vorlagennutzerids)) 
						{
							$success = true;
							if($_POST['deleteregisterkeys'] == "true") {
								$allcodes = Trainingssystem_Plugin_Database::getInstance()->RegisterKey->getAll();

								foreach($allcodes as $code) {
									if($code->getVorlageid() == $userid) {
										if(!Trainingssystem_Plugin_Database::getInstance()->RegisterKey->deleteCode($code->getCode())) {
											echo "0";
											$success = false;
											break;
										}
									}
								}
							}

							if($success) {
								if(wp_delete_user($userid)) {
									echo "1";
								} else {
									echo "0";
								}
							}
						}
						else 
						{
							echo "access denied";
						}

					}
			}
		}
		wp_die();
	}

}
