<?php
/**
 * GFB Customer Class
 *
 * @package GFB.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'APBGF_Customer' ) ) {
	/**
	 * Checks if WooCommerce is enabled.
	 */
	class APBGF_Customer {        
		/**
		 * Instance
		 *
		 * @var $instance
		 */
		private static $instance = null;

		private static $checkPostType = null;

		/**
		 * Init the Dependencies.
		 */
		private function __construct() {                 

			// phpcs:ignore
			self::$checkPostType = isset( $_REQUEST['post_type'] ) && ! empty( sanitize_text_field(wp_unslash( $_REQUEST['post_type'] )) ) ? sanitize_text_field(wp_unslash( $_REQUEST['post_type'] )) : '';

			add_action( 'init', array( $this, 'register_customer_posttype' ) );
			add_filter( 'manage_apbgf-customer_posts_columns', array( $this, 'apbgf_modify_column_names' ) );
			add_action( 'manage_apbgf-customer_posts_custom_column', array( $this, 'apbgf_add_custom_column' ), 9, 2 );

			add_action( 'deleted_user', array( $this, 'delete_apbgf_customer_if_user_deleted' ), 99, 1 );

			add_action( 'wp_ajax_apbgf_add_customer', array( $this, 'apbgf_add_customer' ) );
			add_action( 'wp_ajax_apbgf_edit_customer', array( $this, 'apbgf_edit_customer' ) );
			add_action( 'wp_ajax_apbgf_show_customer_data', array( $this, 'apbgf_show_customer_data' ) );
			add_action( 'wp_ajax_apbgf_delete_customer', array( $this, 'apbgf_delete_customer' ) );
			add_action( 'wp_ajax_apbgf_cancel_appointment_by_customer', array( $this, 'apbgf_cancel_appointment_by_customer' ) );

			add_action( 'wp_enqueue_scripts', array( $this, 'register_frontend_assets' ) );

			add_action( 'init', array( $this, 'apbgf_register_customer_appointment_shortcode' ) );         

			if ( 'apbgf-customer' === self::$checkPostType ) {                

				add_action( 'admin_footer', array( $this, 'highlight_menu' ) );

				add_filter('post_row_actions', '__return_empty_array');

				add_action('manage_posts_extra_tablenav', array( $this, 'apbgf_manage_posts_extra_tablenav' ));

				add_filter('months_dropdown_results', '__return_empty_array');

				add_filter( 'bulk_actions-edit-apbgf-customer', '__return_empty_array' ); //

				// HTML of the filter
				add_action( 'restrict_manage_posts', array( $this, 'apbgf_add_filters' ) );

				add_action( 'views_edit-apbgf-customer', function ( $views ) {

					unset($views['all']);
					unset($views['publish']);
					unset($views['trash']);
					unset($views['draft']);

					return $views;
				});

				// the function that filters posts
				add_action( 'pre_get_posts', array( $this, 'apbgf_filter_query' ) );

			}

			add_filter( 'show_admin_bar', array( $this, 'remove_admin_toolbar_for_apbgf_customers' ), 90, 1 );
		}

		public static function apbgf_create_customer( $data = array() ) {

	    	if ( ! empty( trim( $data['fname'] ) ) && ! empty( trim( $data['email'] ) ) ) {				

	    		$user = get_user_by('email', trim( $data['email'] ) );

	    		if ( $user ) {
	    			$role = ( array ) $user->roles;
	    			if (in_array('administrator', $role)) {
	    				return $user->ID;
	    			}

	    			$apbgf_user_id = get_user_meta( $user->ID, 'apbgf_user', true);
	    			if ( ! empty( $apbgf_user_id ) ) {
	    				return $user->ID;
	    			} else {
	    				$args = apply_filters( 'apbgf_add_customer_args', array(
	    					'post_title' => trim( $data['fname'] ) . ' ' . trim( $data['lname'] ),
	    					'post_type' => 'apbgf-customer',
	    					'post_status' => 'publish',
	    					'wp_error'    => true,
	    					'meta_input'  => array(
	    						'wp_user' => $user->ID,
	    						'phone' => trim( $data['phone'] )
	    					)
	    				));

	    				$apbgf_user_id = wp_insert_post( $args );

	    				if ( ! is_wp_error( $apbgf_user_id ) ) {
	    					update_user_meta( $user->ID, 'apbgf_user', $apbgf_user_id);

	    					if ( ! in_array( 'administrator', $user->roles) ) {
	    						$user->add_role( 'apbgf-customer' );
	    					}

	    					return $user->ID;
	    				}
	    			}
	    		} else {
	    			$user_args = array(										
	    				'user_login'   => trim( $data['fname'] ) . ' ' . trim( $data['lname'] ),
	    				'user_email'   => trim( $data['email'] ),
	    				'display_name' => trim( $data['fname'] ) . ' ' . ( isset( $data['lname'] ) ? trim( $data['lname'] ) : '' ),
	    				'first_name'   => trim( $data['fname'] ),
	    				'last_name'    => isset( $data['lname'] ) ? trim( $data['lname'] ) : '',
	    				'role' 		   => 'apbgf-customer',
	    				'meta_input'  => array(
	    					'phone' => isset( $data['phone'] ) ? trim( $data['phone'] ) : ''
	    				)
	    			);

	    			$user_args['user_pass'] = isset( $data['password'] ) && ! empty( $data['password'] ) ? trim($data['password']) : apbgf_randon_pass();

	    			$wp_user = wp_insert_user($user_args);
					
	    			if ( ! is_wp_error( $wp_user ) ) {					

	    				$args = apply_filters( 'apbgf_add_customer_args', array(
	    					'post_title' => trim( $data['email'] ),
	    					'post_type' => 'apbgf-customer',
	    					'post_status' => 'publish',
	    					'wp_error'    => true,
	    					'meta_input'  => array(
	    						'wp_user' => $wp_user,							
	    						'phone' => trim( $data['phone'] )							
	    					)
	    				));

	    				$apbgf_user = wp_insert_post( $args );					

	    				if ( ! is_wp_error( $apbgf_user ) ) {

	    					update_user_meta( $wp_user, 'apbgf_user', $apbgf_user );	
							$apbgf_email_templates = get_option('apbgf_email_templates', array());
							$template_11_switch = isset($apbgf_email_templates['template_11']['switch'])
								? $apbgf_email_templates['template_11']['switch']
								: null;			

	    					/* EMAIL NOTIFICATION STARTS */
	    					if ( true === apply_filters('apbgf_add_customer_personal_details_notification', true) &&  'enabled' == $template_11_switch) {
	    						$body = __('Your account has been created, below are the credentials to login', 'apbgf');
	    						APBGF_Email::new_customer_notification( $wp_user, $body, $user_args['user_pass'] );
	    					}
	    					/* EMAIL NOTIFICATION ENDS */

	    					return $wp_user;
	    				}

	    			}
	    		}

	    	}

	    	return false;
	    }


		public function remove_admin_toolbar_for_apbgf_customers( $show ) {
			
			$user = wp_get_current_user();
			$user_roles = (array) $user->roles;
			if ( in_array( 'apbgf-customer', $user_roles ) ) {
				$show = apply_filters('apbgf_customer_remove_admin_toolbar', false); // Hide admin toolbar
			}
			
			return $show;
		}

	
		public function apbgf_add_filters( $post_type ) {         

			require_once APBGF_ADMIN_VIEW_PATH . 'appointment-filters.php';           
		}

		public static function all_customer( $customer_id = '' ) {

			if ( ! empty( $customer_id ) ) {
				$get_customer = get_post( $customer_id );
				if ( $get_customer && 'apbgf-customer' == $get_customer->post_type ) {                    
					return $get_customer;
				}
			}

			$get_customer = get_posts( array(
				'post_type' => 'apbgf-customer',              
				'numberposts' => -1,
				'status' => 'publish',
			));         

			if ( is_array( $get_customer ) && ! empty( $get_customer ) ) {
				$all_customers = array();

				foreach ( $get_customer as $customer ) {                    
					$wp_user = get_post_meta( $customer->ID, 'wp_user', true );
					$userdata = get_userdata( $wp_user );                   
					if ( $userdata ) {
						$all_customers[ $customer->ID ] = $userdata->user_email;
					}
				}

				return (array) $all_customers;
			}
		}

		public function register_frontend_assets() {
			
			if ( APBGF_LIVE_MODE ) {
				$minimized = '.min';
				$clear_cache = '';
			} else {
				$minimized = '';
				$clear_cache = '?t=' . gmdate('ymdhis');
			}

			wp_register_style( 'apbgf-sweetalert-style', APBGF_COMMON_URL . 'sweetalert2.min.css', array(), APBGF_VERSION . $clear_cache, 'all' );

			wp_register_script( 'apbgf-sweetalert-script', APBGF_COMMON_URL . 'sweetalert2.min.js', array( 'jquery' ), APBGF_VERSION . $clear_cache, true );
			wp_register_script( 'apbgf-frontend-script', APBGF_JS_URL . 'apbgf-frontend-script' . $minimized . '.js', array( 'jquery', 'apbgf-sweetalert-script' ), APBGF_VERSION . $clear_cache, true );
			wp_localize_script( 'apbgf-frontend-script', 'apbgf_frontend', array(
				'ajaxurl'  => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('appointment-and-booking-for-gravity-forms'),
				'title' => __('Appointment Cancellation', 'appointment-and-booking-for-gravity-forms'),
				'confirm' => __('Confirm', 'appointment-and-booking-for-gravity-forms'),
				'cancel' => __('No, I don\'t want', 'appointment-and-booking-for-gravity-forms'),
			)); 
		}

		public function apbgf_filter_query( $admin_query ) {

			if ( is_admin() && $admin_query->is_main_query() ) {

				if ( is_user_logged_in() ) {

					if ( absint($admin_query->query_vars['s']) ) {
						// Set the post id value
						$admin_query->set('p', $admin_query->query_vars['s']);

						// Reset the search value
						$admin_query->set('s', '');
					}           
				}               
			}           

			return $admin_query;
		}

		// public function apbgf_add_bulk_delete( $actions ) {

		//  unset( $actions['edit'] );
		//  unset( $actions['trash'] );
		//  $actions['delete'] = __('Delete All', 'appointment-and-booking-for-gravity-forms');

		//  return $actions;
		// }

		public function apbgf_register_customer_appointment_shortcode() {
			add_shortcode( 'apbgf_customer_appointments', array( $this, 'apbgf_customer_appointments' ) );
			add_shortcode( 'apbgf_customer_appointment', array( $this, 'apbgf_customer_appointments' ) );
		}

		public function apbgf_customer_appointments() {

			if ( is_admin() ) {
				return;
			}

			wp_enqueue_style('apbgf-sweetalert-style');
			wp_enqueue_script('apbgf-sweetalert-script');
			wp_enqueue_script('apbgf-frontend-script');

			$redirect_url = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] )): '';
			
			if ( is_user_logged_in() ) {
				$user = wp_get_current_user();  
				$user_id = $user->ID;               
				if ( isset( $user->roles ) && in_array( 'apbgf-customer', $user->roles ) ) {
					if (file_exists(get_stylesheet_directory() . '/gf-bookings-premium/customer-appointments.php') ) {
						$template_path =  get_stylesheet_directory() . '/gf-bookings-premium/customer-appointments.php';
						require_once $template_path;
					} else {
						$template_path = apply_filters('apbgf_customer_appointments_template', APBGF_VIEW_PATH . 'customer-appointments.php');
						require_once $template_path;
					}
				} else {
					// Translators: %1$s and %2$s are tags.
					printf( esc_html__( 'You are logged in with a different role. %1$sClick here%2$s to log in with a apbgf-customer role.', 'appointment-and-booking-for-gravity-forms' ), '<a href="' . esc_url( wp_login_url($redirect_url) ) . '">', '</a>' );
				}
			} else {
				// Translators: %1$s and %2$s are tags.
				printf( esc_html__( '%1$sClick here%2$s to login.', 'appointment-and-booking-for-gravity-forms' ), '<a href="' . esc_url( wp_login_url($redirect_url) ) . '">', '</a>' );
			}

			return ob_get_clean();
		}

		public static function get_customer_by_id( $customer_id ) {

			if ( ! empty( $customer_id ) ) {
				$customer = get_post( $customer_id );

				if ( $customer && 'apbgf-customer' == $customer->post_type ) {
					return $customer;
				}               
			}

			return false;
		}

		public function apbgf_cancel_appointment_by_customer() {

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(          
				'status'  => 'error'
			);

			$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
			$status = isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '';
			$reason = isset( $_POST['reason'] ) ? sanitize_text_field( wp_unslash( $_POST['reason'] ) ) : '';

			if ( $post_id ) {

				update_post_meta( $post_id, 'status', $status );
				update_post_meta( $post_id, 'cancel_reason', $reason );

				APBGF_Email::send_notification( $post_id, 'template_3', 'customer' ); # template_3
				APBGF_Email::send_notification( $post_id, 'template_6', 'admin' ); # template_6
				APBGF_Email::send_notification( $post_id, 'template_7', 'staff' ); # template_7
				
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
				$response_message = sprintf(// translators: %1$s is for Appointment ID
					esc_html__( 'Your appointment # %1$s has been cancelled.', 'appointment-and-booking-for-gravity-forms' ),
					esc_attr( absint( $data['post_id'] ) )
				);              
				$response['message'] = $response_message;
				$response['status'] = 'success';
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_show_customer_data() {

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'message' => esc_html__( 'Failed to cancel the appointment.', 'appointment-and-booking-for-gravity-forms' ),  
				'status'  => 'error'
			);
			// Accept only the expected value
			$post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;

			if ( $post_id ) {

				$post = get_post( $post_id );               
				if ( $post && 'apbgf-customer' == $post->post_type ) {

					$user_id = get_post_meta( $post_id, 'wp_user', true );
					$userdata = get_userdata( $user_id );
					if ( $userdata ) {
						$phone = get_post_meta( $post_id, 'phone', true );
						if ( empty( $phone ) ) {
							$phone = get_user_meta( $user_id, 'phone', true );
						}
						$gender = get_post_meta( $post_id, 'gender', true );
						if ( '' === $gender ) {
							$gender = get_user_meta( $user_id, 'gender', true );
						}
						$dob = get_post_meta( $post_id, 'dob', true );
						if ( '' === $dob ) {
							$dob = get_user_meta( $user_id, 'dob', true );
						}
						$info = get_post_meta( $post_id, 'info', true );
						if ( '' === $info ) {
							$info = get_user_meta( $user_id, 'info', true );
						}

						$response['fname'] = $userdata->first_name;
						$response['lname'] = $userdata->last_name;
						$response['email'] = $userdata->user_email;
						//$response['password'] = $userdata->login_pass;
						$response['user']  = absint( $user_id );
						$response['phone'] = $phone;
						$response['gender'] = $gender;
						$response['dob'] = $dob;
						$response['info'] = $info;
						$response['status'] = 'success';
					}
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_delete_customer() {

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			$response = array(
				'message' => esc_html__( 'Customer not deleted.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error',
			);

			if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'delete_users' ) ) {
				$response['message'] = esc_html__( 'You do not have permission to delete customers.', 'appointment-and-booking-for-gravity-forms' );
				echo wp_json_encode( $response );
				wp_die();
			}

			$post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;

			if ( $post_id ) {
				$post = get_post( $post_id );
				if ( $post && 'apbgf-customer' === $post->post_type ) {
					$user_id = absint( get_post_meta( $post_id, 'wp_user', true ) );

					if ( wp_delete_post( $post_id, true ) ) {
						if ( $user_id ) {
							delete_user_meta( $user_id, 'apbgf_user' );

							$user = get_userdata( $user_id );
							if ( $user && in_array( 'apbgf-customer', (array) $user->roles, true ) && 1 === count( $user->roles ) ) {
								require_once ABSPATH . 'wp-admin/includes/user.php';
								wp_delete_user( $user_id );
							}
						}

						$response['message'] = esc_html__( 'Customer deleted successfully.', 'appointment-and-booking-for-gravity-forms' );
						$response['status']  = 'success';
					}
				}
			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function delete_apbgf_customer_if_user_deleted( $user_id ) {           

			$get_customer = get_posts( array(
				'post_type' => 'apbgf-customer',
				'numberposts' => -1,
				'meta_query' => array(
					array(
						'key'   => 'wp_user',
						'value' => $user_id
					)
				)
			));         

			if ( isset($get_customer[0]) && $get_customer[0] ) {
				wp_delete_post( $get_customer[0]->ID, true );
			}           
		}

		public function apbgf_edit_customer() {

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );
			if ( ! current_user_can( 'create_users' ) ) {
		        wp_send_json_error( array(
		            'message' => __( 'You do not have permission to add customer members.', 'appointment-and-booking-for-gravity-forms' ),
		            'status'  => 'error',
		        ) );
		    }
			$response = array(
				'message' => esc_html__( 'Please fill all required fields.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error',
			);
		
			$post_id  = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
			$fname    = isset( $_POST['fname'] ) ? sanitize_text_field( wp_unslash( $_POST['fname'] ) ) : '';
			$lname    = isset( $_POST['lname'] ) ? sanitize_text_field( wp_unslash( $_POST['lname'] ) ) : '';
			$email    = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
			$info     = isset( $_POST['info'] ) ? sanitize_text_field( wp_unslash( $_POST['info'] ) ) : '';
			$gender   = isset( $_POST['gender'] ) ? sanitize_text_field( wp_unslash( $_POST['gender'] ) ) : 'no';
			$phone    = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
			$dob      = isset( $_POST['dob'] ) ? sanitize_text_field( wp_unslash( $_POST['dob'] ) ) : '';
			$password = isset( $_POST['password'] ) ? sanitize_text_field( wp_unslash( $_POST['password'] ) ) : '';
		
			// // Validate email.
			// if ( ! is_email( $email ) ) {
			// 	$response['message'] = __( 'Invalid email address. Customer not updated.', 'appointment-and-booking-for-gravity-forms' );
			// 	echo wp_json_encode( $response );
			// 	wp_die();
			// }
		
			// Find the linked WP user.
			$user_id = get_post_meta( $post_id, 'wp_user', true );

			if ( ! $user_id ) {
				$response['message'] = __( 'No linked WordPress user found for this customer.', 'appointment-and-booking-for-gravity-forms' );
				echo wp_json_encode( $response );
				wp_die();
			}

			 	update_user_meta( $user_id, 'info',   trim( $info ) );
    			update_user_meta( $user_id, 'gender', trim( $gender ) );
    			update_user_meta( $user_id, 'dob',    trim( $dob ) );
    			update_user_meta( $user_id, 'phone',  trim( $phone ) );
			


			if ( $user_id ) {
		
				// Update the corresponding apbgf-customer CPT.
				$apbgf_user = get_user_meta( $user_id, 'apbgf_user', true );
				$user_info = get_userdata($user_id);
			    if ($user_info) {
			        $fname =  esc_html(trim($user_info->first_name . ' ' . $user_info->last_name));
			    }	
				$args = apply_filters( 'apbgf_edit_customer_args', array(
					'ID'          => intval( $apbgf_user ),
					'post_title'  => $fname,
					'post_type'   => 'apbgf-customer',
					'post_status' => 'publish',
					'meta_input'  => array(
						'wp_user' => $user_id,
						'info'    => $info,
						'gender'  => $gender,
						'phone'   => $phone,
						'dob'     => $dob,
					),
				) );
		
				$apbgf_user = wp_update_post( $args, true );
		
				if ( ! is_wp_error( $apbgf_user ) ) {
		
					update_user_meta( $wp_user, 'apbgf_user', $apbgf_user );
		
					$response['message'] = esc_html__( 'Customer updated successfully.', 'appointment-and-booking-for-gravity-forms' );
					$response['status']  = 'success';
		
					/* EMAIL NOTIFICATION STARTS */
					if ( true === apply_filters( 'apbgf_edit_customer_personal_details_notification', true ) ) {
						$body     = __( 'Your account details have been updated. Below are the credentials to login:', 'appointment-and-booking-for-gravity-forms' );
						$password = ! empty( $password ) ? $password : __( 'Password not changed', 'appointment-and-booking-for-gravity-forms' );
						$response['notification'] = APBGF_Email::new_customer_notification( $wp_user, $body, $password );
					}
					/* EMAIL NOTIFICATION ENDS */
		
				} else {
					$response['message'] = $apbgf_user->get_error_message();
				}
		
			} else {
				$response['message'] = $wp_user->get_error_message();
			}
		
			echo wp_json_encode( $response );
			wp_die();
		}
		

		public function apbgf_add_customer() {            

			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			if ( ! current_user_can( 'create_users' ) ) {
		        wp_send_json_error( array(
		            'message' => __( 'You do not have permission to add customer.', 'appointment-and-booking-for-gravity-forms' ),
		            'status'  => 'error',
		        ) );
		    }

			$response = array(
				'message' => esc_html__( 'Please fill all required fields.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error',
				'notification' => false
			);
			 
           	$apbgf_user_id = isset( $_POST['apbgf_user'] ) ? sanitize_text_field( wp_unslash( $_POST['apbgf_user'] ) ) : '';
			$info = isset( $_POST['info'] ) ? sanitize_text_field( wp_unslash( $_POST['info'] ) ) : '';
			$gender = isset( $_POST['gender'] ) ? sanitize_text_field( wp_unslash( $_POST['gender'] ) ) : 'no';
			$dob = isset( $_POST['dob'] ) ? sanitize_text_field( wp_unslash( $_POST['dob'] ) ) : '';
			$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';

			if ( ! empty( trim( $apbgf_user_id ) ) && ! empty( trim( $gender ) ) && ! empty( trim( $dob ) ) ) {

				update_user_meta( $apbgf_user_id, 'info',   trim( $info ) );
    			update_user_meta( $apbgf_user_id, 'gender', trim( $gender ) );
    			update_user_meta( $apbgf_user_id, 'dob',    trim( $dob ) );
    			update_user_meta( $apbgf_user_id, 'phone',  trim( $phone ) );

				if ( $apbgf_user_id ) {                  
					$user_info = get_userdata($apbgf_user_id);
				    if ($user_info) {
				        $fname =  esc_html(trim($user_info->first_name . ' ' . $user_info->last_name));
				    }
					$args = apply_filters( 'apbgf_add_customer_args', array(
						'post_title' => $fname,
						'post_type' => 'apbgf-customer',
						'post_status' => 'publish',
						'wp_error'    => true,
						'meta_input'  => array(
							'wp_user' => $apbgf_user_id,
							'info' => trim( $info ),
							'gender' => trim( $gender ),
							'phone' => trim( $phone ),
							'dob' => trim( $dob ),
						)
					));

					$apbgf_user = wp_insert_post( $args );

					if ( ! is_wp_error( $apbgf_user ) ) {

						update_user_meta( $wp_user, 'apbgf_user', $apbgf_user );
						$response['message'] = esc_html__( 'Customer created successfully.', 'appointment-and-booking-for-gravity-forms' );
						$response['status'] = 'success';

						/* EMAIL NOTIFICATION STARTS */
						if ( true === apply_filters('apbgf_add_customer_personal_details_notification', true) ) {
							$body = __('Your account has been created, below are the credentials to login', 'appointment-and-booking-for-gravity-forms');
							$response['notification'] = APBGF_Email::new_customer_notification( $wp_user, $body, $user_args['user_pass'] );
						}
						/* EMAIL NOTIFICATION ENDS */

					} else {

						$response['message'] = $wp_user->get_error_message();

					}

				} else {

					$response['message'] = $wp_user->get_error_message();

				}

			}

			echo wp_json_encode( $response );
			wp_die();
		}

		public function apbgf_add_custom_column( $column, $postId ) {

			$user_id = get_post_meta( $postId, 'wp_user', true );
			$userdata = get_userdata( $user_id );

			if ( ! $userdata ) {
				return $column;
			}

			switch ($column) {
				case 'id':
				echo '&nbsp;&nbsp;' . esc_attr($postId);
					break;

				case 'name':
				echo esc_attr($userdata->display_name);
					break;

				case 'phone':
				echo esc_attr ( get_post_meta($postId, 'phone', true) );
					break;

				case 'email':
				echo esc_attr($userdata->user_email);
					break;

				case 'actions':
					echo '<a href="#" data-type="customer" data-id="apbgf-customer-modal" data-post_id="' . esc_attr( $postId ) . '" class="wc-dashicons apbgf-edit" title="' . esc_attr__( 'Edit', 'appointment-and-booking-for-gravity-forms' ) . '"> <i class="fa fa-edit customer--icon"></i></a>';
					if ( 'publish' === get_post_status( $postId ) ) {
						echo '<a href="#" data-type="customer" data-post_id="' . esc_attr( $postId ) . '" class="wc-dashicons apbgf-delete" title="' . esc_attr__( 'Delete', 'appointment-and-booking-for-gravity-forms' ) . '"> <i class="fa fa-trash customer--icon"></i></a>';
					}
					break;
			}
		}

		public function apbgf_modify_column_names( $columns ) {           
			unset($columns['date']);
			unset($columns['title']);
			unset($columns['cb']);

			$columns['id'] = __('&nbsp;&nbsp;Customer ID', 'appointment-and-booking-for-gravity-forms');
			$columns['name'] = __('Name', 'appointment-and-booking-for-gravity-forms');
			$columns['phone'] = __('Phone', 'appointment-and-booking-for-gravity-forms');
			$columns['email'] = __('Email', 'appointment-and-booking-for-gravity-forms');         
			$columns['actions'] = __('Actions', 'appointment-and-booking-for-gravity-forms');

			return $columns;
		}

		public function apbgf_manage_posts_extra_tablenav( $which ) {
			if ( 'top' === $which ) {
				printf('<a href="#" data-id="apbgf-customer-modal" class="apbgf-add-button"><i class="fa fa-plus-circle"></i>%1$s</a>', esc_html__('Add Customers', 'appointment-and-booking-for-gravity-forms') );
			}
		}

		public function highlight_menu() {

			//adding customer modal view file
			require_once APBGF_ADMIN_VIEW_PATH . 'modal/customer-modal.php';

			//adding customer modal view file
			require_once APBGF_ADMIN_VIEW_PATH . 'modal/customer-import-modal.php';

			$popup_img = defined( 'APBGF_IMAGE_URL' ) ? APBGF_IMAGE_URL . 'ProPopup.svg' : '';
			$popup_url = 'https://gravitybooking.com/pricing/?utm_source=plugin&utm_medium=customer';
			if ( $popup_img ) {
				?>
				<div id="apbgf-customer-pro-modal" class="modal" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Export', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:fixed;inset:0;align-items:center;justify-content:center;">
					<div class="apbgf-customer-pro-modal__inner" style="position:relative;max-width:640px;width:100%;margin:auto;">
						<div class="apbgf-customer-pro-modal__content" style="position:relative;border-radius:8px;overflow:hidden;">
							<img src="<?php echo esc_url( $popup_img ); ?>" alt="<?php esc_attr_e( 'Upgrade to Pro', 'appointment-and-booking-for-gravity-forms' ); ?>" style="display:block;width:100%;height:auto;" />
							<a href="<?php echo esc_url( $popup_url ); ?>" target="_blank" rel="noopener noreferrer"
							   aria-label="<?php esc_attr_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>"
							   style="position:absolute;left:31%;top:69%;width:38%;height:15%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;text-indent:-9999px;overflow:hidden;">
								<?php esc_html_e( 'Buy Gravity Bookings', 'appointment-and-booking-for-gravity-forms' ); ?>
							</a>
							<button type="button" class="modal__close" aria-label="<?php esc_attr_e( 'Close', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:absolute;top:0;right:0;width:15%;height:12%;background:transparent;border:none;outline:none;box-shadow:none;cursor:pointer;z-index:2;"></button>
						</div>
					</div>
				</div>
				<?php
			}
			
		}

		public function register_customer_posttype() {

			// Create APBGF Customer role.
			add_role(
				'apbgf-customer', //  System name of the role.
				__( 'APBGF Customer', 'appointment-and-booking-for-gravity-forms'  ), // Display name of the role.       
				array(                              
					'read'         => true,  // true allows this capability
					'edit_posts'   => false,
					'delete_posts' => false, // Use false to explicitly deny
					'upload_files' => false
				)
			);

			$role = get_role( 'apbgf-customer' );

			if ( $role ) {
				$role->remove_cap( 'upload_files' );
			}  
			
			$labels = array(
				'name'                  => _x( 'Customer', 'Post type general name', 'appointment-and-booking-for-gravity-forms' ),
				'singular_name'         => _x( 'Customer', 'Post type singular name', 'appointment-and-booking-for-gravity-forms' ),
				'menu_name'             => _x( 'Customer', 'Admin Menu text', 'appointment-and-booking-for-gravity-forms' ),
				'name_admin_bar'        => _x( 'Customer', 'Add New on Toolbar', 'appointment-and-booking-for-gravity-forms' ),
				'add_new'               => __( 'Add Customer', 'appointment-and-booking-for-gravity-forms' ),
				'add_new_item'          => __( 'Add New Customer', 'appointment-and-booking-for-gravity-forms' ),
				'new_item'              => __( 'New Customer', 'appointment-and-booking-for-gravity-forms' ),
				'edit_item'             => __( 'Edit Customer', 'appointment-and-booking-for-gravity-forms' ),
				'view_item'             => __( 'View Customer', 'appointment-and-booking-for-gravity-forms' ),
				'all_items'             => __( 'Customers', 'appointment-and-booking-for-gravity-forms' ),
				'search_items'          => __( 'Search Customer', 'appointment-and-booking-for-gravity-forms' ),
				'parent_item_colon'     => __( 'Parent Customer:', 'appointment-and-booking-for-gravity-forms' ),
				'not_found'             => __( 'No Customer found.', 'appointment-and-booking-for-gravity-forms' ),
				'not_found_in_trash'    => __( 'No Customer found in Trash.', 'appointment-and-booking-for-gravity-forms' ),
				'featured_image'        => _x( 'Customer Cover Image', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'appointment-and-booking-for-gravity-forms' ),
				'set_featured_image'    => _x( 'Set Customer image', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'appointment-and-booking-for-gravity-forms' ),
				'remove_featured_image' => _x( 'Remove Customer image', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'appointment-and-booking-for-gravity-forms' ),
				'use_featured_image'    => _x( 'Use as Customer image', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'appointment-and-booking-for-gravity-forms' ),
				'archives'              => _x( 'Customer archives', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
				'insert_into_item'      => _x( 'Insert into Customer', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
				'uploaded_to_this_item' => _x( 'Uploaded to this Customer', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
				'filter_items_list'     => _x( 'Filter Customer list', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
				'items_list_navigation' => _x( 'Customer list navigation', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
				'items_list'            => _x( 'Customer list', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'appointment-and-booking-for-gravity-forms' ),
			);

			$args = array(
				'labels'             => $labels,
				'public'             => false,
				'publicly_queryable' => false,
				'show_ui'            => true,
				'show_in_menu'       => 'appointment-and-booking-for-gravity-forms',
				'show_in_rest'       => true,
				'query_var'          => true,
				'rewrite'            => array( 'slug' => 'apbgf-customer' ),
				'capability_type'    => 'post',
				'capabilities' => array(
					'create_posts' => false, // Removes support for the "Add New" function ( use 'do_not_allow' instead of false for multisite set ups )
				),
				'has_archive'        => true,
				'hierarchical'       => false,
				'supports'           => array( 'thumbnail' ),               
			);

			register_post_type( 'apbgf-customer', $args );
		}


		/**
		 * Singleton Class Instatnce.
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new APBGF_Customer();
			}

			return self::$instance;
		}
	}

	APBGF_Customer::get_instance();
}
