<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class DateBook_Login
 *
 * @class DateBook_Login
 * @package DateBook/Classes
 * @author Pagick Themes
 */
class DateBook_Login {


	/**
	 * Hook actions and filters.
	 * 
	 * @since 1.0
	 * @access public
	 */
	public static function init() {

		add_action( 'init', array( __CLASS__, 'datebook_custom_login_page' ) );
		add_action( 'init', array( __CLASS__, 'proccess_login_out' ) );
		//add_action( 'wp_logout', array( __CLASS__, 'redirect_to_after_logout' ) );
		add_action( 'datebook_login_out', array( __CLASS__, 'proccess_login_out' ) );
		add_action( 'datebook_login_form', array( __CLASS__, 'datebook_show_login_form' ) );

		add_filter( 'auth_cookie_expiration', array( __CLASS__, 'datebook_login_timeout') );

		add_shortcode( 'datebook_login_form', array( __CLASS__, 'pre_process_login_form' ) );

	}


	/**
	 * Disable WP login if option enabled in Theme settings. Login redirects.
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_custom_login_page() {

		global $pagenow;
		
		$page = basename($_SERVER['REQUEST_URI']);
		
		// Check if a $_GET['action'] is set, and if so, load it into $action variable
		$action = (isset($_GET['action'])) ? $_GET['action'] : '';
		
		// Check if we're on the login page, and ensure the action is not 'logout'
		if(!is_user_logged_in() && of_get_option('override_wp_login') == 1 && ($pagenow == 'wp-login.php' || $page == 'wp-login.php') && ( ! $action || ( $action && ! in_array($action, array('logout', 'lostpassword', 'rp', 'resetpass')))) && $_SERVER['REQUEST_METHOD'] == 'GET') {

			if ( isset( $_POST['wp-submit'] ) ||   // in case of LOGIN
				( isset($_GET['action']) && $_GET['action']=='logout') ||   // in case of LOGOUT
				( isset($_GET['checkemail']) && $_GET['checkemail']=='confirm') ||   // in case of LOST PASSWORD
				( isset($_GET['checkemail']) && $_GET['checkemail']=='registered') ) return;    // in case of REGISTER

			wp_redirect(get_permalink(of_get_option('login_page')));
			exit();

		}
	}


	/**
	 * Redirect to some page after logout
	 *
	 * @access public
	 * @return void
	 */
	private static function redirect_to_after_logout() {

		$redirect_to_after_logout = of_get_option('redirect_to_after_logout');

		if( $redirect_to_after_logout) {
			wp_redirect(get_permalink($redirect_to_after_logout));
		} else {
			wp_redirect(get_permalink(of_get_option('login_page')));
		}

		exit();

	}


	/**
	 * Login and Logout function
	 *
	 * @access public
	 * @return void
	 */
	public static function proccess_login_out() {

		if ( !is_user_logged_in() ) {
			
			if (isset($_POST['submit']) && isset($_POST['testcookie']) && isset($_POST['testcookie']) == 1) {

				global $datebook_form_error;

				$update_data = array();

				// instantiate the class
				$datebook_form_error = new WP_Error;

				// Get post data
				$login_data = array();
				$user_login = stripslashes(sanitize_text_field($_POST['log']));

				if (is_email($user_login)) {
					if ($user = get_user_by('email', $user_login)) {
						$login_data['user_login'] = $user->user_login;
					}
				} else {
					$login_data['user_login'] = $user_login;
				}

				if (isset($_POST['pwd'])) {
					$login_data['user_password'] = stripslashes(sanitize_text_field($_POST['pwd']));
				}

				$login_data['remember'] = isset($_POST['remember']) ? true : false;


				// Google reCaptcha process
				$google_recaptcha_error = DateBook_Utilities::datebook_google_recaptcha_response('login');

				// Login
				$user_verify = wp_signon($login_data, false);
				
				$is_wp_error_user_verify = is_wp_error($user_verify) ? 1 : 0;

				if ($is_wp_error_user_verify || $google_recaptcha_error == 1) {
					
					if ($is_wp_error_user_verify) {
						$datebook_form_error->add( 'error_login', esc_html__( 'You have entered wrong data', 'datebook' ), 'has-error' );
					}
					
					if($google_recaptcha_error == 1){
						$datebook_form_error->add( 'wrong_recaptcha', esc_html__( 'Check the captcha form', 'datebook' ), 'has-error' );
					}

				} else {

					$user_id = isset($user_verify->ID) && $user_verify->ID > 0 ? $user_verify->ID : 0;

					update_user_meta( absint($user_id), 'last_logout', 0 );

					// Remember when user logged in
					$activity_time = strtotime(gmdate( 'Y-m-d H:i:s' ) . ' GMT');
					update_user_meta( absint($user_id), 'login_time', $activity_time );

					wp_set_auth_cookie($user_id, true, false );

					//$delete_all_message_session = DateBook_Cron::cron_gc($user_id);

					if (is_super_admin($user_id)) {
						$redirect_to = admin_url();
					} else {
						$redirect_to_after_login = of_get_option('redirect_to_after_login') ? of_get_option('redirect_to_after_login') :  of_get_option('my_messages_page');
						$redirect_to = get_permalink($redirect_to_after_login);
					}

					$datebook_redirect_to = isset($_COOKIE['datebook_redirect_to']) ? $_COOKIE['datebook_redirect_to'] : $redirect_to;

					wp_redirect($datebook_redirect_to);
					exit();

				}
			}

		} else {

			// Logout
			if (isset($_GET['action']) && $_GET['action'] == 'logout') {

				if (is_user_logged_in()) {

					if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
						$current_user_id = DATEBOOK_CURRENT_USER_ID;
					} else {
						global $current_user;
						wp_get_current_user();
						$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
					}

					update_user_meta($current_user_id, 'last_logout', 1);

					clean_user_cache($current_user_id);

					wp_destroy_current_session();
					wp_clear_auth_cookie();
					wp_set_current_user(0);

					//wp_logout();

					self::redirect_to_after_logout();

				}

			} else if(of_get_option('login_page') > 0 && get_the_ID() > 0 && of_get_option('login_page') == get_the_ID()){

				if (is_super_admin()) {
					$redirect_to = admin_url();
				} else {
					$redirect_to = of_get_option('redirect_to_after_login') ? of_get_option('redirect_to_after_login') :  of_get_option('my_messages_page');
				}

				wp_redirect($redirect_to);
				exit();

			}

		}
	}


	/**
	 * Reset password
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_process_resetpassword() {
		
		// Resets the user's password if the password reset form was submitted.
		if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'resetpassword' && isset($_REQUEST['keyreset'])) {
			
			global $wpdb, $datebook_form_error, $takekeyreset;

			$update_data = array();
			
			// instantiate the class
			$datebook_form_error = new WP_Error;

			//check if the user has clicked the validation link
			$takekeyreset = esc_attr($_REQUEST['keyreset']);
			$ekeyreset = preg_replace("/([^a-zA-Z0-9])/", '', $takekeyreset);

			$user_id = $wpdb->get_var($wpdb->prepare("SELECT `user_id` FROM `".$wpdb->usermeta."` WHERE `meta_key` = 'resetpassword' AND `meta_value` = '%s' LIMIT 1", $ekeyreset));

			if ($user_id) {

				$resetpassword = get_user_meta( $user_id, 'resetpassword', true);

				if ($takekeyreset != $resetpassword) {

					$datebook_form_error->add( 'error_login', esc_html__( 'The key you have entered does not exist.', 'datebook' ), 'has-error' );
					
				} else {
					
					if(isset($_POST['action']) && $_POST['action'] == 'resetpassword' && isset($_POST['keyreset'])) {
						
						if (empty($_POST['pwd1'])) {
							// Password is empty
							$datebook_form_error->add( 'error_login', esc_html__( 'You need to type in a new password.', 'datebook' ), 'has-error' );
						} else if (empty($_POST['pwd2'])) {
							// Second Password is empty
							$datebook_form_error->add( 'error_login', esc_html__( 'You need to repeat a new password.', 'datebook' ), 'has-error' );
						} else if (!empty($_POST['pwd1']) && !empty($_POST['pwd2'])) {
							if ($_POST['pwd1'] != $_POST['pwd2']) {
								// Passwords don't match
								$datebook_form_error->add( 'error_login', esc_html__( 'The two passwords you entered don\'t match.', 'datebook' ), 'has-error' );
							} else {
								wp_set_password($_POST['pwd1'], $user_id);
								//delete_user_meta( $user_id, "resetpassword", $ekeyreset );
								$datebook_form_error->add( 'success_login', esc_html__( 'Your password has successfully been changed. Now you may login.', 'datebook' ), 'has-error' );
								
								$_REQUEST['action'] = '';
								$_REQUEST['keyreset'] = '';
							}
						
						} else {
							
							$datebook_form_error->add( 'error_login', esc_html__( 'You must create a new password.', 'datebook' ), 'has-error' );
							
						}
					}
				}
				
			} else {

				$datebook_form_error->add( 'error_login', esc_html__( 'The key you have entered does not exist.', 'datebook' ), 'has-error' );

			}
			
		}
		
	}


	/**
	 * Forgot password
	 *
	 * @access private
	 * @return void
	 */
	private static function datebook_process_forgotpassword() {
		
		if(isset($_POST['forgotpassword'])) {
			
			global $datebook_form_error;

			$update_data = array();

			// instantiate the class
			$datebook_form_error = new WP_Error;

			$user_login = stripslashes(sanitize_text_field($_POST['log']));
			
			if ( empty( $user_login) ) {

				$datebook_form_error->add( 'error_login', esc_html__( 'You need to enter your email address to continue.', 'datebook' ), 'has-error' );

			} else if ( is_email( $user_login ) ) {

				if ( $user_data = get_user_by( 'email', $user_login ) ) {

					$user_id = $user_data->ID;
					$to_user_email = $user_data->user_email;
					$profile_name = $user_data->display_name;
					$salt = wp_generate_password(20);
					$keyforgot = sha1($salt . $to_user_email . uniqid(time(), true));

					$reset_link = add_query_arg( array(
						'action' => 'resetpassword',
						'keyreset' => $keyforgot
					), get_permalink(of_get_option('login_page')) );


					$subject_in_email = sprintf( esc_html__( 'Password Reset - %s', 'datebook' ), of_get_option('email_sitename') );

					// Put all data to an array
					$datebook_email_var = array(
						'select_email_template' => 'retrieve_password_message',
						'subject' => $subject_in_email,
						'profile_name' => $profile_name
					);

					set_query_var( 'datebook_email_var', $datebook_email_var );


					include DateBook_Template_Loader::locate( 'misc/email-templates' );
					
					$from_name = of_get_option('email_sitename');
					$from_email = of_get_option('email_siteemail');
					
					$datebook_mail = DateBook_Utilities::datebook_email_send($from_name, $from_email, $to_user_email, $subject_in_email, $body);

					update_user_meta( $user_id, 'resetpassword', $keyforgot );

					$datebook_form_error->add( 'success_login', esc_html__( 'Link for password reset has been emailed to you. Check your email.', 'datebook' ), 'has-error' );
					
				} else {

					$datebook_form_error->add( 'error_login', esc_html__( 'There is no user registered with this email', 'datebook' ), 'has-error' );

				}
				
			} else {
				
				$datebook_form_error->add( 'error_login', esc_html__( 'Your email address does not seem to be in the correct format', 'datebook' ), 'has-error' );

			}
			
		}
		
	}


	/**
	 * Return login form
	 *
	 * @access public
	 * @return void
	 */
	public static function pre_process_login_form($atts = array()){

		if ( !is_user_logged_in() ) {

			if( isset($_REQUEST['action']) && $_REQUEST['action'] == 'resetpassword' && isset($_REQUEST['keyreset']) ) {
			
				// update all the input data
				self::datebook_process_resetpassword();
			
				// display the Reset Password form
				return DateBook_Template_Loader::load( 'login/login-resetpassword' );
			
			} else if (of_get_option('forgot_password_page') == get_the_ID()){

				// update all the input data
				self::datebook_process_forgotpassword();
			
				// display the Forgot Password form
				return DateBook_Template_Loader::load( 'login/login-forgotpassword' );
			
			} else {

				// display the Login form
				return DateBook_Template_Loader::load( 'login/login-form' );

			}
		
		} else {

			// display the Login form
			return DateBook_Template_Loader::load( 'login/logged-in-already' );

		}

	}


	/**
	 * Show login form
	 *
	 * @access public
	 * @return void
	 */
	public static function return_login_form(){
		
		$atts = array('shortcode' => 0);

		// Show Login form
		echo self::pre_process_login_form($atts);

	}


	/**
	 * Show login form
	 *
	 * @access public
	 * @return void
	 */
	public static function datebook_show_login_form() {

		if (isset($_GET['message']) && $_GET['message'] == 'mustlogin') {

			echo DateBook_Template_Loader::load( 'login/login-must-login-alert' );

		}

		echo DateBook_Template_Loader::load( 'login/login' );

	}


	/**
	 * Stay logged in for longer periods
	 *
	 * @access public
	 */
	public static function datebook_login_timeout() {
		
		$expire_days = of_get_option('login_timeout') > 0 ? of_get_option('login_timeout') : 1;
		
		//WP defaults to 48 hrs/2 days;
		$expiration = $expire_days * 86400;
		
		//http://en.wikipedia.org/wiki/Year_2038_problem
		if (PHP_INT_MAX - time() < $expiration){
			//Fix to a little bit earlier!
			$expiration =  PHP_INT_MAX - time() - 5;
		}
		
		return $expiration;

	}


}

DateBook_Login::init();