<?php 

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

	public static function instance() {
		if ( !isset( self::$instance ) ) {
			self::$instance = new sbd_custom_registration_claim();
		}
		return self::$instance;
	}
	private function __construct()
	{
		if( !is_admin() ){
			if(!session_id() && !headers_sent() ){
				session_start();
			}
		}

		add_shortcode( 'sbd_claim_listing', array($this,'custom_registration_shortcode') );
		add_action( 'init', array($this,'claim_listing_form_handle') );
		add_role( 'pduser', __( 'SBD User' ), array( ) );
	}
	
	public function claim_listing_form_handle(){
		//session_start();
		if ( isset($_POST['submit'] ) && isset($_POST['sbdclaimlisting']) ) {
			
			$this->registration_validation(
				$_POST['username'],
				$_POST['password'],
				$_POST['email'],
				$_POST['fname'],
				$_POST['lname']
				
			);
			 
			// sanitize user form input
			global $wpdb, $reg_errors, $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'] );
		  
	 
			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 );
				wp_update_user( array ('ID' => $user, 'role' => 'pduser') ) ;
				$this->sld_new_user_notification($user, $password);
				
				
				// Inserting information
				$date = date('Y-m-d H:i:s');
				$table = $wpdb->prefix.'sbd_claim_purchase';
				$wpdb->insert(
				    $table,
				    array(
					    'date'  => $date,
					    'user_id'   => $user,
					    'listid'   => $_POST['claim_list'],
					    'item'   => $_POST['claim_item'],
					    'status'   => 'pending',
					    
				    )
			    );
				$this->pd_claim_notification($user, $_POST['claim_item']);
				
				$dashboard = qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sbd_dashboard_url','');
				
				$dashboard = esc_url( add_query_arg( 'action', 'claim', $dashboard ) );
				
				$creds = array();
				$creds['user_login'] = $username;
				$creds['user_password'] = $password;
				$creds['remember'] = true;

				$user = wp_signon( $creds, false );
				wp_safe_redirect( $dashboard );
				
				die();
				


			}
	 
	 
		}
	}
	public function pd_claim_notification( $user_id) {
        $user = new WP_User($user_id);

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

        $message  = sprintf(__('A item has been claimed to your list %s. Please go to Simple Business Directory > Claimed Listing to view this claimed item.'), get_option('blogname')) . "\r\n\r\n";
        $message .= sprintf(__('Item Claimed By : %s'), $user_login) . "\r\n\r\n";

        $sbd_lan_a_link_has_been_claimed = pd_ot_get_option('sbd_lan_a_link_has_been_claimed') != '' ? pd_ot_get_option('sbd_lan_a_link_has_been_claimed') : __('A item has been claimed from your list!', 'qc-pd');

        @wp_mail(pd_ot_get_option('pd_admin_email'), sprintf(__('[%s] %s'), get_option('blogname'), $sbd_lan_a_link_has_been_claimed), $message);

    }
	public function custom_registration_shortcode() {

		ob_start();
		$this->custom_registration_function();
		return ob_get_clean();
	}
	
	public function custom_registration_function() {
		
	 
		$this->registration_form(
			@$username,
			@$password,
			@$email,
			@$first_name,
			@$last_name
		  
			
			);
	}

	public function sld_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';

		$new_user_registration = pd_ot_get_option('sbd_lan_new_user_registration') != '' ? pd_ot_get_option('sbd_lan_new_user_registration') : 'New User Registration';

		$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(__('%s %s:','qc-pd'), $title_text, get_option('blogname')) . "\r\n\r\n";
		$message .= sprintf(__('%s: %s','qc-pd'), $username_text, $user_login) . "\r\n\r\n";
		$message .= sprintf(__('%s: %s','qc-pd'), $mail_text, $user_email) . "\r\n";
		if(pd_ot_get_option('sbd_admin_email')!=''){
			@wp_mail(pd_ot_get_option('sbd_admin_email'), sprintf(__('[%s] %s','qc-pd'), get_option('blogname'), $new_user_registration), $message);
		}
		

		if ( empty($plaintext_pass) )
			return;

		$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( 'sld_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('sld_admin_email')!=''){
			$message .= sprintf(__('If you have any stuck, please contact webmaster at %s.'), pd_ot_get_option('sld_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'])){
		    $reg_errors->add('captcha_invalid', __('Captcha does not match!','qc-pd'));
        }

		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 registration_form( $username, $password, $email, $first_name, $last_name ) {
		global $reg_errors;
		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>';
				 
			}
		 
		}

		if(!is_user_logged_in()){
			
			wp_enqueue_script( 'qcpd-custom-script');

			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');
			$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');
		 
			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">
			
			<h2>'. __( 'Account Info', 'qc-pd' ).'</h2>
			<fieldset><div class="cleanlogin-field">
			<input class="cleanlogin-field-username" type="text" name="fname" id="sldfname" 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="sldlname" 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="sldusername" 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="sldpassword" 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="sldemail" value="' . ( isset( $_POST['email']) ? $email : null ) . '" required><input type="text" style="display: none;" />
			<i class="fa fa-envelope"></i>
			</div></fieldset>
			';
			echo '<h2>'. __( 'List Info', 'qc-pd' ).'</h2>';
			?>
			<fieldset><div class="cleanlogin-field">
			<label><?php echo __('Select List Name','qc-pd'); ?></label>
			<select style="" id="sld_claim_list" name="claim_list" required>
				<option value="">None</option>
				<?php 
				$list_args_total = array(
					'post_type' => 'pd',
					'posts_per_page' => -1,
				);
				$list_query = new WP_Query( $list_args_total );
				while ( $list_query->have_posts() )
				{
					$list_query->the_post();
					echo '<option value="'.get_the_ID().'">'.get_the_title().'</option>';
				}
				?>
			</select>
			</div></fieldset>
			 
			<fieldset><div class="cleanlogin-field">
		   <label><?php echo __('Select Item Name','qc-pd'); ?></label>
			<select style="" id="sld_list_item" name="claim_item" required>
				<option value="">None</option>
			</select>
			
			</div></fieldset>
			
			
			
			<?php
			if(pd_ot_get_option( 'pd_enable_captcha')=='on'){
				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="'. __( 'Code', 'qc-pd' ).'" type="text" name="ccode" id="sldcode" value="" required>
				<input type="hidden" name="pdccode" id="pdccode_register" value="'.($_SESSION['sbd_captcha']['sbd_code']).'" />
				</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="sbdclaimlisting" value="sld"/>
			<input type="submit" class="submit_registration" name="submit" value="'. __( 'Claim List', 'qc-pd' ).'"/>
			</div></fieldset>
			
			</form></div>
			<script type="text/javascript">
				jQuery("document").ready(function(){
					setTimeout(function(){
						jQuery(\'#captcha_reload\').click();
					},1000)
				})
			</script>
			';
		}else{
			//$dashboard = qc_sbd_login_page()->pdcustom_login_get_translated_option_page( 'sbd_dashboard_url','');
			//echo 'You are already logged in. <a href="'.$dashboard.'?action=claim'.'">Click here</a> to go to claim listing page';
			$claim_page = qc_sbd_login_page()->pdcustom_login_get_translated_option_page('sbd_dashboard_url').'?action=claim';
			if( $claim_page != '' ) {
		?>
				You are already logged in.<a href='<?php echo $claim_page; ?>'>Click here</a> to go to claim listing page
		<?php
			}else{
			?>
				You are already logged in.<a href='/dashboard?action=claim'>Click here</a> to go to claim listing page
			<?php
			}
		}
	}
	
}

function sbd_custom_registration_claim() {
	return sbd_custom_registration_claim::instance();
}
sbd_custom_registration_claim();
