<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

class fbbttmData
{
	public function getCurrencySymbol()
	{
		$return = FBBTTM_CURRENCY_SYMBOL;
		return $return;
	}

	public function fbbttm_get_single_commonquery($fbbttm_setting_name=null)
	{

		global $wpdb;
	
		$fbbttm_table_setting = FBBTTM_TB_SETTING;

		$fbbttm_result ='';


		/*$fbbttm_result = $wpdb->get_results($wpdb->prepare("SELECT * FROM ". FBBTTM_TB_SETTING." WHERE `fbbttm_setting_name` = %s 	ORDER BY fbbttm_setting_id DESC LIMIT 40", $fbbttm_setting_name), ARRAY_A);*/

		$query = $wpdb->prepare(
			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	    "SELECT * FROM {$fbbttm_table_setting}  where fbbttm_setting_name = %s ORDER BY fbbttm_setting_id DESC LIMIT 40",$fbbttm_setting_name  
	    );

		
		 if(!empty($fbbttm_result))
			{
				return $fbbttm_result;
			}
		return $fbbttm_result;
	}

	public function fbbttm_get_tablename($tablename=null){

		global $wpdb;

			if(!empty($tablename)){
				$tablename = $wpdb->prefix . $tablename;
				return $tablename;
			}	
			return;

	}

	public function fbbttm_get_packagelist($fbbttm_foodid){
		global $wpdb;

		$tablename = FBBTTM_TB_PACKAGELIST;

		$fbbttm_result ='';
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching 
		$fbbttm_result = $wpdb->get_results($wpdb->prepare(
			// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		    "SELECT * FROM $tablename WHERE `fbbttm_f_id` = %s ORDER BY fbbttm_pack_id DESC 
		    LIMIT 30", $fbbttm_foodid ), OBJECT);

	
		if(!empty($fbbttm_result))
		 {
			return $fbbttm_result;
		 }
		
		return $fbbttm_result;

	}

	/*get price information like discout orignal foodprice save upto price*/

	public function fbbttm_get_packinfo($packid=null){
		global $wpdb;
		
		$tablename = FBBTTM_TB_PACKAGELIST;

		$returnresult =array();
		
	
		$pack_status =1;

		$fbbttm_result = $wpdb->get_results($wpdb->prepare("SELECT * FROM $tablename WHERE `fbbttm_pack_id` = %d AND `fbbttm_pack_status` = %d ORDER BY `fbbttm_pack_id`",
		    $packid,
		    $pack_status
		), OBJECT);

		

		$pricesysmbol =  $this->getCurrencySymbol();

		 if(!empty($fbbttm_result)){
		 	 $packname = $fbbttm_result['0']->fbbttm_package_name;
			 $itemprice = $fbbttm_result['0']->fbbttm_fitem_price;
			 $specialprice = $fbbttm_result['0']->fbbttm_special_price;
			 $description = $fbbttm_result['0']->fbbttm_package_description;

			 $mainitemprice = number_format((float)$itemprice, 2, '.', '');
			 $specialprice = number_format((float)$specialprice, 2, '.', '');
			 $packprice = $fbbttm_result['0']->fbbttm_package_price;
			 $fooditemid = 	$fbbttm_result['0']->fbbttm_f_id;

			 $returnresult['pack_name'] = $packname;
			 $returnresult['pack_id'] = $packid;
			 $returnresult['fooditemid'] = $fooditemid;
			 $returnresult['packdescription'] = $description;

			 $returnresult['fooditemprice'] = $this->fbbttm_get_price_with_currency($mainitemprice);
			 $returnresult['fooditemprice_without'] = $mainitemprice;
			 $returnresult['packageday'] =  $fbbttm_result['0']->fbbttm_total_day;
			 $returnresult['pack_specialprice'] = $specialprice;

			 $returnresult['pack_specialprice_withsymbol'] = $this->fbbttm_get_price_with_currency($specialprice);
			 $returnresult['pack_price'] = $this->fbbttm_get_price_with_currency($packprice);
			 $returnresult['pack_price_withoutsymbol'] = $packprice;
			 $returnresult['savemoney'] = '';
			 $returnresult['savemoney_without'] = '';

			 if($specialprice > '0')
			 {
			 	$pricewithspecial  =  $returnresult['packageday'] * $returnresult['pack_specialprice'];
			 	$orignalprice  =  $returnresult['packageday'] * $mainitemprice;
			 	$saveprice = $orignalprice - $pricewithspecial;
			 	$returnresult['savemoney'] = $this->fbbttm_get_price_with_currency($saveprice);
			 	$returnresult['savemoney_without'] = $saveprice;
			 }
		 }
		 return $returnresult;
	}

	public function fbbttm_get_price_with_currency($price){
		$return = '';
		$getCurrencySymbol = $this->getCurrencySymbol();

		if(!empty($price))
		{
		   $return = $getCurrencySymbol.''.$price;
		}
		return $return;
	 }

	/**
	 *  Fooditems description content
	 */

	public function fbbttm_fooditems_description( $post_id='' ){
		$return = '';
		
		// processing content
		$content = get_the_content( null, false );
		$content = apply_filters( 'the_content', $content );
		$content = str_replace( ']]>', ']]&gt;', $content );
		
		// preparing final output
		$return = '<div class="fbbttm-fooditems-description">'. '' . $content . '</div><!-- .fbbttm-fooditems-description -->';
		
		return $return;
	}

	/**
	 *  Common table insert query
	 */

	 public function fbbttm_common_insert($tablename, $data=null){

	 	global $wpdb;

	 	$wpdb->insert($tablename ,  $data );

	 	return $wpdb->insert_id;
	
	 }
	 public function fbbttm_common_multiple_insert($tablename, $dataarray=null)
	 {
	 	global $wpdb;
	 	foreach($dataarray as $data){
	 		$wpdb->insert($tablename ,  $data );
	 	}
	 	return $wpdb->insert_id;
	 }

 	public function fbbttm_common_updatetable($tablename, $dataarray, $wherefield, $wherefieldvalue, $fbbttm_datefield) {
    global $wpdb;

		    // Validate table and field names to prevent SQL injection
		    if (empty($tablename) || empty($dataarray) || empty($wherefield) || empty($fbbttm_datefield)) {
		        return false; // Return false if mandatory parameters are missing
		    }

		    // Escape table and field names
		    $tablename = esc_sql($tablename);
		    $wherefield = esc_sql($wherefield);
		    $fbbttm_datefield = esc_sql($fbbttm_datefield);

		    // Prepare SET clause
		    $set_clauses = [];
		    $values = [];
		    foreach ($dataarray as $key => $value) {
		        $key = esc_sql($key); // Escape the column name
		        $set_clauses[] = "`$key` = %s";
		        $values[] = $value !== null ? $value : ''; // Ensure non-null value
		    }

		    // Add the date field to the SET clause
		    $set_clauses[] = "`$fbbttm_datefield` = %s";
		    $values[] = gmdate('Y-m-d H:i:s');

		    // Prepare WHERE clause
		    $values[] = $wherefieldvalue;

		   
		     // Construct the final query
		    $query = sprintf(
		        "UPDATE `%s` SET %s WHERE `%s` = %%s",
		        $tablename,
		        implode(', ', $set_clauses),
		        $wherefield
		    );

		    // Execute the query with prepared statement
		    $updateinfo = $wpdb->query($wpdb->prepare(
			// phpcs:disable WordPress.DB.PreparedSQL.NotPrepared
		    	$query, ...$values));

		    return $updateinfo;
}


	 public function fbbttm_get_filecontent($path=null)
	 {
	 	global $wpdb;
	 	ob_start();
		include_once $path;
	 	$return = ob_get_contents();
		ob_end_clean();
		return $return;
	 }

	 public function fbbttm_get_user_info($id){
		
		return get_userdata($id);

	 }

	 /**
	  * function for common query table for single table and it field
	  * tablename, fieldname and fieldvalue
	 */

	public function fbbttm_comman_single_tableinfo($tablename = null, $fieldname = null, $fieldvalue = null, $orderbyfield = null, $orderby = 'ASC') {

    		global $wpdb;

		    // Validate table and field names to avoid SQL injection
		    if (empty($tablename) || empty($fieldname)) {
		        return []; // Return an empty array if mandatory parameters are missing
		    }

		    // Escape table and field names
		    $tablename = esc_sql($tablename);
		    
		    // Prepare WHERE clause if fieldname and fieldvalue are provided
		    $whereclause = '';
		    $values = [];
		    if (!empty($fieldvalue)) {
		        $whereclause = "WHERE `$fieldname` = %s";
       			$values[] = $fieldvalue;
		    }

		    // Prepare ORDER BY clause
		    $orderbyfield = !empty($orderbyfield) ? esc_sql($orderbyfield) : esc_sql($fieldname);
		    $orderby = strtoupper($orderby) === 'DESC' ? 'DESC' : 'ASC'; // Allow only ASC or DESC
		    $orderbyclause = "ORDER BY `$orderbyfield` $orderby";

		    // Construct the final query
    		$query = "SELECT * FROM `$tablename` $whereclause $orderbyclause";
		    // Construct the final query
		    if ($values) {
		        $query = $wpdb->prepare($query, ...$values);
		    }

		    $fbbttm_result = $wpdb->get_results($query, OBJECT);

		    return $fbbttm_result;

		}

	 /**
	  *  function for fbbttm_create_option_html
	  */

	  public function fbbttm_create_option_html($optiondata=null,$sid=null) 
	  {	

	  	$optionhtml = '';

	  	  if(!empty($optiondata))
		  	{

		  		foreach($optiondata as $state):
		  			$selected ='';
		  			if(!empty($sid)){
		  				$selected =  ($sid == $state->id)?'selected="selected"':'';
		  			}

		  			$optionhtml .='<option '.esc_html($selected).'  data-attr='.esc_html($state->country_id).' value='.esc_html($state->id).'>'.esc_html($state->name).'</option>';

		  		endforeach;	
		    }

		    return $optionhtml;

	  }



	  public function fbbttm_form_data_validatesubmit($formdata=null, $tablename=null)
	  {	
	  
	  	$message = array();

	  	$tablename = FBBTTM_DELIVERY_ADDRESS;

	  	$flagset = 0;
	  	$error_msg = array();

	  	$fbbttmfname = $fbbttmlname = $fbbttmemail = $fbbttmcountry = $fbbttmstate = $fbbttmaddress = $fbbttmcity = $fbbttmpincode = $fbbttmphone = $userid = $inputuserid = $noncename = $addid = '';

	  	if(isset($_POST['fbbttm-fname'])){
	  		$fbbttmfname   = sanitize_text_field(wp_unslash($_POST['fbbttm-fname']));
	  	}
	  	if(isset($_POST['fbbttm-lname'])){
	  		$fbbttmlname   = sanitize_text_field(wp_unslash($_POST['fbbttm-lname']));
	  	}
		if(isset($_POST['fbbttm-email'])){
	  		$fbbttmemail   = sanitize_text_field(wp_unslash($_POST['fbbttm-email']));
	  	}
	  	if(isset($_POST['fbbttm-country'])){
	  		$fbbttmcountry = sanitize_text_field(wp_unslash($_POST['fbbttm-country']));
	  	}
	  	if(isset($_POST['fbbttm-state'])){
	  		$fbbttmstate = sanitize_text_field(wp_unslash($_POST['fbbttm-state']));
	  	}
	  	if(isset($_POST['fbbttm-street-address-1'])){
	  		$fbbttmaddress = sanitize_text_field(wp_unslash($_POST['fbbttm-street-address-1']));
	    }
	  	//$fbbaddress2 = sanitize_text_field($formdata['fbbttm-street-address-2']);
	  	if(isset($_POST['fbbttm-city'])){
	  		$fbbttmcity = sanitize_text_field(wp_unslash($_POST['fbbttm-city']));
	  	}
	  	if(isset($_POST['fbbttm-pincode'])){
	  		$fbbttmpincode = sanitize_text_field(wp_unslash($_POST['fbbttm-pincode']));
	    }
	    if(isset($_POST['fbbttm-phone'])){
	  		$fbbttmphone = sanitize_text_field(wp_unslash($_POST['fbbttm-phone']));
	    }
	    if(isset($_POST['fbbttm-userid'])){
	  		$userid = sanitize_text_field(wp_unslash($_POST['fbbttm-userid']));
	  	}
	  	if(isset($_POST['fbbttm-userid'])){
	  		$inputuserid = sanitize_text_field(wp_unslash($_POST['fbbttm-userid']));
	  	}
	  	if(isset($_POST['fbbttm_meta_box_noncename'])){	
	  		$noncename = sanitize_text_field(wp_unslash($_POST['fbbttm_meta_box_noncename']));
	  	}
	  	if(isset($_POST['fbbttm-useraddressid'])){	
	  		$addid = sanitize_text_field(wp_unslash($_POST['fbbttm-useraddressid']));
	  	}

		if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {
			  $error_msg['php-error'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
		 }

	  	if(empty($fbbttmfname)){
	  		$error_msg['fbbttmfname'] = esc_html__('Please enter your first name','foodboxbooker'); 
	  	}

	  	if(!empty($fbbttmfname)){
	  		if (!preg_match("/^[a-zA-Z-' ]*$/",$fbbttmfname)) {
				  $error_msg['fbbttmfname'] = esc_html__('Only letters and white space allowed','foodboxbooker'); 
			}
	  	}

	  	if(empty($fbbttmlname)){
	  		$error_msg['fbbttmlname'] = esc_html__('Please enter your last name','foodboxbooker'); 
	  	}

	  	if(!empty($fbbttmlname)){

	  		if (!preg_match("/^[a-zA-Z-' ]*$/",$fbbttmlname)) {
				  $error_msg['fbbttmlname'] = esc_html__('Only letters and white space allowed','foodboxbooker'); 
			}
	  		
	  	}

	  	if(empty($fbbttmemail)){

	  		$error_msg['fbbttmemail'] = esc_html__('Please enter your email','foodboxbooker'); 
	  	}

	  	if(!empty($fbbttmemail))
	  	{

			if (!filter_var($fbbttmemail, FILTER_VALIDATE_EMAIL)) {
			
			  $error_msg['fbbttmemail'] = esc_html__('Please enter valid email address','foodboxbooker'); 

			}

			else
			{


				$emaildata = $this->fbbttm_check_user_exist_byemail($fbbttmemail);

				if($emaildata=='1'){

					$error_msg['fbbttmemail'] = esc_html__('User is already there with this email address','foodboxbooker'); 

				}

			}

	  		
	  	}

	  	if(empty($fbbttmcountry)){

	  		$error_msg['fbbttmcountry'] = esc_html__('Please select your country','foodboxbooker'); 
	  	}

	  	if(empty($fbbttmstate)){

	  		$error_msg['fbbttmcountry'] = esc_html__('Please select your state','foodboxbooker'); 
	  	}

	  	if(empty($fbbttmaddress)){

	  		$error_msg['fbbttmstreet1'] = esc_html__('Please enter your address','foodboxbooker'); 
	  	}

	  	if(empty($fbbttmcity)){

	  		$error_msg['fbbttmcity'] = esc_html__('Please enter your city','foodboxbooker'); 
	  	}

	  	if(empty($fbbttmpincode)){

	  		$error_msg['fbbttmpincode'] = esc_html__('Please enter your pincode','foodboxbooker'); 
	  	}

	  	if(empty($fbbttmphone)){

	  		$error_msg['fbbttmphone'] = esc_html__('Please enter your phone number','foodboxbooker'); 
	  	}

	  	if(!empty($fbbttmphone)){

	  		 if (!preg_match('/^[0-9]{10}+$/', $fbbttmphone)) {
	  		 	$error_msg['fbbttmphone'] = esc_html__('Please enter your valid phone number','foodboxbooker'); 
	  		 }
	
	  	}
	  
	 	$message['error_message'] = $error_msg;
	  	//print_r($error_msg);

	  	$update = 0;
	  	$insert = 0;

	  	if(empty($error_msg)){

	  	  if(!empty($userid)){	
	  		 $deliveryaddress = $this->fbbttm_comman_single_tableinfo($tablename,'fbbttm_user_id',$userid);
	  		 	if(!empty($deliveryaddress))
				    {
				        	$update = 1;	
				    }
				else{
				  			$insert = 1;
				    } 
		  	}
		  	else
		  	{
	  			$user = get_user_by('email', $fbbttmemail);
	  				if ($user) {

						 $userid = $user->ID;
						 $deliveryaddress = $this->fbbttm_comman_single_tableinfo($tablename,'fbbttm_user_id',$userid);
						 if(!empty($deliveryaddress))
						    {
							    	$update = 1;		
							}
					  	else{
					  			$insert = 1;
					  		}  
					   } 
					   else {
							$insert = 1;
							$userid = $this->fbbttm_add_newuser($fbbttmemail,'','','checkout',$noncename);
						    // Handle the case where no user is found for the specified email.
						}	  			
			 }


		  		if($insert=='1')
		  		{
  					$data = array(
				  			'fbbttm_user_id'=>$userid,
				  			'fbbttm_first_name'=>$fbbttmfname,
				  			'fbbttm_last_name'=>$fbbttmlname,
				  			'fbbttm_user_email'=>$fbbttmemail,
				  			'fbbttm_user_country'=>$fbbttmcountry,
				  			'fbbttm_user_state'=>$fbbttmstate,
				  			'fbbttm_street_1'=>$fbbttmaddress,
				  			
				  			'fbbttm_city'=>$fbbttmcity,
				  			'fbbttm_pincode'=>$fbbttmpincode,
				  			'fbbttm_phone'=>$fbbttmphone,
				  		);

					$deliveryid = $this->fbbttm_common_insert($tablename,$data);

					$message['success']	=esc_html__('Delivery address insert successfully','foodboxbooker');	
					$message['userid'] = $userid;
					$message['deliveryid'] = $deliveryid;
					
					if(!empty($inputuserid))
					{
						$message['useravail'] = '1';
					}
					else
					{
						$message['useravail'] = '';
					}



	  		}
	  		else if($update == '1')
	  		{	

	  				$data = array(
						  			'fbbttm_first_name'=>$fbbttmfname,
						  			'fbbttm_last_name'=>$fbbttmlname,
						  			'fbbttm_user_email'=>$fbbttmemail,
						  			'fbbttm_user_country'=>$fbbttmcountry,
						  			'fbbttm_user_state'=>$fbbttmstate,
						  			'fbbttm_street_1'=>$fbbttmaddress,
						  			'fbbttm_city'=>$fbbttmcity,
						  			'fbbttm_pincode'=>$fbbttmpincode,
						  			'fbbttm_phone'=>$fbbttmphone,
						  	);

	  				$this->fbbttm_common_updatetable($tablename,$data,'fbbttm_user_id',$userid,'fbbttm_address_update');

	  				$message['success']	=esc_html__('Delivery address update successfully','foodboxbooker');	
	  				$message['userid'] = $userid;
					$message['deliveryid'] = $addid;
					$message['useravail'] = '1';
				
	  		}
	  	}
	  	return $message;
	  }

	  public function fbbttm_add_newuser($fbbttmemail=null,$password=null,$username=null,$page=null,$noncename=null){

	  		global $fbbttm_emailobj;
	  		$user_id = username_exists( $fbbttmemail );

	  		if(empty($user_id) && email_exists($fbbttmemail) == false )
	  		{	

	  			 $random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
	  			 $random_password  = (!empty($password)) ? $password : $random_password;

	  			 	if(empty($username)){
	  			 		$emaildata =  explode("@",$fbbttmemail);
	  					$username = $emaildata[0];
	  				}

				 	$fbbttmusername = (!empty($username)) ? $username : $fbbttmemail;

	  			 	$user_id = wp_create_user($fbbttmusername, $random_password, $fbbttmemail );

	  			 
	  				$tokenid = $this->fbbttm_get_user_cookie_data(); 
					

					$tablename = FBBTTM_TB_FOODBOOKING_CART;

					$data = array(
						'fbbttm_user_id'=>$user_id 
					);
					
					$cartdata = $this->fbbttm_comman_single_tableinfo($tablename,'fbbttm_token_id',$tokenid);


					if(!empty($cartdata)){
						//$tokenid = "'$tokenid'";
						$this->fbbttm_common_updatetable($tablename,$data,'fbbttm_token_id',$tokenid,'fbbttm_cartupdate_date');
					}


					if(!empty($page)){
		  				$userdata = array();
		  				$userdata['fbbttm-username'] =  $fbbttmusername;
			   			$userdata['fbbttm-password'] = $random_password;
			   			$userdata['fbbttm_meta_box_noncename'] = $noncename;
			   			$this->fbbttm_user_login($userdata);
		   			}

					$emailtemp = $fbbttm_emailobj->fbbttm_new_account_createmail($fbbttmusername,$fbbttmemail,$random_password);

	  		}

	  		return $user_id;
	  }



	  /**
	   * get user by email
	   */
	  public function fbbttm_check_user_exist_byemail($fbbttmemail=null)
	  {

	  		//$user_id = username_exists( $fbbttmemail );

	  		$user_id = email_exists($fbbttmemail);

	  		

	  		$userreturn  = 0;

	  			if(!empty($user_id)){

	  				if ( is_user_logged_in() ) 
					{
						$currentuserid = get_current_user_id();
						$userreturn =	($currentuserid == $user_id) ? '0' : '1';					
					}
					else
					{
						$userreturn = '1';
					}

				}

		 	return $userreturn;		
					
	  }

	  /**
	   * Update user details
	   */ 

	  public function fbbttm_set_user_data($searcharray=null){

	  		global $wpdb;

	  		$message = array();
	  	
		  	$error_msg  = array();

		  	$first_name = $last_name  = $email = $userid = $password_current = $password_1 =$password_2 ='';

		  	if(isset($_POST['fbbttm-fname'])){
		  		$first_name = sanitize_text_field(wp_unslash($_POST['fbbttm-fname']));
		  	}
		  	if(isset($_POST['fbbttm-lname'])){
		  		$last_name  = sanitize_text_field(wp_unslash($_POST['fbbttm-lname']));
		  	}
		  	if(isset($_POST['fbbttm-email'])){
		  		$email   	= sanitize_text_field(wp_unslash($_POST['fbbttm-email']));
		  	}
		  	if(isset($_POST['fbbttm-userid'])){
		  		$userid 	= sanitize_text_field(wp_unslash($_POST['fbbttm-userid']));
		 	 }

		 	if(isset($_POST['password_current'])){
		  		$password_current = sanitize_text_field(wp_unslash($_POST['password_current']));
		  	}
		  	if(isset($_POST['password_1'])){
		  		$password_1 = sanitize_text_field(wp_unslash($_POST['password_1']));
		  	}
		  	if(isset($_POST['password_2'])){
		  		$password_2 = sanitize_text_field(wp_unslash($_POST['password_2']));
		  	}

		  	$emailinfo = $this->fbbttm_check_user_exist_byemail($email);
		  	$userdata = $this->fbbttm_get_user_info($userid);

		  	$orignalpass = $userdata->user_pass;
		  	$noncename = '';
		  	if(isset($_POST['fbbttm_meta_box_noncename'])){
		  	$noncename = sanitize_text_field(wp_unslash($_POST['fbbttm_meta_box_noncename']));
			  }

			if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {
				  $error_msg['php-error'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
						 
			 }

		  	if(empty($first_name)){
		  		$error_msg['fbbttmacountfname'] = esc_html__('Please enter your first name','foodboxbooker'); 
		  	}
		  	if(!empty($fbbttmfname)){
		  		if (!preg_match("/^[a-zA-Z-' ]*$/",$first_name)) {
					  $error_msg['fbbttmacountfname'] = esc_html__('Only letters and white space allowed','foodboxbooker'); 
				}
		  	}

		  	if(empty($last_name)){
		  		$error_msg['fbbttmacountlname'] = esc_html__('Please enter your last name','foodboxbooker'); 
		  	}
		  	if(!empty($last_name)){
		  		if (!preg_match("/^[a-zA-Z-' ]*$/",$last_name)) {
					  $error_msg['fbbttmacountlname'] = esc_html__('Only letters and white space allowed','foodboxbooker'); 
				}
		  	}

		  	if(empty($email)){
		  		$error_msg['fbbttmacountemail'] = esc_html__('Please enter your email','foodboxbooker'); 
		  	}

		  	if(!empty($email))
		  	{
				if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				  $error_msg['fbbttmacountemail'] = esc_html__('Please enter valid email address','foodboxbooker'); 
				}

			else
			{
				$emaildata = $this->fbbttm_check_user_exist_byemail($email);

				if($emaildata=='1'){
					$error_msg['fbbttmacountemail'] = esc_html__('User is already there with this email address','foodboxbooker'); 
				}
			}
	  	  } 

	  	 if(!empty($password_current)){
	  	  	if(wp_check_password($password_current, $orignalpass)) {
			} else {
			    $error_msg['fbbttmacountpassword'] = esc_html__('Your current password is wrong','foodboxbooker'); 
			}
	  	  }

	  	  if(empty($password_1) && !empty($password_2)){
	  	  	$error_msg['fbbttmanewpassword1'] = esc_html__('Please enter your new password','foodboxbooker'); 
	  	  }

	  	  if(!empty($password_1) && empty($password_2)){
	  	  	$error_msg['fbbttmanewpassword2'] = esc_html__('Please enter confirm new password','foodboxbooker'); 
	  	  }

	  	  if(!empty($password_1) && !empty($password_2)){

	  	  	if($password_1 != $password_2 ){
	  	  		$error_msg['fbbttmanewpassword1'] = esc_html__('Password mismatch.','foodboxbooker'); 
	  	  		$error_msg['fbbttmanewpassword2'] = esc_html__('Password mismatch.','foodboxbooker'); 
	  	  	}

	  	  }
	  	  
	  	$update = 0;
	  	$insert = 0;

	  	if(empty($error_msg)){
	  			
		  	if($emailinfo == '0'){
		  	
			  	$userdata = array(
					'ID' => $userid,
					'first_name' => $first_name,
					'last_name' => $last_name,
					'user_email ' => $email
				);


		  		wp_update_user($userdata);

		  		

		  		 $delivarydata = $this->fbbttm_comman_single_tableinfo(FBBTTM_DELIVERY_ADDRESS,'fbbttm_user_id',$userid);

		  		 if(!empty($delivarydata)){
		  		 	
			  		$data = array(
						  			'fbbttm_first_name'=>$first_name,
						  			'fbbttm_last_name'=>$last_name,
							 	);

		  				$this->fbbttm_common_updatetable(FBBTTM_DELIVERY_ADDRESS,$data,'fbbttm_user_id',$userid,'fbbttm_address_update');

	  				}else
	  				{
	  					
	  					$data = array(
				  			'fbbttm_user_id'=>$userid,
				  			'fbbttm_first_name'=>$first_name,
				  			'fbbttm_last_name'=>$last_name,
				  			'fbbttm_user_email'=>$email,
				  			
				  		);

					$deliveryid = $this->fbbttm_common_insert(FBBTTM_DELIVERY_ADDRESS,$data);

	  				}



		  		 if(!empty($password_1) && !empty($password_2)){

		  		 	//echo 'password set';
		  		 	wp_set_password($password_1, $userid);
		  		 	//wp_update_user($userid,'user_pass',)
		  		 }

		  		$message['success'] = esc_html__('Your account details update successfully','foodboxbooker'); 
		  		 
			  }
			  else
			  {
			  	$error_msg['fbbttmacountemail'] = esc_html__('User is already there with this email address','foodboxbooker'); 
			  }

		   }

		   $message['error_message'] = $error_msg;

		 

		 return  $message;
		 
	  }


	  public function fbbttm_user_login_form()
	  {

	  	global $wpdb,$fbbttm_cartobj;

	  	$message = array();
	  	$error_msg = array();


	  	$noncename = '';
		  	if(isset($_POST['fbbttm_meta_box_noncename'])){
		  	$noncename = sanitize_text_field(wp_unslash($_POST['fbbttm_meta_box_noncename']));
			  }


			if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {

				

				$message['loggedin'] = false;

		    	$message['message'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
						 
			 }
			 else{

			 	$username = $email =$password = '';

			  	if(isset($_POST['fbbttm-username'])){
					$username = sanitize_text_field(wp_unslash($_POST['fbbttm-username']));
				}

				if(isset($_POST['fbbttm-password'])){
					$password = sanitize_text_field(wp_unslash($_POST['fbbttm-password']));
				}


	  	if(!empty($username) && !empty($password)){


	  	    $info['user_login'] = $username;

		    $info['user_password'] = $password;
		    
		    $info['remember'] = true;

		    $user_signon = wp_signon( $info, false );

		    $user_id = username_exists( $username );	

		    $tokenid = '';

		     if(!empty($user_id)){

					$tokenid = $this->fbbttm_get_user_cookie_data(); 
					//$tokenid = "$tokenid";

					$tablename = FBBTTM_TB_FOODBOOKING_CART;

					$data = array(
						'fbbttm_user_id'=>$user_id 
					);

					/*
					update cart item info start date and end date		
					*/
					$cartdata = $this->fbbttm_comman_single_tableinfo($tablename,'fbbttm_token_id',$tokenid);

					if(!empty($cartdata)){
					//	$tokenid = "'$tokenid'";
						$this->fbbttm_common_updatetable($tablename,$data,'fbbttm_token_id',$tokenid,'fbbttm_cartupdate_date');

						$fbbttm_cartobj->fbbttm_validate_packin_order_iteminfo($user_id);
					}

				}
		


		    if ( is_wp_error($user_signon) ){

		    	$message['loggedin'] = false;
		    	$message['message'] = esc_html__('Wrong username or password please check your details','foodboxbooker');

		    } else {

		    	$message['loggedin'] = true;
		    	$message['message'] = esc_html__('Login successful, redirecting...','foodboxbooker');
		       
		    }

	  	  }
	  	  else
	  	  {
	  	  		$message['loggedin'] = false;
		    	$message['message']  = esc_html__('Please check username or password.','foodboxbooker');
	  	  }
	    }
	   return $message;
	  }




	  /**
	   * Function for user login
	   */ 

	  public function fbbttm_user_login($userdata=null){



	  	global $wpdb,$fbbttm_cartobj;

	  	$message = array();
	  	$error_msg = array();


	  	$noncename = sanitize_text_field(wp_unslash($userdata['fbbttm_meta_box_noncename']));

			if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {

				

				$message['loggedin'] = false;

		    	$message['message'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
						 
			 }
			 else{

			 	$username = $email =$password = '';

			  	if(isset($userdata['fbbttm-username'])){
					$username = sanitize_text_field(wp_unslash($userdata['fbbttm-username']));
				}

				if(isset($userdata['fbbttm-password'])){
					$password = sanitize_text_field(wp_unslash($userdata['fbbttm-password']));
				}


	  	if(!empty($username) && !empty($password)){


	  	    $info['user_login'] = $username;

		    $info['user_password'] = $password;
		    
		    $info['remember'] = true;

		    $user_signon = wp_signon( $info, false );

		    $user_id = username_exists( $username );	

		    $tokenid = '';

		 	

		
		    	if(!empty($user_id)){

					$tokenid = $this->fbbttm_get_user_cookie_data(); 
					$tokenid = "$tokenid";

					$tablename = FBBTTM_TB_FOODBOOKING_CART;

					$data = array(
						'fbbttm_user_id'=>$user_id 
					);

					/*
					update cart item info start date and end date		
					*/
					$cartdata = $this->fbbttm_comman_single_tableinfo($tablename,'fbbttm_token_id',$tokenid);

					if(!empty($cartdata)){
						$tokenid = "'$tokenid'";
						$this->fbbttm_common_updatetable($tablename,$data,'fbbttm_token_id',$tokenid,'fbbttm_cartupdate_date');

						$fbbttm_cartobj->fbbttm_validate_packin_order_iteminfo($user_id);
					}

				}
		


		    if ( is_wp_error($user_signon) ){

		    	$message['loggedin'] = false;
		    	$message['message'] = esc_html__('Wrong username or password please check your details','foodboxbooker');

		    } else {

		    	$message['loggedin'] = true;
		    	$message['message'] = esc_html__('Login successful, redirecting...','foodboxbooker');
		       
		    }

	  	  }
	  	  else
	  	  {
	  	  		$message['loggedin'] = false;
		    	$message['message']  = esc_html__('Please check username or password.','foodboxbooker');
	  	  }
	    }
	   return $message;
	  }

	  /**
	   * Public function for user register 
	   */
	  public function fbbttm_user_register($userdata=null)
	  {

	  	global $wpdb;

	  	$message   =  array();
	  	$error_msg =  array();

	   	$username = $email =$password = '';
	  	if(isset($_POST['fbbttm-registerusername'])){
			$username = sanitize_text_field(wp_unslash($_POST['fbbttm-registerusername']));
		}

		if(isset($_POST['fbbttm-registeremail'])){
			$email = sanitize_text_field(wp_unslash($_POST['fbbttm-registeremail']));
		}

		if(isset($_POST['fbbttm-registerpassword'])){
			$password = sanitize_text_field(wp_unslash($_POST['fbbttm-registerpassword']));
		}

		$noncename = '';
		  	if(isset($_POST['fbbttm_meta_box_noncename'])){
		  	$noncename = sanitize_text_field(wp_unslash($_POST['fbbttm_meta_box_noncename']));
			  }


		if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {
			  $error_msg['php-error'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
		 }

	  	if(empty($username))
	  	{
	  		$error_msg['fbbttm-registerusername'] = esc_html__('Please enter your username','foodboxbooker'); 
	  	}
	  	if(empty($email))
	  	{
	  		$error_msg['fbbttm-registeremail'] = esc_html__('Please enter your email','foodboxbooker'); 
	  	}

	  	if(empty($password))
	  	{
	  		$error_msg['fbbttm-registerpassword'] = esc_html__('Please enter password','foodboxbooker'); 
	  	}

	  	
	  	if(!empty($password))
	  	{
	  		$length = strlen ($password);
	  		if($length < 5)	{
	  			$error_msg['fbbttm-registerpassword'] = esc_html__('Please enter password atleast five character','foodboxbooker'); 
	  		}
	  	}

	  	if(!empty($email))
		  	{
				if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
				  $error_msg['fbbttm-registeremail'] = esc_html__('Please enter valid email address','foodboxbooker'); 
				}

			else
			{
				$emaildata = $this->fbbttm_check_user_exist_byemail($email);
				if($emaildata=='1'){
					$error_msg['fbbttm-registeremail'] = esc_html__('User is already there with this email address','foodboxbooker'); 
				}
			}
	  	  } 

	  	if(!empty($username))
	  	{
	  		$user_id = username_exists( $username );
	  		if(!empty($user_id)){
	  			$error_msg['fbbttm-registerusername'] = esc_html__('User is already exist with same username','foodboxbooker'); 
	  		}
	  	} 

	  	$message['error_message'] = $error_msg;

	 
	  	if(empty($error_msg)){


		 $user_id =	$this->fbbttm_add_newuser($email,$password,$username);

		 $message['success'] = 	esc_html__('User register successfully. Login with same Username and password','foodboxbooker'); 
	  	}

	 	return $message;
	 
	  }
	  /**
	   * Function for user lostpassword
	   */ 
	  public function fbbttm_user_lost_password($userdata=null)
	  {

	  	global $wpdb, $current_site, $wp_hasher, $fbbttm_emailobj;

	  	$messagearray = array();
	  	$error_msg = array();
	  	$username = $noncename ='';
	  	if(isset($_POST['fbbttm-username'])){
	  		$username = sanitize_text_field(wp_unslash($_POST['fbbttm-username']));
	  	}

	  	if(isset($_POST['fbbttm_meta_box_noncename'])){
	  		$noncename = sanitize_text_field(wp_unslash($_POST['fbbttm_meta_box_noncename']));
	 	}

		if ( ! isset( $noncename ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash($noncename) ), 'fbbttm_meta_box_nonce' ) ) {
				  $error_msg['php-error'] = esc_html__('Sorry, Your request can not be processed due to security reason.','foodboxbooker'); 
		}

	  	if(empty($username))
	  	{
	  		$error_msg['fbbttm-username'] = esc_html__('Please enter your username','foodboxbooker'); 
	  	}

	  	if(!empty($username))
	  	{
	  		$user_id = username_exists( $username );
	  		if(empty($user_id)){
	  			$user_id = $this->fbbttm_check_user_exist_byemail($username);
	  				if(empty($user_id)){
	  					$error_msg['fbbttm-username'] = esc_html__('Invalid username or email.','foodboxbooker'); 
	  				}
	  		}
	  	} 

	  		do_action('lostpassword_post');

	  		$messagearray['error_message'] = $error_msg;

	  		if(empty($error_msg)){
		  		$user_data = get_user_by('login', $username);

				if(empty($user_data))
				{
					$user_data = get_user_by( 'email', trim( $username ) );
				}

	   			$user_id = $user_data->ID;
	  		 	$user_login = $user_data->user_login;
			    $user_email = $user_data->user_email;

			    do_action('retreive_password', $user_login);  // Misspelled and deprecated

			    $allow = apply_filters('allow_password_reset', true, $user_data->ID);

			    if ( ! $allow )
			        return false;
			    else if ( is_wp_error($allow) )
			        return false;
			        
			    $key = wp_generate_password( 20, false );
			    do_action( 'retrieve_password_key', $user_login, $key );

			    if ( empty( $wp_hasher ) ) {
			    	if ( ! class_exists( 'PasswordHash' ) ) {
    					require_once ABSPATH . WPINC . '/class-phpass.php';
					}

				       $wp_hasher = new PasswordHash( 8, true );
   				 }
			    $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
			    $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user_login ) );

			    $hashed  = base64_encode( $hashed  );
			    $user_id = base64_encode( $user_id );

			    $emailtemp = $fbbttm_emailobj->fbbttm_reset_mail($user_login,$hashed,$user_id,$user_email, $key);

			  	$messagearray['success'] = 	esc_html__('Please check your email in your inbox.','foodboxbooker'); 
	  	   }
	 	return $messagearray;
	  }

	  /**
	   * Check user login or not
	   * return user id 
	   **/

	  public function fbbttm_check_user_loginornot()
	  {
	  	$user_id = '';

	  	if ( is_user_logged_in() ) {

	  		$user_id = get_current_user_id();

	  	}

	  	return $user_id;

	  }

	 /**
	  * Function for check check user email on checkout page 
	  * 
	  */  


	 public function fbbttm_user_email_checkajx($emailval=null)
	 {

	 	$message = array();
	 	$error_msg = array();
	 	$extramessage = array();
	 		if(empty($emailval)){
		  		$error_msg['fbbttm-email'] = esc_html__('Please enter your email','foodboxbooker'); 
		  	}

		  	if(!empty($emailval))
		  	{
				if (!filter_var($emailval, FILTER_VALIDATE_EMAIL)) 
					{
					  	$error_msg['fbbttm-email'] = esc_html__('Please enter valid email address','foodboxbooker'); 
					}

			}

			$message['error_message'] = $error_msg;

			if(empty( $error_msg)){

				

				$user_id = email_exists($emailval);
				
				if(!empty($user_id)){
					
					$extramessage['userid'] = $user_id;
					$extramessage['useravailindata'] = '1';

					$message['success']  = esc_html__('This email is already exist please login from below login box','foodboxbooker'); 
					$message['extramessage'] = $extramessage;
				}
				else{
					$extramessage['userid'] = '';
					$extramessage['useravailindata'] = '';

					$message['success']['newemail'] ='1';
					$message['extramessage'] = $extramessage;
				}

			}
			

			return $message;

	 }



	 /**
	 *  Function for get cookie data
	 */ 

	public function fbbttm_get_user_cookie_data()
	{

		$tokenid ='';
		
			if(isset($_COOKIE['custom_token_cookie'])){

				$tokenid = sanitize_text_field( wp_unslash($_COOKIE['custom_token_cookie'])); 
			
			}

		return $tokenid;

	}


	/**
	 * fbbttm_get_setting_tablekeyval
	 */

	 public function fbbttm_get_setting_tablekeyval($keyname=null)
	 {
	 	global $wpdb, $fbbttm_helperobj;

		$fbbttm_settingdata = $this->fbbttm_comman_single_tableinfo(FBBTTM_TB_SETTING,'fbbttm_setting_id');

		$keyarray = array();
		$array_withkey = array(); 


		foreach($fbbttm_settingdata as $dataval)
		  {

		  	if($dataval->fbbttm_setting_name == $keyname)
		  	{
		  		array_push($keyarray,$dataval->fbbttm_setting_value);

		  		$array_withkey[$dataval->fbbttm_setting_name] = $dataval->fbbttm_setting_value;
		  	}
		 }


		 return $array_withkey;


	 } 

	 /**
	  * common delete query from table using id
	  */

	  public function fbbttm_delete_from_table($tablename=null,$fieldname=null,$fieldvalue=null)  
	  {
	  	global $wpdb;

	  	if(!empty($tablename) && !empty($fieldname) && !empty($fieldvalue))
		  	{
		  		$wpdb->delete( $tablename, array( $fieldname => $fieldvalue ) );
		  	}

	  }

	 



	public function fbbttm_paramval($keyname=null)
	{
		
		return filter_input( INPUT_GET, $keyname, FILTER_SANITIZE_STRING );
	}

}