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

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

	}

	public function coach_edit_user_profile($atts){

		/**
		 * Ansatz einer Übersetzung. Kann für weitere Seiten fortgeführt werden.  
		**/
		
		include 'profile-text.php';

		if(!isset($atts['titel'])){
			$heading = __("Mein Profil", TRAININGSSYSTEM_PLUGIN_SLUG);
		}
		else{
			$heading = $atts['titel'];
		}

		$settings = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS);

        $strength = Trainingssystem_Plugin_zxcvbn::getInstance()->zxcvbn;
		$twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
		ob_start();
		$current_user = wp_get_current_user();
		$demoUser = get_user_meta($current_user->ID, 'demo_user', true);
		if ( 0 == $current_user->ID || $demoUser == "0" || $demoUser == "1") {
			return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
		}else{
			$user_id = $current_user->ID;
			$nonceaction_delete_content = TRAININGSSYSTEM_PLUGIN_SLUG.'delete-content';
			$noncefield_delete_account = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-delete-content';
			$nonceaction_delete_content_account = TRAININGSSYSTEM_PLUGIN_SLUG.'delete-content-account';
			$noncefield_delete_content_account = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-delete-content-account';
			$nonceaction_form_profile_edit = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-edit';
			$noncefield_form_profile_edit = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-edit';
			$nonceaction_form_profile_mail = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-mail';
			$noncefield_form_profile_mail = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-mail';

			$messages_notification_days = intval(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["mailbox_notification_interval"]);
			$notifications = get_user_meta($user_id, 'mailbox_notifications', true);
			if($notifications == ""){
				$notifications = "1";
			}
		

			$allusers = Trainingssystem_Plugin_Database::getInstance()->NutzerDao->getMyNutzer(true);
			$listuser = $allusers[$user_id];
			$nonceaction_register = TRAININGSSYSTEM_PLUGIN_SLUG.'submitregkey';
			$noncefield_register = 'regkey';

			$user_roles = get_user_meta($user_id, TRAININGSSYSTEM_PLUGIN_USER_HAS_ROLES, false);
			$roles = Trainingssystem_Plugin_Database::getInstance()->PermissionRole->getIdTitleRoles();
			
			$status_string = "";
			if(isset($user_roles[0])) {
				foreach($user_roles[0] 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[0]) > 1) {
					$status_string = $this->str_lreplace(",", " und ", $status_string);
				}
			}

			$nonceaction_form_profile_name = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-name';
			$noncefield_form_profile_name = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-name';

			$nonceaction_form_profile_phonenumber = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-phonenumber';
			$noncefield_form_profile_phonenumber = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-phonenumber';

			$nonceaction_form_profile_privacy = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-privacy';
			$noncefield_form_profile_privacy = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-privacy';

			$userPhonenumber = get_user_meta($user_id, 'phonenumber', true);
			$privacy_confirmed = get_user_meta($user_id, 'privacy_terms_confirmed',true);

			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($privacy_confirmed) || $privacy_confirmed == NULL){
				$privacy_confirmed = 0;
			}

			$rejectPrivacyTermsAllowed = false;
			if (!empty(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['reject_privacy_terms'])){
				$rejectPrivacyTermsAllowed = get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['reject_privacy_terms'];
			}

			$profileLayout = "profile_layout_double_column";
			if(isset($settings['profile_layout'])){
				$profileLayout = $settings['profile_layout'];
			}

			$showName = true;
			if(isset($settings['hide_profile_name'])){
				$showName = false;
			}

			$showPhonenumber = true;
			if(isset($settings['hide_profile_phonenumber'])){
				$showPhonenumber = false;
			}

			$showTrainings = true;
			if(isset($settings['hide_profile_trainings'])){
				$showTrainings = false;
			}

			$showRegistercode = true;
			if(isset($settings['hide_profile_registercode'])){
				$showRegistercode = false;
			}

			echo $twig->render('user-profile/user-profil.html',[
				'submitnoncedelcontent'=>wp_nonce_field($nonceaction_delete_content,$noncefield_delete_account,true,false),
				'submitnoncedeluser'=>wp_nonce_field($nonceaction_delete_content_account,$noncefield_delete_content_account,true,false),
				'submitnonceprofedit'=>wp_nonce_field($nonceaction_form_profile_edit,$noncefield_form_profile_edit,true,false),
				'submitnonceprofmail'=>wp_nonce_field($nonceaction_form_profile_mail,$noncefield_form_profile_mail,true,false),
				'submitnonceprofname'=>wp_nonce_field($nonceaction_form_profile_name,$noncefield_form_profile_name,true,false),
				'submitnonceprofphonenumber'=>wp_nonce_field($nonceaction_form_profile_phonenumber,$noncefield_form_profile_phonenumber,true,false),
				'submitnonceprofprivacy'=>wp_nonce_field($nonceaction_form_profile_privacy,$noncefield_form_profile_privacy,true,false),
				'mail'=> $current_user->user_email,
           		'messages_notification_days' => $messages_notification_days,
            	'notifications' => $notifications,
				'register_nonce' =>wp_nonce_field($nonceaction_register,$noncefield_register,true,false),
				'listuser' => $listuser,
				'training_button' => false,
				'url'=>site_url(),
				'status_string' => $status_string,
				'hideMails' => isset(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)['hide_mails']),
				'heading' => $heading,
				'text' => $profile_text,
				'firstname' => $current_user->user_firstname,
				'lastname' => $current_user->user_lastname,
				'phonenumber' => $userPhonenumber,
				'privacy_terms_URL' => $privacy_terms_URL,
				'privacy_confirmed' => $privacy_confirmed,
				'rejectPrivacyTermsAllowed' => $rejectPrivacyTermsAllowed,
				'admin_mail' => get_option('admin_email'),
				'website_name' => get_bloginfo(),
				'userCanSeeTrainingsProgress' => true,
				'profileLayout' => $profileLayout,
				'showName' => $showName,
				'showPhonenumber' => $showPhonenumber,
				'showTrainings' => $showTrainings,
				'showRegistercode' => $showRegistercode,
				'canSeeHiddenTrainings' => Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingshidden"),
			]
		);
		}
		return ob_get_clean();

	}

	function saveMail() {

		$nonceaction_form_profile_mail = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-mail';
		$noncefield_form_profile_mail = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-mail';
		
		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			if(wp_verify_nonce( $_POST[$noncefield_form_profile_mail], $nonceaction_form_profile_mail ) && isset($_POST['email']))
			{
				if(isset($_POST['notification'])) {
					update_user_meta($user_id, 'mailbox_notifications', $_POST['notification']);
				} 

				//echo "edit user mail";
				$mail = strtolower(sanitize_email($_POST['email']));
				if($mail !=""){
					$user_id_erg = wp_update_user( array( 'ID' => $user_id, 'user_email' => $mail ) );
					if ( is_wp_error( $user_id_erg ) ) {
						// There was an error, probably that user doesn't exist.
						echo "0";
					} else {
						// User Event
						$title = "E-Mail Einstellungen erfolgreich geändert";
						$subtitle = "";
						// Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
						Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]), "profile", "important");
						
						echo "1";
					}
				}
			}
		}
		wp_die();
	}

	function savePassword() {

		$strength = Trainingssystem_Plugin_zxcvbn::getInstance()->zxcvbn;

		$nonceaction_form_profile_edit = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-edit';
		$noncefield_form_profile_edit = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-edit';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			if(wp_verify_nonce( $_POST[$noncefield_form_profile_edit], $nonceaction_form_profile_edit )&& isset($_POST['pw0']) && isset($_POST['pw1']) && isset($_POST['pw2'])  ){
				//echo "edit user account";
				$pw0 = sanitize_text_field($_POST['pw0']);  //altes pass
				$pw1 = sanitize_text_field($_POST['pw1']);      // neues pass
				$pw2 = sanitize_text_field($_POST['pw2']);        // wiederholt neues pass

				if($pw1!= "" && $pw1== $pw2){
					if ($pw0!= "" && wp_check_password( $pw0, $current_user->user_pass, $user_id ) ) {
						if($strength->passwordStrength($pw1)['score'] >= 4 ) {
							//echo "That's it";
							echo "1";
							wp_set_password($pw1, $user_id);    // wird pass gesetzt

							// User Event
							$title = "Passwort erfolgreich geändert";
							$subtitle = "";
							// Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
							Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]), "profile", "important");
							
						}else{
							echo "tooweak";
						}
					} else {
						echo "falseold";
					}
				} else {
					echo "falseconfirm";
				}
			}
		}
		wp_die();
	}

	function saveName(){

		$nonceaction_form_profile_name = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-name';
		$noncefield_form_profile_name = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-name';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			if(wp_verify_nonce( $_POST[$noncefield_form_profile_name], $nonceaction_form_profile_name )&&isset($_POST['user_firstname'])&&isset($_POST['user_lastname'])){
				$userFirstname = sanitize_text_field($_POST['user_firstname']);
				$userLastname = sanitize_text_field($_POST['user_lastname']);

				update_user_meta($user_id, 'first_name', $userFirstname);
				update_user_meta($user_id, 'last_name', $userLastname);

				// User Event
				$title = "Namen erfolgreich geändert";
				$subtitle = "";
				// Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
				Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]), "profile", "info");

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

	function savePhonenumber(){

		$nonceaction_form_profile_phonenumber = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-phonenumber';
		$noncefield_form_profile_phonenumber = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-phonenumber';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			if(wp_verify_nonce( $_POST[$noncefield_form_profile_phonenumber], $nonceaction_form_profile_phonenumber )&&isset($_POST['user_phonenumber'])){
				$userPhonenumber = sanitize_text_field($_POST['user_phonenumber']);
				
				update_user_meta($user_id, 'phonenumber', $userPhonenumber);
				
				// User Event
				$title = "Telefonnummer erfolgreich geändert";
				$subtitle = "";
				// Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
				Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]), "profile", "info");

				echo "1";
			}
		}
		wp_die();

	}


	function savePrivacy(){

		$nonceaction_form_profile_privacy = TRAININGSSYSTEM_PLUGIN_SLUG.'form-profile-privacy';
		$noncefield_form_profile_privacy = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-profile-privacy';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			 if(wp_verify_nonce( $_POST[$noncefield_form_profile_privacy], $nonceaction_form_profile_privacy )){			
			
				$privacy_terms_confirmed = isset($_POST['privacy_terms_confirmed']) ? sanitize_text_field($_POST['privacy_terms_confirmed']) : "";

				if ($privacy_terms_confirmed == 'true') {
					update_user_meta($user_id, 'privacy_terms_confirmed', date('d.m.Y'));
					echo "1";
				}
				else{
					delete_user_meta($user_id, 'privacy_terms_confirmed');
				 	echo "1";
				}
			 }
		 }
		wp_die();

	}

	function deleteContent() {

		$nonceaction_delete_content = TRAININGSSYSTEM_PLUGIN_SLUG.'delete-content';
		$noncefield_delete_account = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-delete-content';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_user->ID;

			if(wp_verify_nonce( $_POST[$noncefield_delete_account], $nonceaction_delete_content )){

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

				// User Event
				$title = "Alle Eingaben erfolgreich gelöscht";
				$subtitle = "";
				// Params: $title, $subtitle, $userid, $postid (= null), $url, $type, $level, $date (= null)
				Trainingssystem_Plugin_Database::getInstance()->UserEvent->insertUserEvent($title, $subtitle, $user_id, null, get_permalink(get_option(TRAININGSSYSTEM_PLUGIN_SETTINGS)["page_user_profil"]), "profile", "important");

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

	function deleteAccount() {

		$nonceaction_delete_content_account = TRAININGSSYSTEM_PLUGIN_SLUG.'delete-content-account';
		$noncefield_delete_content_account = TRAININGSSYSTEM_PLUGIN_SLUG.'userprofil-delete-content-account';

		$current_user = wp_get_current_user();
		if ( 0 != $current_user->ID ) {
			$user_id = $current_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_verify_nonce( $_POST[$noncefield_delete_content_account], $nonceaction_delete_content_account )){
				if ( wp_delete_user( $user_id ) ) {
						wp_clear_auth_cookie();
						echo "1";
				} else {
					echo "0";
				}
			}	
		}
		wp_die();
	}

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