<?php 

//Custom Registration //
class pd_custom_registration
{
	private static $instance;

	public static function instance() {
		if ( !isset( self::$instance ) ) {
			self::$instance = new pd_custom_registration();
		}
		return self::$instance;
	}
	private function __construct()
	{

		add_shortcode( 'sbd_registration', array($this,'custom_registration_shortcode') );
		add_role( 'pduser', __( 'SBD User' ), array( ) );
	}
	
	public function custom_registration_shortcode() {

		ob_start();
		/*
		if(!session_id())
			session_start();
		*/
		wp_enqueue_script('qcld_pd_google_recaptcha', 'https://www.google.com/recaptcha/api.js', array('jquery'), '1.0.0', true);
		if(is_user_logged_in()){
			echo __('You are already a registered user!','qc-pd');
		}else{
			$this->custom_registration_function();
		}
		
		return ob_get_clean();
	}
	
	public function custom_registration_function() {
		if ( isset($_POST['submit']) && isset($_POST['sbd_policy_accept']) ) {
			
			$this->registration_validation(
				$_POST['username'],
				$_POST['password'],
				$_POST['email'],
				$_POST['fname'],
				$_POST['lname']
			);
			 
			// sanitize user form input
			global $username, $password, $email, $first_name, $last_name;
			$username   =   sanitize_user( $_POST['username'] );
			$password   =   esc_attr( $_POST['password'] );
			$email      =   sanitize_email( $_POST['email'] );
			
			$first_name =   sanitize_text_field( $_POST['fname'] );
			$last_name  =   sanitize_text_field( $_POST['lname'] );
		  
	 
			// call @function complete_registration to create the user
			// only when no WP_error is found
			$this->complete_registration(
				$username,
				$password,
				$email,
				$first_name,
				$last_name
			);
		}
	 
		$this->registration_form(
			@$username,
			@$password,
			@$email,
			@$first_name,
			@$last_name
		  
			
			);
	}

	public function pd_new_user_notification( $user_id, $plaintext_pass = '' ) {
		$user = new WP_User($user_id);

		$user_login = stripslashes($user->user_login);
		$user_email = stripslashes($user->user_email);

		$title_text = pd_ot_get_option('sbd_lan_new_user_registration_email') != '' ? pd_ot_get_option('sbd_lan_new_user_registration_email') : 'New user registration on your blog';
		$username_text = pd_ot_get_option('sbd_lan_only_username') != '' ? pd_ot_get_option('sbd_lan_only_username') : 'Username';
		$mail_text = pd_ot_get_option('sbd_lan_email') != '' ? pd_ot_get_option('sbd_lan_email') : 'Email';

		$sbd_lan_email_hi = pd_ot_get_option('sbd_lan_email_hi') != '' ? pd_ot_get_option('sbd_lan_email_hi') : __('Hi,', 'qc-pd');
		$sbd_lan_email_welcome_to = pd_ot_get_option('sbd_lan_email_welcome_to') != '' ? pd_ot_get_option('sbd_lan_email_welcome_to') : __('Welcome to', 'qc-pd');
		$sbd_lan_email_here_how_to_login = pd_ot_get_option('sbd_lan_email_here_how_to_login') != '' ? pd_ot_get_option('sbd_lan_email_here_how_to_login') : __('Here\'s how to log in', 'qc-pd');


		$message  = sprintf(__('%1$s: %2$s','qc-pd'), $title_text, get_option('blogname')) . "\r\n\r\n";
		$message .= sprintf(__('%1$s: %2$s','qc-pd'), $username_text, $user_login) . "\r\n\r\n";
		$message .= sprintf(__('%1$s: %2$s','qc-pd'), $mail_text, $user_email) . "\r\n";
		
		$new_user_registration = pd_ot_get_option('sbd_lan_new_user_registration') != '' ? pd_ot_get_option('sbd_lan_new_user_registration') : 'New User Registration';

		if(pd_ot_get_option('pd_admin_email')!=''){
			@wp_mail(pd_ot_get_option('pd_admin_email'), sprintf(__('[%s] %s','qc-pd'), get_option('blogname'), $new_user_registration), $message);
		}
		

		$username_text = pd_ot_get_option('sbd_lan_only_username') != '' ? pd_ot_get_option('sbd_lan_only_username') : 'Username';

		$message  = __($sbd_lan_email_hi) . "\r\n\r\n";
		$message .= sprintf(__("%s %s! %s:",'qc-pd'), $sbd_lan_email_welcome_to, get_option('blogname'), $sbd_lan_email_here_how_to_login ) . "\r\n\r\n";
		$message .= qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sbd_login_url','') . "\r\n";
		$message .= sprintf(__('%s: %s','qc-pd'), $username_text, $user_login) . "\r\n";
		//$message .= sprintf(__('Password: %s','qc-pd'), $plaintext_pass) . "\r\n\r\n";
		/*if(pd_ot_get_option('pd_admin_email')!=''){
			$message .= sprintf(__('If you have any stuck, please contact webmaster at %s.'), pd_ot_get_option('pd_admin_email')) . "\r\n\r\n";
		}*/
		
		$username_and_password = pd_ot_get_option('sbd_lan_new_username_and_password') != '' ? pd_ot_get_option('sbd_lan_new_username_and_password') : 'Your username and password';

		wp_mail($user_email, sprintf(__('[%s] %s','qc-pd'), get_option('blogname'), $username_and_password ), $message);

	}




	public function registration_validation( $username, $password, $email, $first_name, $last_name)  {
		global $reg_errors;
		$reg_errors = new WP_Error;

		if ( empty( $username ) || empty( $password ) || empty( $email ) ) {
			$reg_errors->add('field', pd_ot_get_option('sbd_lan_required_field_missing') != '' ? pd_ot_get_option('sbd_lan_required_field_missing') : __('Required form field is missing','qc-pd'));
		}elseif( 4 > strlen( $username ) ){
			$reg_errors->add( 'username_length', pd_ot_get_option('sbd_lan_username_too_short') != '' ? pd_ot_get_option('sbd_lan_username_too_short') : __('Username too short. At least 4 characters is required','qc-pd') );
		}elseif( 5 > strlen( $password ) ){
			$reg_errors->add( 'password', pd_ot_get_option('sbd_lan_pwd_length_too_short') != '' ? pd_ot_get_option('sbd_lan_pwd_length_too_short') : __('Password length must be greater than 5','qc-pd') );
		}elseif( !is_email( $email ) ){
			$reg_errors->add( 'email_invalid', pd_ot_get_option('sbd_lan_email_not_valid') != '' ? pd_ot_get_option('sbd_lan_email_not_valid') : __('Email is not valid','qc-pd') );
		}elseif( email_exists( $email ) ){
			$reg_errors->add( 'email', pd_ot_get_option('sbd_lan_email_already_in_use') != '' ? pd_ot_get_option('sbd_lan_email_already_in_use') : __('Email Already in use','qc-pd') );
		}elseif( ! validate_username( $username ) ){
			 $reg_errors->add( 'username_invalid', pd_ot_get_option('sbd_lan_username_not_valid') != '' ? pd_ot_get_option('sbd_lan_username_not_valid') : __('Sorry, the username you entered is not valid','qc-pd') );
		}elseif(isset($_POST['ccode']) && ((strtolower($_POST['ccode'])))!==strtolower($_POST['pdccode'])){
			if( pd_ot_get_option( 'pd_enable_captcha')=='on' && pd_ot_get_option( 'pd_enable_recaptcha')=='off' ){
		    	$reg_errors->add('captcha_invalid', pd_ot_get_option('sbd_lan_captcha_not_match') != '' ? pd_ot_get_option('sbd_lan_captcha_not_match') : __('Captcha does not match!','qc-pd'));
			}
        }

        if( pd_ot_get_option( 'pd_enable_captcha')=='on' && pd_ot_get_option( 'pd_enable_recaptcha')=='on' ){
			if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
		        $secret = pd_ot_get_option( 'pd_recaptcha_secret_key');
		        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
		        $responseData = json_decode($verifyResponse);
		        if($responseData->success)
		        {
		            //$succMsg = 'Your contact request have submitted successfully.';
		        }
		        else
		        {
		        	$reg_errors->add('robot_verification_failed', __('Robot verification failed, please try again.','qc-opd'));
		        }
		    }else{
		    	$reg_errors->add('robot_verification_failed', __('Robot verification failed, please try again.','qc-opd'));
		    }
		}

		if ( username_exists( $username ) )
			$reg_errors->add('user_name', pd_ot_get_option('sbd_lan_username_already_exist') != '' ? pd_ot_get_option('sbd_lan_username_already_exist') : __('Sorry, that username already exists!','qc-pd') );



		if ( is_wp_error( $reg_errors ) ) {
		 
			foreach ( $reg_errors->get_error_messages() as $error ) {
			 
				echo '<div style="color: red;border: 1px solid #e38484;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;">';
				echo '';
				echo $error . '<br/>';
				echo '</div>';
				 
			}
		 
		}
	}
	public function complete_registration() {
		global $reg_errors, $username, $password, $email, $first_name, $last_name, $bio;
		if ( 1 > count( $reg_errors->get_error_messages() ) ) {
			$userdata = array(
				'user_login'    =>   $username,
				'user_email'    =>   $email,
				'user_pass'     =>   $password,
				'first_name'    =>   $first_name,
				'last_name'     =>   $last_name,
				
			);
			$user = wp_insert_user( $userdata );
			$this->pd_new_user_notification($user, $password);
			
			wp_update_user( array ('ID' => $user, 'role' => 'pduser') ) ;
            



	?>
		<script type="text/javascript">
		jQuery(document).ready(function($){
		$('#pdfname').val('');
		$('#pdlname').val('');
		$('#pdemail').val('');
		$('#pdusername').val('');
		$('#pdpassword').val('');

		})
		</script>
		<?php
			$registration_success_text = pd_ot_get_option('sbd_lan_registration_successful') != '' ? pd_ot_get_option('sbd_lan_registration_successful') : __('Registration Successful!','qc-pd');
			$goto_login_page_text = pd_ot_get_option('sbd_lan_go_to_login') != '' ? pd_ot_get_option('sbd_lan_go_to_login') : __('Go to login page','qc-pd');
			$user_info_submitted_text = pd_ot_get_option('sbd_lan_user_info_submit_wait_approval') != '' ? pd_ot_get_option('sbd_lan_user_info_submit_wait_approval') : __('User Information submitted! Waiting for approval.','qc-pd');

            if(pd_ot_get_option('pd_enable_user_approval')=='off'){
	            echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;">'.$user_info_submitted_text.'</div>.';
            }else{
	            echo '<div style="color: green;border: 1px solid green;margin: 2px;padding: 2px;text-align: center;margin-bottom: 8px;">'.$registration_success_text.' <a href="' . qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sbd_login_url','') . '">'.$goto_login_page_text.'</a></div>.';
            }

        }
	}
	
	public function registration_form( $username, $password, $email, $first_name, $last_name ) {

		session_start();
		if(isset($_SESSION['sbd_captcha'])){
			unset($_SESSION['sbd_captcha']);
		}

        $_SESSION['sbd_captcha'] = pd_simple_php_captcha();

		echo '
		<style>
		div {
			margin-bottom:2px;
		}
		 
		input{
			margin-bottom:4px;
		}
		</style>
		';
	 	
	 	if(pd_ot_get_option('sbd_lan_already_account')!=''){
			$srcplaceholder = pd_ot_get_option('sbd_lan_already_account');
		}else{
			$srcplaceholder = __('Already Have an Account?', 'qc-pd');
		}
			
	 	$sbd_lan_first_name = pd_ot_get_option('sbd_lan_first_name') != '' ? pd_ot_get_option('sbd_lan_first_name') : __('First Name', 'qc-pd');
	 	$sbd_lan_last_name = pd_ot_get_option('sbd_lan_last_name') != '' ? pd_ot_get_option('sbd_lan_last_name') : __('Last Name', 'qc-pd');
	 	$sbd_lan_only_username = pd_ot_get_option('sbd_lan_only_username') != '' ? pd_ot_get_option('sbd_lan_only_username') : __('Username', 'qc-pd');
	 	$create_account_text = pd_ot_get_option('sbd_lan_create_account') != '' ? pd_ot_get_option('sbd_lan_create_account') : __('Create Account', 'qc-pd');
	 	$sbd_lan_only_password = pd_ot_get_option('sbd_lan_only_password') != '' ? pd_ot_get_option('sbd_lan_only_password') : __('Password', 'qc-pd');
	 	$sbd_lan_email = pd_ot_get_option('sbd_lan_email') != '' ? pd_ot_get_option('sbd_lan_email') : __('Email', 'qc-pd');
	 	$sbd_lan_code = pd_ot_get_option('sbd_lan_code') != '' ? pd_ot_get_option('sbd_lan_code') : __('Code', 'qc-pd');
	 	$sbd_lan_register = pd_ot_get_option('sbd_lan_register') != '' ? pd_ot_get_option('sbd_lan_register') : __('Register', 'qc-pd');

	 	echo ' <div style="margin: 10px auto;max-width: 500px;text-align:right"><a href="'.qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sbd_login_url','').'">'.$srcplaceholder.'</a></div>
			<div class="cleanlogin-container">	<form autocomplete="off" class="cleanlogin-form" action="' . $_SERVER['REQUEST_URI'] . '" method="post" id="registration_form_sld">';
		echo '
		<div class="cleanlogin-container">	<form autocomplete="off" class="cleanlogin-form" action="' . $_SERVER['REQUEST_URI'] . '" method="post" id="registration_form_pd">
		<h2>'. $create_account_text .'</h2>
		<fieldset><div class="cleanlogin-field">
		<input class="cleanlogin-field-username" type="text" name="fname" id="pdfname" placeholder="'. $sbd_lan_first_name .' *" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '" required>
		<i class="fa fa-user"></i>
		</div></fieldset>
		 
		<fieldset><div class="cleanlogin-field">
	   
		<input class="cleanlogin-field-username" placeholder="'. $sbd_lan_last_name .' *" type="text" name="lname" id="pdlname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '" required>
		<i class="fa fa-user"></i>
		</div></fieldset>


		<fieldset><div class="cleanlogin-field">
		<input class="cleanlogin-field-username" placeholder="'. $sbd_lan_only_username .' *" type="text" name="username" id="pdusername" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '" required>
		<i class="fa fa-user"></i>
		</div></fieldset>
		
		<fieldset><div class="cleanlogin-field"><input type="password" style="display: none;" />
		<input class="cleanlogin-field-username" placeholder="'. $sbd_lan_only_password .' *" type="password" name="password" id="pdpassword" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '" required>
		<i class="fa fa-lock"></i>
		</div></fieldset>
		
		<fieldset><div class="cleanlogin-field">
		<input class="cleanlogin-field-username" placeholder="'. $sbd_lan_email .' *" type="email" name="email" id="pdemail" value="' . ( isset( $_POST['email']) ? $email : null ) . '" required><input type="text" style="display: none;" />
		<i class="fa fa-envelope"></i>
		</div></fieldset>
		';

		if(pd_ot_get_option( 'pd_enable_captcha')=='on'){
			if( pd_ot_get_option( 'pd_enable_recaptcha')=='off' ){
	            echo '<fieldset><div class="cleanlogin-field">
	            <img src="'.($_SESSION['sbd_captcha']['image_src']).'" alt="Captcha Code" id="pd_captcha_image_register" />
	            <img style="width: 24px;cursor:pointer;" id="captcha_reload" src="'.QCSBD_IMG_URL.'/captcha_reload.png" />
	            <input class="cleanlogin-field-username" placeholder="'. $sbd_lan_code .'" type="text" name="ccode" id="pdcode_register" value="" required>
				<input type="hidden" name="pdccode" id="pdccode_register" value="'.($_SESSION['sbd_captcha']['sbd_code']).'" />
	            </div></fieldset>
	             ';
	         }

	        if( pd_ot_get_option( 'pd_enable_recaptcha')=='on' ){
				echo '<fieldset><div class="cleanlogin-field"><div class="g-recaptcha" data-sitekey="'.pd_ot_get_option( 'pd_recaptcha_site_key').'"></div></div></fieldset>';
			}
        }

		$gdrp_text = pd_ot_get_option('sbd_lan_gdrp')!=''?pd_ot_get_option('sbd_lan_gdrp'):'I accept the <a href="#">Terms of Service</a> and have read the <a href="#">Services Privacy Policy</a>';
		
		echo '<fieldset><div class="cleanlogin-field">
		<input class="cleanlogin-field-username" type="checkbox" name="sbd_policy_accept" id="sbd_policy" required /> '.$gdrp_text.'		
		</div></fieldset>';
		
		
		echo '<fieldset style="    text-align: center; padding: 0px !important;"><div style="margin-top: 16px;margin-bottom: 0px;" class="cleanlogin-field">
		<input type="hidden" name="pdregistration" value="pd"/>
		<input type="submit" class="submit_registration" name="submit" value="'. $sbd_lan_register .'"/>
		</div></fieldset>
		
		</form></div>
		<script type="text/javascript">
			jQuery("document").ready(function(){
				setTimeout(function(){
					jQuery(\'#captcha_reload\').click();
				},1000)
			})
		</script>
		';
	$customCss = pd_ot_get_option( 'pd_custom_style' );
	if( trim($customCss) != "" ) :
?>
	<style>
		<?php echo trim($customCss); ?>
	</style>

<?php endif;
	}
	
}

function sbd_registration_page() {
	return pd_custom_registration::instance();
}
sbd_registration_page();

 