<?php
/**
 * APBGF Staff Class
 *
 * @package APBGF.
 */

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

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

		private static $checkPostType = null;

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

			add_action('init', array( $this, 'apbgf_staff_role_management' ), 10);

			// 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_staff_posttype' ), 20 );
			add_filter( 'manage_apbgf-staff_posts_columns', array( $this, 'apbgf_modify_column_names' ) );
			add_action( 'manage_apbgf-staff_posts_custom_column', array( $this, 'apbgf_add_custom_column' ), 9, 2 );

			add_action( 'wp_ajax_apbgf_edit_staff', array( $this, 'apbgf_edit_staff' ) );
			add_action( 'wp_ajax_apbgf_show_staff_data', array( $this, 'apbgf_show_staff_data' ) );
			add_action( 'wp_ajax_apbgf_add_staff_services', array( $this, 'apbgf_add_staff_services' ) );
			add_action( 'wp_ajax_apbgf_add_staff_timings', array( $this, 'apbgf_add_staff_timings' ) );


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

			if ( 'apbgf-staff' === 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-staff', '__return_empty_array' );                

				add_action( 'views_edit-apbgf-staff', 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_action( 'wp_ajax_apbgf_get_staff_by_service_and_location', array( $this, 'apbgf_get_staff_by_service_and_location' ) );
			add_action( 'wp_ajax_nopriv_apbgf_get_staff_by_service_and_location', array( $this, 'apbgf_get_staff_by_service_and_location' ) );
			
			add_action('admin_menu', array( $this, 'remove_profile_menu' ));

			add_action('wp_ajax_apbgf_open_admin_booking_form', array( $this, 'apbgf_open_admin_booking_form' ));
		}

		public function apbgf_open_admin_booking_form() {
			check_ajax_referer( 'appointment-and-booking-for-gravity-forms', 'nonce' );

			// Sanitize expected inputs
			$date       = isset( $_POST['date'] ) ? sanitize_text_field( wp_unslash( $_POST['date'] ) ) : '';
			$staff_id   = isset( $_POST['staff_id'] ) ? absint( $_POST['staff_id'] ) : 0;
			$service_id = isset( $_POST['service_id'] ) ? absint( $_POST['service_id'] ) : 0;
			$location_id = isset( $_POST['location_id'] ) ? absint( $_POST['location_id'] ) : 0;

			$daySName = strtolower( gmdate('D', strtotime($date)) );

			$data = self::get_staff_by_id( $staff_id );

			$result = array();
			$timeslots = array();

			$service_price = $data['services'][ $service_id ]['price'];
			$service_price = ( '' == $service_price ) ? APBGF_Service::get_service_by_id($service_id)['price'] : $service_price;

			if ( isset( $data['timeslots'] ) ) {
				$timeslots = $data['timeslots'][ $daySName ]['slot'];
			}

			if ( isset( $data['spl_day_timeslots'][ $date ] ) ) {
				$timeslots = $data['spl_day_timeslots'][ $date ][ $daySName ]['slot'];
			} else {
				$timeslots = ( isset($data['booking_type']) && 'fullday' == $data['booking_type'] ) ?  array( __('Fullday', 'appointment-and-booking-for-gravity-forms') ) : $timeslots;
			}

			$all_customers = APBGF_Customer::all_customer();

			$result['location'] = get_the_title($location_id);
			$result['service'] = get_the_title($service_id);
			$result['staff'] = get_the_title($staff_id);
			$result['date'] = gmdate('d F Y', strtotime($date));
			$result['timeslots'] = $timeslots;
			$result['price'] = $service_price;
			$result['customers'] = $all_customers;

			wp_send_json($result);

			wp_die();
		}


		//Remove Profile Menu from Dashboard
		public function remove_profile_menu() {
			if ( is_user_logged_in() ) {
				if ( current_user_can( 'apbgf-staff' ) && ! current_user_can( 'manage_options' ) ) {
					remove_menu_page('profile.php');
				}
			}
		}       

		// new changes
		public static function get_staff_exist() {
			$staffs = self::all_staff();
			if (count( $staffs) > 0) {
				return true;
			}
			return false;
		} 

		public function apbgf_staff_role_management() {           
			
			//remove_role('apbgf-staff');

			// Create APBGF Staff role.
			add_role(
				'apbgf-staff', //  System name of the role.
				__( 'APBGF Staff', 'appointment-and-booking-for-gravity-forms'  ), // Display name of the role.
			);

			$staff_role = get_role('apbgf-staff');

			if ( $staff_role ) {
				
				$staff_role->add_cap('read');

				$staff_role->add_cap('view_admin_dashboard');
				$staff_role->add_cap('edit_apbgf-staff');
				$staff_role->add_cap('edit_apbgf-staffs');
				$staff_role->add_cap('edit_others_apbgf-staff');
				$staff_role->add_cap('edit_others_apbgf-staffs');

				$staff_role->add_cap('edit_apbgf-appointment');
				$staff_role->add_cap('edit_apbgf-appointments');
				$staff_role->add_cap('edit_others_apbgf-appointment');
				$staff_role->add_cap('edit_others_apbgf-appointments');
			}

			$admin_role = get_role('administrator');

			if ( $admin_role ) {                
				
				$admin_role->add_cap('edit_apbgf-staff');
				$admin_role->add_cap('edit_apbgf-staffs');
				$admin_role->add_cap('edit_others_apbgf-staff');
				$admin_role->add_cap('edit_others_apbgf-staffs');

				$admin_role->add_cap('edit_apbgf-appointment');
				$admin_role->add_cap('edit_apbgf-appointments');
				$admin_role->add_cap('edit_others_apbgf-appointment');
				$admin_role->add_cap('edit_others_apbgf-appointments');
			}
		}

		public static function apbgf_get_staff_by_service_and_location_noajax( $service_id = '', $location_id = '' ) {            

			if ( '' != $service_id && 'all' != $service_id ) {
				
				$post = get_post( $service_id );                
				
				if ( $post && 'apbgf-service' == $post->post_type ) {

					if ( '' != $location_id && 'all' != $location_id ) {                        
						$check_location = array(
							'relation' => 'OR',
							array(
								'relation' => 'AND',
								array(
									'key' => 'location',
									'value' => $location_id,
									'compare' => 'LIKE'
								),
								array(
									'key' => 'services',
									'value' => $post->ID,
									'compare' => 'LIKE'
								),
							),
							array(
								'relation' => 'AND',
								array(
									'key' => 'location',
									'value' => '',
									'compare' => 'NOT EXISTS'
								),
								array(
									'key' => 'services',
									'value' => $post->ID,
									'compare' => 'LIKE'
								),
							)
						);
					} else {
						$check_location = array(
							'relation' => 'OR',
							array(
								'key' => 'services',
								'value' => $post->ID,
								'compare' => 'LIKE'
							)
						);
					}
					
					$args = apply_filters('apbgf_staffs_args', array(
						'post_type' => 'apbgf-staff',
						'posts_per_page' => -1,
						'post_status' => 'publish',                     
						'meta_query' => $check_location
					));

					$query = new WP_Query( $args );

					if ( isset( $query->posts ) && is_array( $query->posts ) && count( $query->posts ) > 0 ) {
						return $query->posts;                       
					}
					
				}
			} else {

				$staffs = self::all_staff();
				if ( is_array( $staffs ) && count( $staffs ) > 0 ) {
					return $staffs;
				}

			}

			return array();
		}

		public function apbgf_get_staff_by_service_and_location() {

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

			$response = array(              
				'status'  => 'error',
				'selected_staff_id' => ''           
			);
			
			// Whitelist and sanitize expected inputs only
			$form_id    = isset( $_REQUEST['form_id'] ) ? absint( $_REQUEST['form_id'] ) : 0;
			$post_id    = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : 0;
			$location_id= isset( $_REQUEST['location_id'] ) && 'all' !== $_REQUEST['location_id'] && 'undefined' !== $_REQUEST['location_id'] && 'null' !== $_REQUEST['location_id']
				? absint( $_REQUEST['location_id'] ) : 0;

			if ( $form_id ) {
				$form  = \GFAPI::get_form( $form_id );

				if ( is_array( $form['fields'] ) && count($form['fields']) > 0 ) {
					foreach ( $form['fields'] as $field ) {
						if ( 'apbgf_appointment_calendar' == $field->type ) {
							$response['selected_staff_id'] = $field->apbgf_staff;
							break;
						}
					}
				}
			}

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

					if ( $location_id ) {                     
						$check_location = array(
							'relation' => 'OR',
							array(
								'relation' => 'AND',
								array(
									'key' => 'location',
									'value' => $location_id,
									'compare' => 'LIKE'
								),
								array(
									'key' => 'services',
									'value' => $post->ID,
									'compare' => 'LIKE'
								),
							),
							array(
								'relation' => 'AND',
								array(
									'key' => 'location',
									'value' => '',
									'compare' => 'NOT EXISTS'
								),
								array(
									'key' => 'services',
									'value' => $post->ID,
									'compare' => 'LIKE'
								),
							)
						);
					} else {
						$check_location = array(
							'relation' => 'OR',
							array(
								'key' => 'services',
								'value' => $post->ID,
								'compare' => 'LIKE'
							)
						);
					}
					
					$args = array(
						'post_type' => 'apbgf-staff',
						'posts_per_page' => -1,
						'post_status' => 'publish',                     
						'meta_query' => $check_location
					);

					$query = new WP_Query( $args );

					if ( isset( $query->posts ) && is_array( $query->posts ) && count( $query->posts ) > 0 ) {
						// Update post_title for each staff post to ensure it has a display name
						foreach ( $query->posts as $staff_post ) {
							$display_name = self::get_staff_display_name( $staff_post->ID );
							if ( ! empty( $display_name ) && empty( trim( $staff_post->post_title ) ) ) {
								$staff_post->post_title = $display_name;
							}
						}
						$response['data'] = $query->posts;
						$response['status'] = 'success';                        
					}

					
				}
			} else {

				$staffs = self::all_staff();

				if ( is_array( $staffs ) && count( $staffs ) > 0 ) {
					// Update post_title for each staff post to ensure it has a display name
					foreach ( $staffs as $staff_post ) {
						$display_name = self::get_staff_display_name( $staff_post->ID );
						if ( ! empty( $display_name ) && empty( trim( $staff_post->post_title ) ) ) {
							$staff_post->post_title = $display_name;
						}
					}
					$response['data'] = $staffs;
					$response['status'] = 'success';
				}

			}

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

		public static function get_booking_type( $staff_id = '' ) {

			$staffData = self::get_staff_by_id( $staff_id );
			if ( isset( $staffData['booking_type'] ) ) {
				return $staffData['booking_type'];
			}   
		}

		public static function all_staff( $staff_id = '' ) {

			if ( ! empty( $staff_id ) ) {
				$get_staff = get_post( $staff_id );
				if ( $get_staff && 'apbgf-staff' == $get_staff->post_type ) {                 
					return $get_staff;
				}
			}

			$args = apply_filters('apbgf_staffs_args', array(
				'post_type' => 'apbgf-staff',
				'numberposts' => -1,                
				'status' => 'publish',
			));

			$get_staff = get_posts( $args );

			return $get_staff;
		}

		/**
		 * Get staff display name with fallback
		 * 
		 * @param int|WP_Post $staff_id Staff post ID or staff post object
		 * @return string Staff display name
		 */
		public static function get_staff_display_name( $staff_id ) {
			$staff_post = is_object( $staff_id ) ? $staff_id : get_post( $staff_id );
			
			if ( ! $staff_post || 'apbgf-staff' !== $staff_post->post_type ) {
				return '';
			}

			// First check if post_title is not empty
			$post_title = trim( $staff_post->post_title );
			if ( ! empty( $post_title ) ) {
				return $post_title;
			}

			// Fallback to user's first_name + last_name or display_name or user_login
			$user_id = get_post_meta( $staff_post->ID, 'wp_user', true );
			if ( $user_id ) {
				$user = get_userdata( $user_id );
				if ( $user ) {
					$name = trim( $user->first_name . ' ' . $user->last_name );
					if ( ! empty( $name ) ) {
						return $name;
					}
					if ( ! empty( $user->display_name ) ) {
						return $user->display_name;
					}
					return $user->user_login;
				}
			}

			return '';
		}

		public static function get_staff_by_id( $staff_id ) {

			$response = array();

			if ( ! empty( $staff_id ) ) {
				$response = get_post_meta($staff_id, 'staff_data', true );
			}

			return $response;
		}

		public static function get_staff_data_by_id( $staff_id ) {

			$response = array();

			if ( ! empty( $staff_id ) ) {
				$staff = get_post( $staff_id );

				if ( $staff && 'apbgf-staff' == $staff->post_type ) {                 
					$user_id = get_post_meta( $staff_id, 'wp_user', true );             
					$userdata = get_userdata( $user_id );
					if ( $userdata ) {
						$phone = get_post_meta( $staff_id, 'phone', true);
						$profession = get_post_meta( $staff_id, 'profession', true);
						$location = get_post_meta( $staff_id, 'location', true);
						$info = get_post_meta( $staff_id, 'info', true);
						$services = get_post_meta( $staff_id, 'services', true);
						$timings = get_post_meta( $staff_id, 'timings', true);
						$spl_timings = get_post_meta( $staff_id, 'spl_day_timings', true);
						$timezone = get_post_meta( $staff_id, 'timezone', true);
						$booking_type = ! empty(get_post_meta( $staff_id, 'booking_type', true)) ? get_post_meta( $staff_id, 'booking_type', true) : 'custom';
						$multiple_booking = 'disabled';
						$time_duration = get_post_meta( $staff_id, 'time_duration', true);
						$time_interval = get_post_meta( $staff_id, 'time_interval', true);
						$time_slots = array();
						$spl_day_time_slots = array();

						$holidays = ! empty(get_post_meta( $staff_id, 'apbgf_staff_holidays', true)) ? get_post_meta( $staff_id, 'apbgf_staff_holidays', true) : array();

						if ( is_array($timings) && count($timings) > 0 ) {                          
							foreach ( $timings as $day => $timing ) {                                
								if ( isset($timing['start']) && isset($timing['end']) ) {
									$time_slots[ $day ] = apbgf_split_time($timing['start'], $timing['end'], apply_filters('apbgf_modify_time_duration', $time_duration, $day), apply_filters('apbgf_modify_time_interval', $time_interval, $day), $timing['capacity']);
								}                       
							}
						}

						if ( is_array($spl_timings) && count($spl_timings) > 0 ) {                  
							foreach ( $spl_timings as $index => $spl_timing ) {                              
								if ( isset($spl_timing['start']) && isset($spl_timing['end']) && isset($spl_timing['date']) ) {
									// get day short name
									$daySName = strtolower( gmdate('D', strtotime($spl_timing['date'])) );
									$spl_day_time_slots[ $spl_timing['date'] ][ $daySName ] = apbgf_split_time($spl_timing['start'], $spl_timing['end'], $spl_timing['duration'], $spl_timing['interval'], $spl_timing['capacity'], $index);
								}                       
							}
						}

						$response['user_id'] = $user_id;
						$response['fname'] = $userdata->first_name;
						$response['lname'] = $userdata->last_name;
						$response['email'] = $userdata->user_email;                     
						$response['phone'] = $phone;
						$response['profession'] = $profession;
						$response['location'] = $location;
						$response['info'] = $info;
						$response['services'] = $services;
						$response['timings'] = $timings;
						$response['spl_day_timings'] = $spl_timings;
						$response['timeslots'] = $time_slots;
						$response['spl_day_timeslots'] = $spl_day_time_slots;
						$response['timezone'] = $timezone;
						$response['booking_type'] = $booking_type;
						$response['multiple_booking'] = $multiple_booking;
						$response['duration'] = $time_duration;
						$response['interval'] = $time_interval;                     
						$response['holidays'] = $holidays;                      
					}
				}
			}

			// gathered all metadata and add in one meta for better performance.
			update_post_meta($staff_id, 'staff_data', $response );
		}

		public function apbgf_show_staff_data() {

			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;
			
			if ( $post_id ) {
				$post = get_post( $post_id );

				if ( $post && 'apbgf-staff' === $post->post_type ) {

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

					if ( $userdata ) {
						$phone               = sanitize_text_field( get_post_meta( $post_id, 'phone', true ) );
						$profession          = sanitize_text_field( get_post_meta( $post_id, 'profession', true ) );
						$location            = sanitize_text_field( get_post_meta( $post_id, 'location', true ) );
						$info                = wp_kses_post( get_post_meta( $post_id, 'info', true ) );
						$services            = get_post_meta( $post_id, 'services', true );
						$timings             = get_post_meta( $post_id, 'timings', true );
						$spl_day_timings     = get_post_meta( $post_id, 'spl_day_timings', true );
						$timezone            = sanitize_text_field( get_post_meta( $post_id, 'timezone', true ) );
						$booking_type        = sanitize_text_field( get_post_meta( $post_id, 'booking_type', true ) );
						$multiple_booking    = sanitize_text_field( get_post_meta( $post_id, 'multiple_booking', true ) );
						$lead_time           = absint( get_post_meta( $post_id, 'gbf_lead_time', true ) );
						$time_duration       = absint( get_post_meta( $post_id, 'time_duration', true ) );
						$time_interval       = absint( get_post_meta( $post_id, 'time_interval', true ) );
						$holidays            = get_post_meta( $post_id, 'apbgf_staff_holidays', true );
						if ( ! is_array( $holidays ) ) {
							$holidays = array();
						}

						$time_slots = array();
						if ( is_array( $timings ) && ! empty( $timings ) ) {
							foreach ( $timings as $day => $timing ) {
								if ( isset( $timing['start'], $timing['end'], $timing['capacity'] ) ) {
									$time_slots[ $day ] = apbgf_split_time(
										sanitize_text_field( $timing['start'] ),
										sanitize_text_field( $timing['end'] ),
										apply_filters( 'apbgf_modify_time_duration', $time_duration, $day ),
										apply_filters( 'apbgf_modify_time_interval', $time_interval, $day ),
										absint( $timing['capacity'] )
									);
								}
							}
						}

						$spl_day_time_slots = array();
						if ( is_array( $spl_day_timings ) && ! empty( $spl_day_timings ) ) {
							foreach ( $spl_day_timings as $index => $spl_day_timing ) {
								if ( isset( $spl_day_timing['start'], $spl_day_timing['end'], $spl_day_timing['date'] ) ) {
									$date = sanitize_text_field( $spl_day_timing['date'] );
									$daySName = strtolower( gmdate( 'D', strtotime( $date ) ) );
									$spl_day_time_slots[ $date ][ $daySName ] = apbgf_split_time(
										sanitize_text_field( $spl_day_timing['start'] ),
										sanitize_text_field( $spl_day_timing['end'] ),
										absint( $spl_day_timing['duration'] ),
										absint( $spl_day_timing['interval'] ),
										absint( $spl_day_timing['capacity'] ),
										$index
									);
								}
							}
						}

						$response = array(
							'status'              => 'success',
							'fname'               => sanitize_text_field( $userdata->first_name ),
							'lname'               => sanitize_text_field( $userdata->last_name ),
							'email'               => sanitize_email( $userdata->user_email ),
							'phone'               => $phone,
							'profession'          => $profession,
							'location'            => $location,
							'info'                => $info,
							'services'            => $services,
							'timings'             => $timings,
							'spl_day_timings'     => $spl_day_timings,
							'time_slots'          => $time_slots,
							'spl_day_time_slots'  => $spl_day_time_slots,
							'timezone'            => $timezone,
							'booking_type'        => $booking_type ?: 'custom',
							'multiple_booking'    => $multiple_booking ?: 'disabled',
							'lead_time'           => $lead_time,
							'duration'            => $time_duration,
							'interval'            => $time_interval,
							'holidays'            => $holidays,
						);
					}
				}
			}

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


		public function delete_apbgf_staff_if_user_deleted( $user_id ) {          

			$get_staff = get_posts( array(
				'post_type' => 'apbgf-staff',
				'numberposts' => -1,
				'meta_query' => array(
					array(
						'key'   => 'wp_user',
						'value' => $user_id
					)
				)
			));         
			
			if ( isset($get_staff[0]) && $get_staff[0] ) {
				wp_delete_post( $get_staff[0]->ID, true );
			}           
		}

		public function apbgf_edit_staff() {

			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 staff 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'] ) ) : '';
			$profession = isset( $_POST['profession'] ) ? sanitize_text_field( wp_unslash( $_POST['profession'] ) ) : '';
			$phone = isset( $_POST['phone'] ) ? sanitize_text_field( wp_unslash( $_POST['phone'] ) ) : '';
			$password = isset( $_POST['password'] ) ? sanitize_text_field( wp_unslash( $_POST['password'] ) ) : '';
			if ( ! empty( $post_id ) && ! empty( trim( $fname ) ) && ! empty( trim( $lname ) ) && ! empty( trim( $email ) ) ) {

				$user = get_user_by( 'email', trim( $email ) );

				if ( ! empty( $user ) ) {

					$check_apbgf_user = get_user_meta( $user->ID, 'apbgf_user', true );

					$role = ( array ) $user->roles;
					if (in_array('administrator', $role)) {
						$response['message'] = esc_html__( 'This email address is already assigned as administrator.', 'appointment-and-booking-for-gravity-forms' );
						echo wp_json_encode( $response );
						wp_die();
					}

					if ( in_array('apbgf-staff', $role) && $check_apbgf_user != $post_id ) {
						$response['message'] = esc_html__( 'This email address is already assigned as another staff member.', 'appointment-and-booking-for-gravity-forms' );
						echo wp_json_encode( $response );
						wp_die();
					}                   
				}

				$user_id = get_post_meta( $post_id, 'wp_user', true );

				if ( ! $user_id ) {
					$response['message'] = __('WP User not found', 'appointment-and-booking-for-gravity-forms');
					echo wp_json_encode( $response );
					wp_die();
				}

				if ( $user_id ) {

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

					$args = apply_filters( 'apbgf_edit_staff_args', array(
						'ID'         => $apbgf_user,
						'post_title' => trim( $fname ) . ' ' . trim( $lname ),
						'post_type' => 'apbgf-staff',
						'post_status' => 'publish',
						'wp_error'    => true,
						'meta_input'  => array(
							'wp_user' => $user_id,
							'info' => trim( $info ),
							'profession' => trim( $profession ),
							'phone' => trim( $phone ),
							//'location' => ( isset( $data['location'] ) && is_array( $data['location'] ) && count( $data['location'] ) > 0 ) ? $data['location'] : array(),
						)
					));

					$apbgf_user = wp_update_post( $args );

					if ( ! is_wp_error( $apbgf_user ) ) {

						if ( isset( $location ) && is_array( $location ) && count( $location ) > 0 ) {
							update_post_meta( $apbgf_user, 'location', $location );
						} else {
							delete_post_meta( $apbgf_user, 'location');
							// update_post_meta( $apbgf_user, 'location', array() );
						}

						update_user_meta( $apbgf_user, 'apbgf_user', $apbgf_user );

						self::get_staff_data_by_id($apbgf_user);

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

						/* EMAIL NOTIFICATION STARTS */
						if ( true === apply_filters('apbgf_add_staff_personal_details_notification', true) ) {
							$body = __('Your account details has 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_staff_notification( $apbgf_user, $body, $password );
						}
						/* EMAIL NOTIFICATION ENDS */

					} else {

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

				} else {

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

				}

			}

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

		public function apbgf_add_staff_services() {

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

			$response = array(
				'message' => esc_html__( 'Staff services not saved.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error',
				'notification' => false
			);

			$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
            $services = isset($_POST['apbgf_staff_service']) ? $_POST['apbgf_staff_service'] : array();
			$total_staff =  self::all_staff();
			$staff = self::get_staff_by_id($post_id);
			
			if ( count( $total_staff ) > 0 && empty($staff) == true ) {
				$response['message'] = esc_html__( 'Only one staff member is allowed.', 'appointment-and-booking-for-gravity-forms' );
				$response['status'] = 'error';
				echo wp_json_encode( $response );
				wp_die();
			} else if ( ! empty( $post_id ) ) {
				
				foreach ( $services as $key => $val ) {

					if ( isset( $val['price'] ) && '' !== $val['price'] ) {
						$services[ $key ]['price'] = apbgf_normalize_price( $val['price'] );
					}

					if ( !isset($val['available']) ) {
						unset($data['apbgf_staff_service'][ $key ]);
					} /*else {
						if ( ! isset($val['price']) || (isset($val['price']) && '' == $val['price']) ) {
							$service_price = get_post_meta($key, 'price', true);
							$data['apbgf_staff_service'][$key]['price'] = $service_price;
						}
					}*/
				}

				

				update_post_meta( $post_id, 'services', $services );

				self::get_staff_data_by_id($post_id);

				$response['message'] = esc_html__('Staff services saved successfully', 'appointment-and-booking-for-gravity-forms');
				$response['status'] = 'success';                
			}

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

		public function apbgf_add_staff_timings() {

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

			$response = array(
				'message' => esc_html__( 'Staff timings not saved.', 'appointment-and-booking-for-gravity-forms' ),
				'status'  => 'error',
				'notification' => false
			);

			$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
			$apbgf_settings = APBGF_Setting::get_settings();


			$total_staff =  self::all_staff();
			$staff = self::get_staff_by_id($post_id);
			$data = $_POST;
			if ( count( $total_staff ) > 0 && empty($staff) == true ) {
				$response['message'] = esc_html__( 'Only one staff member is allowed.', 'appointment-and-booking-for-gravity-forms' );
				$response['status'] = 'error';
				echo wp_json_encode( $response );
				wp_die();
			} else if ( ! empty( $post_id ) ) {
				foreach ( $data['apbgf_staff_timing'] as $key => $val ) {
					$switch = true;
					if ( !isset($val['switch']) ) {
						$switch = false;
					}
					if ( !$switch ) {
						unset($data['apbgf_staff_timing'][ $key ]);
					} else {
						if ( empty($val['start']) || empty($val['end']) ) {
							$data['apbgf_staff_timing'][ $key ]['start'] = '00:00';
							$data['apbgf_staff_timing'][ $key ]['end'] = '23:59';
						}
						if ( ( isset($val['capacity']) && '' == $val['capacity'] ) || empty($val['capacity']) ) {
							$data['apbgf_staff_timing'][ $key ]['capacity'] = 1;
						}
					}
				}
				update_post_meta( $post_id, 'timings', $data['apbgf_staff_timing'] );
				update_post_meta( $post_id, 'timezone', $data['apbgf-timezone'] );
				if ( isset($data['booking_type']) ) {
					update_post_meta( $post_id, 'booking_type', $data['booking_type'] );
				} else {
					update_post_meta( $post_id, 'booking_type', 'custom' );
				}
				if ( isset( $data['multiple_booking'] ) && ! empty( $data['multiple_booking'] ) ) {
					update_post_meta( $post_id, 'multiple_booking', 'disabled' );
				}
				if ( isset( $data['apbgf-lead-time'] ) && ! empty( $data['apbgf-lead-time'] ) ) {
					update_post_meta( $post_id, 'gbf_lead_time', $data['apbgf-lead-time'] );
				} else {
					update_post_meta( $post_id, 'gbf_lead_time', $apbgf_settings['gbf_lead_time'] );
				}
				if ( isset( $data['apbgf-time-slot-duration'] ) && ! empty( $data['apbgf-time-slot-duration'] ) ) {
					update_post_meta( $post_id, 'time_duration', $data['apbgf-time-slot-duration'] );
				} else {
					update_post_meta( $post_id, 'time_duration', $apbgf_settings['gbf_time_duration'] );
				}
				if ( isset( $data['apbgf-time-slot-interval'] ) && '' != $data['apbgf-time-slot-interval'] ) {
					update_post_meta( $post_id, 'time_interval', $data['apbgf-time-slot-interval'] );
				} else {
					update_post_meta( $post_id, 'time_interval', $apbgf_settings['gbf_time_interval'] );
				}
				self::get_staff_data_by_id($post_id);
				$response['message'] = esc_html__('Staff timings saved successfully', 'appointment-and-booking-for-gravity-forms');
				$response['status'] = 'success';
			}

			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 ) {
				wp_delete_post($postId, true);
				return $column;
			}
			
			switch ($column) {

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

				case 'name':
			    $user_info = get_userdata($user_id);
			    if ($user_info) {
			        echo esc_html(trim($user_info->first_name . ' ' . $user_info->last_name));
			    }
			    break;

				case 'phone':
			    $phone = get_user_meta($user_id, 'phone', true); 
			    if ($phone) {
			        echo esc_html($phone);
			    } else {
			        echo '—'; // fallback if no phone is saved
			    }
			    break;
				
				case 'email':
					echo esc_attr($userdata->user_email);
					break;

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

				case 'service':
					$staff_services = get_post_meta( $postId, 'services', true );
					if ( is_array($staff_services) && count($staff_services) > 0 ) {
						echo esc_html__('Assigned', 'appointment-and-booking-for-gravity-forms');
					} else {
						echo esc_html__('Not assigned', 'appointment-and-booking-for-gravity-forms');
					}
					
					break;
				
				case 'actions':
					echo '<a href="#" data-type="staff" data-id="apbgf-staff-modal" data-post_id="' . esc_attr( $postId ) . '" class="wc-dashicons apbgf-edit"> <i class="fa fa-edit customer--icon"></i></a>';
					// if ( is_user_logged_in() ) {                
					// 	if ( current_user_can( 'manage_options' ) ) {                
					// 		if ( 'publish' == get_post_status($postId) ) {
					// 			echo '<a href="#" data-type="staff" data-post_id="' . esc_attr( $postId ) . '" class="wc-dashicons apbgf-delete" title="Delete"> <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;Staff 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['profession'] = __('Profession', 'appointment-and-booking-for-gravity-forms');
			$columns['service'] = __('Service', '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 ( is_user_logged_in() ) {                
				if ( current_user_can( 'manage_options' ) ) {
					if ( 'top' === $which ) {
						printf(
							'<a href="#" data-id="apbgf-staff-pro-modal" class="apbgf-add-button apbgf-staff-add-disabled" aria-disabled="true" title="%2$s"><i class="fa fa-plus-circle"></i>%1$s</a>',
							esc_html__( 'Add Staff', 'appointment-and-booking-for-gravity-forms' ),
							esc_attr__( 'Upgrade to Pro to add more staff', 'appointment-and-booking-for-gravity-forms' )
						);
					}
				}
			}           
		}

		public function highlight_menu() {
			//adding customer modal view file
			require_once APBGF_ADMIN_VIEW_PATH . 'modal/staff-modal.php';

			// Add Staff: SVG popup modal (button opens URL in new tab)
			$popup_img = defined( 'APBGF_IMAGE_URL' ) ? APBGF_IMAGE_URL . 'ProPopup.svg' : '';
			$popup_url = 'https://gravitybooking.com/pricing/?utm_source=plugin&utm_medium=staff';
			if ( $popup_img ) {
				?>
				<div id="apbgf-staff-pro-modal" class="modal" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Add Staff', 'appointment-and-booking-for-gravity-forms' ); ?>" style="position:fixed;inset:0;align-items:center;justify-content:center;">
					<div class="apbgf-staff-pro-modal__inner" style="position:relative;max-width:640px;width:100%;margin:auto;">
						<div class="apbgf-staff-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" class="apbgf-staff-pro-modal__cta" 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 apbgf-staff-pro-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>
				<script type="text/javascript">
					(function() {
						function apbgfStaffPopupReady(fn) {
							if (document.readyState === 'loading') {
								document.addEventListener('DOMContentLoaded', fn);
							} else {
								fn();
							}
						}
						apbgfStaffPopupReady(function() {
							var modal = document.getElementById('apbgf-staff-pro-modal');
							if (!modal) { return; }
							function closeStaffProModalOnly() {
								modal.classList.remove('apbgf-modal-show');
								var staffModal = document.getElementById('apbgf-staff-modal');
								if (staffModal && staffModal.classList.contains('apbgf-modal-show')) {
									document.body.classList.add('apbgf-modal-open');
								} else {
									document.body.classList.remove('apbgf-modal-open');
								}
							}
							// Close when clicking backdrop (the .modal element itself)
							modal.addEventListener('click', function(e) {
								if (e.target === modal) {
									closeStaffProModalOnly();
								}
							});
							// Close button (main admin script also handles .modal__close; keep body class if staff edit stays open)
							var closeBtn = modal.querySelector('.apbgf-staff-pro-modal-close');
							if (closeBtn) {
								closeBtn.addEventListener('click', function(e) {
									e.stopPropagation();
									closeStaffProModalOnly();
								});
							}
						});
					})();
				</script>
				<?php
			}
		}

		public function register_staff_posttype() {
			$labels = array(
				'name'                  => _x( 'Staff', 'Post type general name', 'appointment-and-booking-for-gravity-forms' ),
				'singular_name'         => _x( 'Staff', 'Post type singular name', 'appointment-and-booking-for-gravity-forms' ),
				'menu_name'             => _x( 'Staff', 'Admin Menu text', 'appointment-and-booking-for-gravity-forms' ),
				'name_admin_bar'        => _x( 'Staff', 'Add New on Toolbar', 'appointment-and-booking-for-gravity-forms' ),
				'add_new'               => __( 'Add Staff', 'appointment-and-booking-for-gravity-forms' ),
				'add_new_item'          => __( 'Add New Staff', 'appointment-and-booking-for-gravity-forms' ),
				'new_item'              => __( 'New Staff', 'appointment-and-booking-for-gravity-forms' ),
				'edit_item'             => __( 'Edit Staff', 'appointment-and-booking-for-gravity-forms' ),
				'view_item'             => __( 'View Staff', 'appointment-and-booking-for-gravity-forms' ),
				'all_items'             => __( 'Staff', 'appointment-and-booking-for-gravity-forms' ),
				'search_items'          => __( 'Search Staff', 'appointment-and-booking-for-gravity-forms' ),
				'parent_item_colon'     => __( 'Parent Staff:', 'appointment-and-booking-for-gravity-forms' ),
				'not_found'             => __( 'No Staff found.', 'appointment-and-booking-for-gravity-forms' ),
				'not_found_in_trash'    => __( 'No Staff found in Trash.', 'appointment-and-booking-for-gravity-forms' ),
				'featured_image'        => _x( 'Staff 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 Staff 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 Staff 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 Staff image', 'Overrides the "Use as featured image" phrase for this post type. Added in 4.3', 'appointment-and-booking-for-gravity-forms' ),
				'archives'              => _x( 'Staff 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 Staff', '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 Staff', '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 Staff 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( 'Staff 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( 'Staff 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' ),
			);

			$show_in_menu = 'appointment-and-booking-for-gravity-forms';      

			if ( is_user_logged_in() ) {                
				if ( current_user_can( 'apbgf-staff' ) && ! current_user_can( 'manage_options' ) ) {
					$show_in_menu = true;                   
				}
			}

			$args = array(
				'labels'             => $labels,
				'public'             => false,
				'publicly_queryable' => false,
				'show_ui'            => true,
				'show_in_menu'       => $show_in_menu,
				'menu_icon'          => 'dashicons-businessperson',
				'show_in_rest'       => true,
				'query_var'          => true,
				'rewrite'            => array( 'slug' => 'apbgf-staff' ),
				'capability_type'    => 'apbgf-staff',
				// '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( 'title', 'thumbnail' ),              
			);

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

		public function apbgf_filter_query( $admin_query ) {

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

				if ( is_user_logged_in() ) {
					if ( current_user_can( 'apbgf-staff' ) && ! current_user_can( 'manage_options' ) ) {
						$current_user_id = get_current_user_id();

						$cond_arr[] = array(
							array(
								'key'     => 'wp_user',
								'value'   => $current_user_id,
								'compare' => '='                                
							),
						);

						if ( isset( $cond_arr ) ) {
							$admin_query->set(
								'meta_query',
								$cond_arr
							);                          
						}                       
					}

					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;
		}


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

			return self::$instance;
		}
	}

	APBGF_Staff::get_instance();
}
