 jQuery(document).ready(function($) {
 	$('#apbgf_service_category').select2();
 	jQuery('#apbgf-user').select2({
		placeholder: "Select a Customer",
		allowClear: true,
		width: 'resolve'
	});
 });
 const swalWithBootstrapButtons = Swal.mixin({
 	customClass: {
 		confirmButton: 'apbgf-btn apbgf-btn-success',
 		cancelButton: 'apbgf-btn apbgf-btn-danger'
 	},
 	buttonsStyling: true
 });

 const datePickerAddHolidayField = document.getElementById('datepicker');
 const datePickerRemoveHolidayField = document.getElementById('datepicker-2');

 let dateRanges = [];

 const datePickerAddHolidayInvalidDate = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');
 	var flag = jQuery.inArray(current_date, dateRanges);
 	if ( flag >= 0 ) {				
 		return true;
 	}
 }

 const datePickerAddHolidayInvalidDateClass = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');
 	var flag = jQuery.inArray(current_date, dateRanges);
 	if ( flag >= 0 ) {
		//console.log(current_date);
 		return 'apbgf-day-off';
 	}
 }

 const datePickerRemoveHolidayInvalidDate = (date) => {
 	var current_date = moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD');	
 	if ( jQuery.inArray(current_date, dateRanges) < 0 ) {				
 		return true;
 	}
 }

 const datePickerAddHolidaySettings = {
 	parentEl: jQuery('#add_holidays'),
 	autoApply: false,
 	showDropdowns: true,	
 	alwaysShowCalendars: true,
 	linkedCalendars: true,		
 	opens: 'center',
 	minDate: moment(),
 	locale: {
 		format: 'DD-MM-YYYY',
 		separator: '_',
 		applyLabel: 'Add Holiday'			
 	},
 	isInvalidDate: datePickerAddHolidayInvalidDate,
 	isCustomDate: datePickerAddHolidayInvalidDateClass
 };

 const datePickerRemoveHolidaySettings = {
 	parentEl: jQuery('#remove_holidays'),
 	autoApply: false,
 	showDropdowns: true,	
 	alwaysShowCalendars: true,
 	linkedCalendars: true,		
 	opens: 'center',
 	minDate: moment(),
 	locale: {
 		format: 'DD-MM-YYYY',
 		separator: '_',
 		applyLabel: 'Remove Holiday'			
 	},
 	isInvalidDate: datePickerRemoveHolidayInvalidDate,	
 };

 const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

 function getUrlParameter(sParam) {
 	var sPageURL = window.location.search.substring(1),
 	sURLVariables = sPageURL.split('&'),
 	sParameterName,
 	i;

 	for (i = 0; i < sURLVariables.length; i++) {
 		sParameterName = sURLVariables[i].split('=');

 		if (sParameterName[0] === sParam) {
 			return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
 		}
 	}
 	return false;
 };

 jQuery( document ).ready(function($) {

	/*Email Template Accordion*/
 	$( "#accordion" ).accordion({
 		collapsible: true,
 		heightStyle: "content",
 		animate: 200	
 	});

	/*Create Booking From Admin start*/
 	$(document).on('click', '.apbgf-add-booking', function(event) {
 		event.preventDefault();
 		
 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

 		$('.apbgf-response').html('').removeClass('success error');
 		if ( $('#apbgf-booking-form').length > 0 ) {
 			
 			$(`#apbgf-booking-form #apbgf-hdn-location`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-service`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-staff`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-date`).val('');
 			$(`#apbgf-booking-form #apbgf-hdn-cost`).val('');
 			$('#apbgf-booking-form')[0].reset();
 		}

 		var current = $(this);
 		var location_id = $('.apbgf_location').val();
 		var service_id = $('.apbgf_service').val();
 		var staff_id = $('.apbgf_staff').val();
 		var date = $(current).data('date');
		
 		$(`#apbgf-booking-form #apbgf-hdn-location`).val(location_id);
 		$(`#apbgf-booking-form #apbgf-hdn-service`).val(service_id);
 		$(`#apbgf-booking-form #apbgf-hdn-staff`).val(staff_id);
 		$(`#apbgf-booking-form #apbgf-hdn-date`).val(date);		

 		var data = {
 			action: 'apbgf_open_admin_booking_form',
 			nonce: apbgf_admin.nonce,
 			date: date,
 			location_id: location_id,
 			service_id: service_id,		
 			staff_id: staff_id			
 		}

 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: data,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');
 			},
 			success: function (response) {
 				console.log(response);

 				$(`#apbgf-booking-form #apbgf-hdn-cost`).val(response.price);

 				if ( response['timeslots'] && response['timeslots'].length > 0 ) {
 					var timeslots = response['timeslots'];
 					var selectElement = document.getElementById('apbgf-time');
 					selectElement.innerHTML = '';
					// Iterate over the array and create options
 					timeslots.forEach(function(value) {
 						var option = document.createElement('option');
 						option.text = value;
 						option.value = value;
 						selectElement.appendChild(option);
 					});
 				}
 				
 				var selectElement = document.getElementById('apbgf-customer');
 				selectElement.innerHTML = '';
 				var option = document.createElement('option');
 				option.text = 'Select Customer';
 				option.value = '';
 				selectElement.appendChild(option);				
 				
 				if (response && typeof response.customers === 'object' && response.customers !== null) {
					const customers = response.customers;

					if (Object.keys(customers).length > 0) {
						for (let key in customers) {
							if (customers.hasOwnProperty(key)) {
								const option = document.createElement('option');
								option.text = customers[key];
								option.value = key;
								selectElement.appendChild(option);
							}
						}
					}
				}

 				$(`#apbgf-booking-form #apbgf-show-location`).val(response.location);
 				$(`#apbgf-booking-form #apbgf-show-service`).val(response.service);
 				$(`#apbgf-booking-form #apbgf-show-staff`).val(response.staff);
 				$(`#apbgf-booking-form #apbgf-show-date`).val(response.date);

 			},
 			complete: function() {
 				$('#apbgf-overlay').remove();
				//modal to open
 				$(`#apbgf-booking-modal`).addClass('apbgf-modal-show');	
 			},
 			error: function(errorThrown) {
	            // Handle any error that occurs during the AJAX request
 				console.log(errorThrown);
 			}
 		});		
 	});

 	$('#apbgf-add-customer').on('click', function(event) {
 		event.preventDefault();
 		$('#apbgf-customer').val('');
 		$('#apbgf_new_customer_form').toggle();
 		if ( $('#apbgf_new_customer_form').is(':visible') ) {
 			$('#apbgf-fname').val('').attr('required', true);
 			$('#apbgf-lname').val('').attr('required', true);
 			$('#apbgf-email').val('').attr('required', true);
 			$('#apbgf-email').val('').attr('pattern', '/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-]))+\.([a-zA-Z0-9]{2,4})+$/');
 		} else {
 			$('#apbgf-fname').val('').removeAttr('required', true);
 			$('#apbgf-lname').val('').removeAttr('required', true);
 			$('#apbgf-email').val('').removeAttr('required', true);
 			$('#apbgf-email').val('').removeAttr('pattern');
 		}
 	});

 	$('#apbgf-customer').on('change', function(event) {
 		if ( $(this).val() != '' ) {			
 			$('#apbgf-fname').val('').removeAttr('required');
 			$('#apbgf-lname').val('').removeAttr('required');
 			$('#apbgf-phone').val('');
 			$('#apbgf-email').val('').removeAttr('required');
 			$('#apbgf-email').val('').removeAttr('pattern');
 			$('#apbgf_new_customer_form').hide();
 		}		
 	});


	/*$('#apbgf-booking-form').validate({
		rules: {
		    // simple rule, converted to {required:true}
		    fname: {
		    	required: true
		    },
		    lname: {
		    	required: true
		    },
		    email: {
		    	required: true,
		    	email: true
		    },	    
		},
		highlight: function(element, errorClass) {			
			$(element).addClass('errorBorder');	
		},
		success: function (label, element) {
			$(element).removeClass('errorBorder');
		},
		submitHandler: function( form ) {			
			event.preventDefault();

			var action = 'apbgf_create_booking_admin';

			var formData = $(form).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;

			$.ajax({
				url: apbgf_admin.ajaxurl,
				type: 'POST',
				data: formData,
				beforeSend: function() {
					$('body').append('<div id="apbgf-overlay" />');				
				},
				success: function (response) {
					// var response = $.parseJSON(response);
					console.log(response);
					$('#apbgf-overlay').remove();
					swalWithBootstrapButtons.fire(
			      		response.status,
			      		response.message,
			      		response.status
			    	).then((result) => {
			    		location.reload();
			    	});
				},
				complete: function() {
					
				}
			});
		}

	});*/

 	$('#apbgf-booking-form').on('submit', function(event) {
 		event.preventDefault();

 		var action = 'apbgf_create_booking_admin';

 		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;

 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');				
 			},
 			success: function (response) {
				// var response = $.parseJSON(response);
 				console.log(response);
 				$('#apbgf-overlay').remove();
 				swalWithBootstrapButtons.fire(
 					response.status,
 					response.message,
 					response.status
 					).then((result) => {
 						location.reload();
 					});
 				},
 				complete: function() {
 					
 				}
 			});
 	});
	/*Create Booking From Admin end*/


	//Email Template settings
 	$('#app_notification_form').on('submit', function(event) {
 		event.preventDefault();

 		var action = 'apbgf_email_template_settings';

 		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function() {
 				$('body').append('<div id="apbgf-overlay" />');				
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
				// console.log(response);
 				$('#apbgf-overlay').remove();
 				swalWithBootstrapButtons.fire(
 					response.status,
 					response.message,
 					response.status
 					);
 			},
 			complete: function() {
 				
 			}
 		});
 	});

	/*Dashboard Filters Starts*/

 	var start = '';
 	var end = '';

 	function applyFilterRange(start = '', end = '', flag = false) {    	
 		$('#reportrange span').html(`Select date to filter appointments`);    	
 		if ( start != '' && end != '' ) {    		
 			if ( flag ) {	        	
 				$('#reportrange span').html(`${moment(start, 'YYYY-MM-DD').format('MMMM D, YYYY')} - ${moment(end, 'YYYY-MM-DD').format('MMMM D, YYYY')}`);	        	
 			} else {	        	
 				$('#reportrange span').html(`Select date to filter appointments`);	        	
 			}
 		}
 		$('#reportrange').css({'visibility': 'visible', 'opacity': 1});      
 	}

 	$('#reportrange').daterangepicker({
 		start: moment(),
 		end: moment(),
 		ranges: {           
 			'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
 			'Today': [moment(), moment()],
 			'Tomorrow': [moment().add(1, 'days'), moment().add(1, 'days')],
 			'This Week': [moment(), moment().add(6, 'days')],           
 			'Last Week': [moment().subtract(7, 'days'), moment().subtract(1, 'days')],
 			'This Month': [moment().startOf('month'), moment().endOf('month')],
 			'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
 			'This Year': [moment().startOf('year'), moment().endOf('year')],           
 			'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
 		}
 	}, applyFilterRange);

 	$(document).on('click', '.ranges ul li', function() {

 	});

 	var url_start = $.trim( getUrlParameter('date_from') );
 	var url_end = $.trim(getUrlParameter('date_to'));
 	console.log('url_start', url_start);
 	console.log('url_end', url_end);
 	if ( url_start != '' && url_end != '' && url_start != 'true' && url_end != 'true' && url_start != 'false' && url_end != 'false' ) {
 		console.log('test1');	
 		applyFilterRange(url_start, url_end, true);
 	} else {		
 		console.log('test2');
 		applyFilterRange(start, end, false);
 	}    

 	$('#reportrange').on('apply.daterangepicker', function(ev, picker) {    	
 		$('#reportrange span').html(picker.startDate.format('MMMM D, YYYY') + ' - ' + picker.endDate.format('MMMM D, YYYY'));
 		$('input[name="date_from"]').val(picker.startDate.format('YYYY-MM-DD'));
 		$('input[name="date_to"]').val(picker.endDate.format('YYYY-MM-DD'));
 		$('#post-query-submit').click();
 	});

	/*Dashboard Filters End*/

	// Add Placeholder To Search Box
 	jQuery('.search-box input[type=search]').attr('placeholder', 'Search');

 	if ( $(datePickerAddHolidayField).length > 0 ) {
		//Init calendar again
 		$(datePickerAddHolidayField).daterangepicker(datePickerAddHolidaySettings);
 		$(datePickerRemoveHolidayField).daterangepicker(datePickerRemoveHolidaySettings);
 	}

 	$(".close_icon").click(function(){
 		$(".gf_booking_sidebar").removeClass("activesidebar");
 		$(".gf_booking_overlayDiv").removeClass("active");
 	});
 	$("#gf_booking_cardOne").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(".gf_booking_general--inner").removeClass("closed");
 		$(".gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_compnay_detail, .gf_booking_google_calander, .gf_booking_email_configuration, .gf_booking_outlook_calender").addClass("closed");
 	});
 	$("#gf_booking_cardtwo").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(".gf_booking_general--inner,  .gf_booking_apointments_listing, .gf_booking_email_configuration, .gf_booking_google_calander, .gf_booking_compnay_detail, .gf_booking_outlook_calender").addClass("closed");
 		$(".gf_booking_display--inner").removeClass("closed");
 		
 	});
 	$("#gf_bookings_appointments").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");					
		$(".gf_booking_overlayDiv").addClass("active");																																					// new changes		
		$(".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_email_configuration, .gf_booking_google_calander, .gf_booking_compnay_detail, .gf_booking_outlook_calender").addClass("closed");
		$(".gf_booking_apointments_listing").removeClass("closed");
		$(".close_icon").css("display","block");
	});
 	$("#gf_booking_company_detail").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");																																						// new changes
		$(".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_email_configuration, .gf_booking_google_calander, .gf_booking_outlook_calender").addClass("closed");
		$(".gf_booking_compnay_detail").removeClass("closed");
		$(".close_icon").css("display","block");
	});

 	$("#gf_booking_email_configuration").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");														  																							// new changes	
		$(".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_compnay_detail, .gf_booking_google_calander, .gf_booking_outlook_calender").addClass("closed");
		$(".gf_booking_email_configuration").removeClass("closed");
		$(".close_icon").css("display","block");
	});
	// google integration
 	$("#gf_booking_google_calender").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
		$(".gf_booking_overlayDiv").addClass("active");																																						// new changes
		$(".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_compnay_detail, .gf_booking_email_configuration, .gf_booking_outlook_calender").addClass("closed");
		$(".gf_booking_google_calander").removeClass("closed");
		// $(".close_icon").css("display","none");
	});

 	$("#gf_booking_outlook_calender").click(function(){
 		$(".gf_booking_sidebar").addClass("activesidebar");
 		$(".gf_booking_overlayDiv").addClass("active");
 		$(".gf_booking_general--inner, .gf_booking_display--inner, .gf_booking_apointments_listing, .gf_booking_compnay_detail, .gf_booking_email_configuration, .gf_booking_google_calander").addClass("closed");
 		$(".gf_booking_outlook_calender").removeClass("closed");
		// $(".close_icon").css("display","none");
 	});

 	$(".gf_booking_overlayDiv").click(function(){
 		$(".gf_booking_overlayDiv").removeClass("active");
 		$(".gf_booking_sidebar").removeClass("activesidebar");
 	});

	//initializing select2
 	$('#apbgf-location').select2();

	//initializing staff time slot break select2
 	$('.apbgf-slot-break').select2();

	//staff time slot break div show hide
 	$(document).on('click', '.add-break-btn > span', function() {
 		var id = $(this).data('id');
 		$(`#break-${id}`).toggleClass('form-time-slots-break-box-show');
 	});

	//Trigger to open modal 
	// add staff
 	$('.apbgf-add-button').on('click', function(event) {
 		event.preventDefault();
 		var id = $(this).data('id');
 		var isStaffProPopup = ( id === 'apbgf-staff-pro-modal' );

 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

 		if ( ! isStaffProPopup ) {
 			$('.apbgf-response').html('').removeClass('success error');
 			$('.modal--form')[0].reset();
 			if ( $('#apbgf-location').length > 0 ) {
 				$('#apbgf-location').trigger('change');	
 			}

 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				
 				if ( $('#apbgf-location').length > 0 ) {
 					$('#apbgf-location').trigger('change');	
 				}

 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);


 			if ( $('.post_id').length > 0 ) {
 				$('.post_id').val('');
 			}
 		}
		//modal to open
 		$(`#${id}`).addClass('apbgf-modal-show');

		// new changes
		/**
		console.log(id =='apbgf-staff-modal' && apbgf_admin.staff_exists == true);
		if(id =='apbgf-staff-modal' && apbgf_admin.staff_exists == true) {
			$(`#${id}`).addClass('apbgf-pro-modal-show');

		}
		else {

			$(`#${id}`).addClass('apbgf-modal-show');


		}
			 */

 		if ( ! isStaffProPopup && $(datePickerAddHolidayField).length > 0 ) {
			//destroy the calendar
 			$(datePickerAddHolidayField).data('daterangepicker').remove();
 			$(datePickerRemoveHolidayField).data('daterangepicker').remove();
 			
	   		//Init calendar again
 			$(datePickerAddHolidayField).daterangepicker(datePickerAddHolidaySettings);
 			$(datePickerRemoveHolidayField).daterangepicker(datePickerRemoveHolidaySettings);

	   		//open calendar again
 			$(datePickerAddHolidayField).trigger('click');
 			$(datePickerRemoveHolidayField).trigger('click');
 		}
 	});

	//Trigger to close modal
 	$('.modal__close').on('click', function (e) {
 		e.preventDefault();
 		if ( $('.post_id').length > 0 ) {
 			$('.post_id').val('');
 		}

 		window.scrollTo({top: 0});
 		$('body').removeClass('apbgf-modal-open');

		// $(this).siblings('.modal--form')[0].reset();		
 		if ( $('.modal--form').length > 0 ) {			
 			$('.apbgf-response').html('').removeClass('success error');
 			$('.modal--form')[0].reset();

 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				if ( $('#apbgf-location').length > 0 ) {
 					$('#apbgf-location').val(null).trigger('change');	
 				}
 				
 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);
 		}
 		$('.modal').removeClass('apbgf-modal-show');
		// new changes
		// $('.modal').removeClass('apbgf-pro-modal-show');

 	});

	// Staff modal: clicking any disabled element or disabled section opens SVG pro popup
	// Note: some "disabled-looking" controls are implemented via CSS classes, and some areas (labels/containers)
	// are not the disabled element itself — so we detect disabled state by proximity.
	$(document).on('click pointerdown mousedown touchstart', '#apbgf-staff-modal', function(e) {
		if ( $('#apbgf-staff-pro-modal').length === 0 ) {
			return;
		}
		// Only trigger from inside the open staff modal (not when opening it).
		if ( ! $('#apbgf-staff-modal').hasClass('apbgf-modal-show') ) {
			return;
		}
		var $target = $(e.target);
		// Don't hijack close clicks.
		if ( $target.closest('.modal__close').length > 0 ) {
			return;
		}

		var $closestFormCol = $target.closest('#apbgf-staff-modal .form-col-full');
		var isTimingDisabledContainer =
			$closestFormCol.find('#apbgf-duration.form-time-slots-disabled, #apbgf-interval.form-time-slots-disabled').length > 0;

		var isStartEndDisabled =
			$target.closest('.form-start-time-slots.form-time-slots-disabled, .form-end-time-slots.form-time-slots-disabled').length > 0;

		var isDisabledZone =
			$target.closest('#apbgf-multiple_booking, #apbgf-lead-time-container, .form-time-slots-disabled, .disabled-block').length > 0 ||
			isTimingDisabledContainer ||
			isStartEndDisabled ||
			$target.is('[disabled]');

		if ( isDisabledZone ) {
			e.preventDefault();
			e.stopPropagation();
			$('body').addClass('apbgf-modal-open');
			$('#apbgf-staff-pro-modal').addClass('apbgf-modal-show');
		}
	});

	// Capture-phase handler: attached ONLY to the staff modal so it can't interfere with list-table edit icon clicks.
	// Needed for <input type="time"> which can swallow bubbling events.
	(function() {
		var staffModal = document.getElementById('apbgf-staff-modal');
		if (!staffModal) { return; }

		function openStaffProModal() {
			jQuery('body').addClass('apbgf-modal-open');
			jQuery('#apbgf-staff-pro-modal').addClass('apbgf-modal-show');
		}

		function isDisabledZoneTarget(target) {
			var proModal = document.getElementById('apbgf-staff-pro-modal');
			if (!proModal) { return false; }
			if (!staffModal.classList.contains('apbgf-modal-show')) { return false; }
			if (!staffModal.contains(target)) { return false; }
			if (target.closest && target.closest('.modal__close')) { return false; }

			var inDisabledZone =
				(target.closest && target.closest('#apbgf-multiple_booking, #apbgf-lead-time-container, .form-time-slots-disabled, .disabled-block')) ||
				(target.closest && target.closest('.form-start-time-slots.form-time-slots-disabled, .form-end-time-slots.form-time-slots-disabled')) ||
				(target.matches && target.matches('[disabled]'));

			if (!inDisabledZone && target.closest) {
				var col = target.closest('#apbgf-staff-modal .form-col-full');
				if (col && col.querySelector('#apbgf-duration.form-time-slots-disabled, #apbgf-interval.form-time-slots-disabled')) {
					inDisabledZone = true;
				}
			}

			return !!inDisabledZone;
		}

		function captureHandler(e) {
			if (isDisabledZoneTarget(e.target)) {
				e.preventDefault();
				e.stopPropagation();
				openStaffProModal();
			}
		}

		['pointerdown', 'mousedown', 'touchstart', 'click'].forEach(function(evt) {
			staffModal.addEventListener(evt, captureHandler, true);
		});
	})();

 	$('#apbgf-booking_type').on('change', function() {
 		if ( 'fullday' == $(this).val() ) {
 			$('#apbgf-lead-time-container').hide();
 			$('form#apbgf-staff-form-timings .form-start-time-slots, form#apbgf-staff-form-timings .form-end-time-slots, form#apbgf-staff-form-timings .add-break-btn, form#apbgf-staff-form-timings #apbgf-duration, form#apbgf-staff-form-timings #apbgf-interval').addClass('form-time-slots-disabled');
 		} else {
 			$('#apbgf-lead-time-container').show();
 			$('#apbgf-staff-form-timings .form-start-time-slots, #apbgf-staff-form-timings .form-end-time-slots, #apbgf-staff-form-timings .add-break-btn, #apbgf-staff-form-timings #apbgf-duration, #apbgf-staff-form-timings #apbgf-interval').removeClass('form-time-slots-disabled');
 		}
 	});

 	$(document).on('click pointerdown', '.apbgf-pro-trigger', function(e) {
		var modalId = $(this).data('apbgf-pro-modal') || 'apbgf-pro-modal';
		var $modal = $(`#${modalId}`);
		if ( $modal.length === 0 ) {
			return;
		}
		e.preventDefault();
		e.stopPropagation();
		$('body').addClass('apbgf-modal-open');
		if ( $modal.hasClass('apbgf-pro-modal') ) {
			$modal.show();
		} else {
			$modal.addClass('apbgf-modal-show');
		}
	});

 	$('.form-time-slots-content-row .apbgf_staff_time_toggle').on('click', function() {		
 		if ( $(this).is(':checked') ) {
 			$(this).parents('.form-time-slots-content-row').find('.form-slots-capacity').removeClass('form-time-slots-disabled');
 		} else {
 			$(this).parents('.form-time-slots-content-row').find('.form-slots-capacity').addClass('form-time-slots-disabled');
 		}
 	});

	// $(document).on('click', '.remove_spl_date', function(event) {
 	
	// 	$(this).parents('.spl_day_repeater_block').remove();
	// 	var len = $('#spl_day_repeater_wrapper').find('.spl_day_repeater_block').length;

	// 	$('#spl_day_repeater_wrapper > div.spl_day_repeater_block').each(function(i, v) {
	// 		$(this).data('id', i);
	// 	});
	// });

	// $('#add_spl_date').on('click', function(event) {

	// 	event.preventDefault();

	// 	var len = $('#spl_day_repeater_wrapper').find('.spl_day_repeater_block').length;

	// 	if ( len == 0 || 'undefined' == len ) {
	// 		len = 0;
	// 	}

	// 	$('#spl_day_repeater_wrapper').append(`
	// 		<div class="spl_day_repeater_block" data-id="${len}">
	// 			<div class="form-col-full">
    //                 <input type="number" class="apbgf-spl-duration" name="apbgf_staff_spl_day_timing[${len}][duration]" min="1" data-general="${apbgf_admin.time_duration}" value="${apbgf_admin.time_duration}">
    //                 <small>${apbgf_admin.durationHelpTxt}</small>
    //             </div>
    //             <div class="form-col-full">                                
    //                 <input type="number" class="apbgf-spl-interval" name="apbgf_staff_spl_day_timing[${len}][interval]" min="0" data-general="${apbgf_admin.time_interval}" value="${apbgf_admin.time_interval}">
    //                 <small>${apbgf_admin.intervalHelpTxt}</small>
    //             </div>
	//             <div class="form-time-slots-content-row">
	//                 <div class="form-start-time-slots">
	//                     <input type="time" name="apbgf_staff_spl_day_timing[${len}][start]" class="apbgf_staff_spl_event_start" data-id="${len}">
	//                     <small>${apbgf_admin.startTimeLbl}</small>
	//                 </div>
	//                 <div class="form-end-time-slots">
	//                     <input type="time" name="apbgf_staff_spl_day_timing[${len}][end]" class="apbgf_staff_spl_event_end" data-id="${len}">
	//                     <small>${apbgf_admin.endTimeLbl}</small>
	//                 </div>
	//                 <div class="form-end-time-slots">
	//                     <input type="date" name="apbgf_staff_spl_day_timing[${len}][date]" class="apbgf_staff_spl_event_date">
	//                     <small>${apbgf_admin.dateLbl}</small>
	//                 </div>
	//                 <div class="form-slots-capacity">
	//                     <input type="number" name="apbgf_staff_spl_day_timing[${len}][capacity]" class="apbgf_staff_spl_event_capacity" min="1">
	//                     <small>${apbgf_admin.capacityLbl}</small>
	//                 </div>
	//                 <div class="add-break-btn">
	//                 	<span class="remove_spl_date"><i class="fa fa-minus-circle"></i> ${apbgf_admin.removeSlotTxt}</span>
	//                     <span data-id="${len}"><i class="fa fa-plus-circle"></i> ${apbgf_admin.addBreakTxt}</span>
	//                 </div>
	//             </div>
	//             <div id="break-${len}" class="form-time-slots-break-box">
	//                 <div class="form-col-full">
	//                     <label for="add-break">${apbgf_admin.addBreakTxt}</label>
	//                     <select name="apbgf_staff_spl_day_timing[${len}][break][]" id="apbgf_staff_timing_${len}_break" class="apbgf-slot-break" multiple></select>
	//                 </div>
	//             </div>
	//         </div>
	// 	`);

	// 	//initializing staff time slot break select2
	// 	$('.apbgf-slot-break').select2();
	// });

 	$('.apbgf-edit').on('click', function(e) {
 		e.preventDefault();
 		var id = $(this).data('id');
 		var post_id = $(this).data('post_id');
 		var type = $(this).data('type');
 		var action = '';

 		window.scrollTo({top: 0});
 		$('body').addClass('apbgf-modal-open');

		//resetting previous values.
 		if ( $('.modal--form').length > 0 ) {
 			$('.apbgf-response').html('').removeClass('success error');
 			$('.modal--form')[0].reset();
 			if ( $('#apbgf-staff-form-details').length > 0 ) {
 				$('#apbgf-staff-form-details')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-services').length > 0 ) {
 				$('#apbgf-staff-form-services')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-timings').length > 0 ) {
 				$('#apbgf-staff-form-timings')[0].reset();
 			}

 			if ( $('#apbgf-staff-form-spl-day').length > 0 ) {
 				$('#apbgf-staff-form-spl-day')[0].reset();
 			}

 			$('input[type=checkbox]').prop('checked', false);
 		}

 		if ( post_id != '' && type != '' && id != '' ) {

 			if ( 'location' == type ) {
 				action = 'apbgf_show_location_data';
 			}

 			if ( 'staff' == type ) {
 				action = 'apbgf_show_staff_data';
 			}

 			if ( 'customer' == type ) {
 				action = 'apbgf_show_customer_data';
 			}

 			if ( 'service' == type ) {
 				action = 'apbgf_show_service_data';
 			}

 			if ( 'appointment' == type ) {
 				action = 'apbgf_show_appointment_data';
 			}

 			$.ajax({
 				url: apbgf_admin.ajaxurl,
 				type: 'POST',
 				data: `post_id=${post_id}&action=${action}&nonce=${apbgf_admin.nonce}`,
 				beforeSend: function() {
 					$('body').append('<div id="apbgf-overlay" />');
 				},
 				success: function (response) {
 					var response = $.parseJSON(response);
 					if ( 'success' == response.status ) {
 						if ( $('.post_id').length > 0 ) {
 							$('.post_id').val(post_id);
 						}
 						
 						if ( 'appointment' != type ) {
 							$.each( response, function(i, v) {								
								// console.log(i);
								// console.log(v);
 								if ( $(`#apbgf-${i}`).length > 0 ) {
 									if ( 'multiple_booking' == i ) {										
 										$('input[name="multiple_booking"]').removeAttr('checked');
 										$(`#apbgf-multiple_booking-${v}`).prop('checked', true);
 									} else if ( 'duration' == i || 'interval' == i ) {
 										$(`#apbgf-${i}`).val(v);
 									} else {
 										$(`#apbgf-${i}`).val(v).trigger('change');
 									}
 								}

								//if action is for staff so we will check for staff services
 								if ( 'services' === i ) {
									// console.log(v);
 									$.each( v, function(ii, vv) {
 										if ( $(`#apbgf_staff_service_aval_${ii}`).length > 0 ) {
 											$(`#apbgf_staff_service_aval_${ii}`).prop('checked', true);
 											$(`#apbgf_staff_service_price_${ii}`).val(vv.price);
 										}
 									});
 								}
 								console.log( response );
								//if action is for staff so we will check for staff services
 								if ( 'timings' === i ) {
 									$('#apbgf-booking_type').trigger('change');
 									$('#apbgf-lead-time').val( response.lead_time );
 									$.each( v, function(ii, vv) {								
 										if ( $(`#apbgf_staff_timing_${ii}_start`).length > 0 ) {
 											if ( '1' == vv.switch ) {
 												$(`#apbgf_staff_timing_${ii}_switch`).prop('checked', true);
 											}											
 											$(`#apbgf_staff_timing_${ii}_start`).val(vv.start);
 											$(`#apbgf_staff_timing_${ii}_end`).val(vv.end);
 											$(`#apbgf_staff_timing_${ii}_capacity`).val(vv.capacity);

											// $.each( vv.break, function( iii, vvv ) {
											// 	$(`#apbgf_staff_timing_${ii}_break`).val(vv.capacity);
											// });										
 										}
 									});
 								}

 								if ( 'time_slots' === i ) {
 									
 									if ( $(`#apbgf-staff-form-timings .apbgf-slot-break`).length > 0 ) {
 										$(`#apbgf-staff-form-timings .apbgf-slot-break`).html('');
 									}

 									$.each( v, function(ii, vv) {
 										if ( $(`#apbgf_staff_timing_${ii}_break`).length > 0 ) {											
 											$.each( vv.slot, function( xx, yy ) {												
 												var selected = false;
 												if ( $.inArray(vv.start[xx], response.timings[ii].break) >= 0 ) {
 													var selected = true;
 												}
 												
												// console.log( `${ii} set as break ${vv.start[xx]} - ${selected}`);

 												$(`#apbgf_staff_timing_${ii}_break`).append($('<option>', {												
 													value: vv.start[xx],
 													text: yy,
 													selected: selected
 												}));												
 											});
 										}
 									});
 								}

								//if action is for staff so we will check for staff spl day timings
 								if ( 'spl_day_timings' === i ) {
									// console.log(v);
									//empty before adding looping block
 									$('#spl_day_repeater_wrapper').html('');
 									var spl_time_slots = response.spl_day_time_slots;
 									console.log('spl_time_slots before: ', spl_time_slots);
 									$.each( v, function(ii, vv) {
 										console.log('vv.date: ', vv.date);
 										if ( typeof vv.date != 'undefined' ) {
 											var date = new Date(vv.date);
 											var dayName = date.toLocaleString('en-US', { weekday: 'short' }).toLowerCase();
											console.log(dayName); // Output: Thu
											var spl_day_time_slots = spl_time_slots[vv.date][dayName];
											console.log('spl_day_time_slots after: ', spl_day_time_slots);                                    	

											$('#spl_day_repeater_wrapper').append(`
												<div class="spl_day_repeater_block" data-id="${ii}">
													<div class="form-col-full">
									                    <input type="number" class="apbgf-spl-duration" name="apbgf_staff_spl_day_timing[${ii}][duration]" min="1" data-general="${apbgf_admin.time_duration}" placeholder="${apbgf_admin.time_duration}" value="${vv.duration}">
									                    <small>${apbgf_admin.durationHelpTxt}</small>
									                </div>
									                <div class="form-col-full">                                
									                    <input type="number" class="apbgf-spl-interval" name="apbgf_staff_spl_day_timing[${ii}][interval]" min="0" data-general="${apbgf_admin.time_interval}" placeholder="${apbgf_admin.time_interval}" value="${vv.interval}">
									                    <small>${apbgf_admin.intervalHelpTxt}</small>
									                </div>   
		                                            <div class="form-time-slots-content-row">   
		                                                <div class="form-start-time-slots">
		                                                    <input type="time" name="apbgf_staff_spl_day_timing[${ii}][start]" class="apbgf_staff_spl_event_start" data-id="${ii}" value="${vv.start}">
		                                                    <small>${apbgf_admin.startTimeLbl}</small>
		                                                </div>
		                                                <div class="form-end-time-slots">
		                                                    <input type="time" name="apbgf_staff_spl_day_timing[${ii}][end]" class="apbgf_staff_spl_event_end" data-id="${ii}" value="${vv.end}">
		                                                    <small>${apbgf_admin.endTimeLbl}</small>
		                                                </div>
		                                                <div class="form-end-time-slots">
		                                                    <input type="date" name="apbgf_staff_spl_day_timing[${ii}][date]" class="apbgf_staff_spl_event_date" value="${vv.date}">
		                                                    <small>${apbgf_admin.dateLbl}</small>
		                                                </div>
		                                                <div class="form-slots-capacity">
		                                                    <input type="number" name="apbgf_staff_spl_day_timing[${ii}][capacity]" class="apbgf_staff_spl_event_capacity" min="1" value="${vv.capacity}">
		                                                    <small>${apbgf_admin.capacityLbl}</small>
		                                                </div>
		                                                <div class="add-break-btn">
		                                                	<span class="remove_spl_date"><i class="fa fa-minus-circle"></i> ${apbgf_admin.removeSlotTxt}</span>
		                                                    <span data-id="${ii}"><i class="fa fa-plus-circle"></i> ${apbgf_admin.addBreakTxt}</span>
		                                                </div>
		                                            </div>
		                                            <div id="break-${ii}" class="form-time-slots-break-box">
		                                                <div class="form-col-full" id="selectBreakWrapper_${ii}">
		                                                    <label for="add-break">${apbgf_admin.addBreakTxt}</label>
		                                                    <select name="apbgf_staff_spl_day_timing[${ii}][break][]" id="apbgf_staff_timing_${ii}_break" class="apbgf-slot-break" multiple></select>
		                                                </div>
		                                            </div>
		                                        </div>
											`);

											$.each(spl_day_time_slots.slot, function(index, slot) {	

												var selected = false;
	                                    		// console.log( 'response.spl_day_timings', response.spl_day_timings );
	                                    		// console.log( 'ii', ii );
	                                    		// console.log( 'spl_day_time_slots.slot[index]', spl_day_time_slots.start[index] );
												if ( $.inArray(spl_day_time_slots.start[index], response.spl_day_timings[ii].break) >= 0 ) {
													var selected = true;
												}
												
												$(`#apbgf_staff_timing_${ii}_break`).append($('<option>', {
													value: spl_day_time_slots.start[index],
													text:  slot,
													selected: selected
												}));
											});

											//initializing staff time slot break select2
											$(`#apbgf_staff_timing_${ii}_break`).select2();
										}
									});
}

if ( 'holidays' === i ) {
	
	if ( $(datePickerAddHolidayField).length > 0 ) {
										//destroy the calendar
		$(datePickerAddHolidayField).data('daterangepicker').remove();
		$(datePickerRemoveHolidayField).data('daterangepicker').remove();

		dateRanges = v;
								   		//Init calendar again
		$(datePickerAddHolidayField).daterangepicker(datePickerAddHolidaySettings);
		$(datePickerRemoveHolidayField).daterangepicker(datePickerRemoveHolidaySettings);

								   		//open calendar again
		$(datePickerAddHolidayField).trigger('click');
		$(datePickerRemoveHolidayField).trigger('click');
	}
}
});
						} else { //only for appointment type
							console.log(response);
							$.each( response, function(i, v) {
								if ( 'status' !== i  ) {
									$(`#${i}`).html(v);
								}
							});
						}

						//modal to open
						$(`#${id}`).addClass('apbgf-modal-show');

					} else {
						swalWithBootstrapButtons.fire(
							'No User Found!',
							'',
							response.status
							);
					}
				},
				complete: function() {
					$('#apbgf-overlay').remove();
				}
			});
}
});

 $('.apbgf-delete').on( 'click', function( event ) {
 	event.preventDefault();
 	var type = $(this).data('type');
 	var post_id = $(this).data('post_id');
 	var action = '';

 	if ( 'location' == type ) {
 		action = 'apbgf_delete_location';
 	}

 	if ( 'staff' == type ) {
 		action = 'apbgf_delete_staff';
 	}

 	if ( 'customer' == type ) {
 		action = 'apbgf_delete_customer';
 	}

 	if ( 'service' == type ) {
 		action = 'apbgf_delete_service';
 	}

 	if ( 'appointment' == type ) {
 		action = 'apbgf_delete_appointment';
 	}

 	swalWithBootstrapButtons.fire({
 		title: 'Are you sure?',
 		text: "You won't be able to revert this!",
 		icon: 'warning',
 		showCancelButton: true,
 		confirmButtonText: 'Yes, delete it!',
 		cancelButtonText: 'No, cancel!',
 		reverseButtons: true
 	}).then((result) => {
 		if (result.isConfirmed) {
 			$.ajax({
 				url: apbgf_admin.ajaxurl,
 				type: 'POST',
 				data: `post_id=${post_id}&action=${action}&nonce=${apbgf_admin.nonce}`,
 				beforeSend: function() {
 					$('body').append('<div id="apbgf-overlay" />');
 				},
 				success: function (response) {
 					var response = $.parseJSON(response);
 					if ( 'success' == response.status ) {
 						swalWithBootstrapButtons.fire(
 							'Deleted!',
 							response.message,
 							response.status
 							).then((result) => {
 								location.reload();
 							});
 						} else {
 							swalWithBootstrapButtons.fire(
 								'Not deleted!',
 								response.message,
 								response.status
 								);
 						}
 					},
 					complete: function() {
 						$('#apbgf-overlay').remove();
 					}
 				});
 		} else if (result.dismiss === Swal.DismissReason.cancel) {
 			swalWithBootstrapButtons.fire(
 				'Cancelled',
 				'',
 				'error'
 				)
 		}
 	});

 });

 $('.apbgf-appointment-status').on( 'change', function( event ) {
 	event.preventDefault();		
 	var post_id = $(this).data('post_id');
 	var status = $(this).val();
 	var action = 'apbgf_change_appointment_status';

 	if ( ''!== post_id ) {
 		swalWithBootstrapButtons.fire({
 			title: 'Are you sure?',
 			text: "You want to change the appointment status",
 			icon: 'warning',
 			showCancelButton: true,
 			confirmButtonText: 'Yes, Change it!',
 			cancelButtonText: 'No, cancel!',
 			reverseButtons: true
 		}).then((result) => {
 			if (result.isConfirmed) {
 				$.ajax({
 					url: apbgf_admin.ajaxurl,
 					type: 'POST',
 					data: `post_id=${post_id}&status=${status}&action=${action}&nonce=${apbgf_admin.nonce}`,
 					beforeSend: function() {
 						$('body').append('<div id="apbgf-overlay" />');
 					},
 					success: function (response) {
 						var response = $.parseJSON(response);
 						if ( 'success' == response.status ) {
 							swalWithBootstrapButtons.fire(
 								'Changed!',
 								response.message,
 								response.status
 								).then((result) => {
 									location.reload();
 								});
 							} else {
 								swalWithBootstrapButtons.fire(
 									'Not Changed!',
 									response.message,
 									response.status
 									);
 							}
 						},
 						complete: function() {
 							$('#apbgf-overlay').remove();
 						}
 					});
 			} else if (result.dismiss === Swal.DismissReason.cancel) {
 				swalWithBootstrapButtons.fire(
 					'Cancelled',
 					'',
 					'error'
 					)
 			}
 		});
 	}	
 });

 $('.apbgf_show_reason').on('click', function(e) {
 	e.preventDefault();
 	var reason = $(this).data('reason');
 	if ( $.trim( reason ) != '' ) {
 		swalWithBootstrapButtons.fire(
 			'Reason of cancellation',
 			reason	      		
 			);
 	}
 });

	// MODAIL FORM TABS SCRIPTS
 var generate_tabs = function( callback ) {
 	'use strict';
		/*Activate default tab contents*/
 	var leftPos, newWidth, $magicLine, defaultActive;

 	defaultActive = $('.staff_tabs .tabs li.active a').attr('href');
 	$(defaultActive).show();

 	$('.staff_tabs .tabs').append("<li id='magic-line'></li>");
 	$magicLine = $('.staff_tabs #magic-line');
 	if ( $magicLine.length > 0 ) {
 		$magicLine.width($('.staff_tabs .active').width())
 		.css('left', $('.staff_tabs .active a').position().left)
 		.data('origLeft', $magicLine.position().left)
 		.data('origWidth', $magicLine.width());
 	}

 	$('.staff_tabs .tabs li a').click(function(){
 		var $this,tabId,leftVal,$tabContent;
 		$this = $(this);
 		$tabContent = $('.staff_tabs .tabContent');
 		$this.parent().addClass('active').siblings().removeClass('active');
 		tabId = $this.attr('href');

 		leftVal = $($tabContent).index($(tabId)) * $tabContent.width() * -1;
 		$('.staff_tabs .tabWrapper').stop().animate({left:leftVal}, function() {
 			callback($this);
 		});

 		$magicLine
 		.data('origLeft',$this.position().left)
 		.data('origWidth',$this.width() + 20);			

 		return false;
 	});

		/*Magicline hover animation*/
 	$('.staff_tabs .tabs li').find('a').hover(function() {
 		var $thisBar = $(this);
 		leftPos = $thisBar.position().left;
 		newWidth = $thisBar.parent().width();
 		$magicLine.stop().animate({left:leftPos,width:newWidth});
 	}, function() {
 		$magicLine.stop().animate({left:$magicLine.data('origLeft'),width: $magicLine.data('origWidth')});
 	});
 }

 generate_tabs(function( $this) {
		//console.log('tab generated');
 });

	//Import customers via ajax
 $('#apbgf-customer-import-form').on( 'submit', function( event ) {

 	event.preventDefault();		
 	var action = 'apbgf_customer_import';
 	var file = $('#apbgf-file')[0].files[0];
 	var formData = new FormData();
 	formData.append('action', action);
 	formData.append('nonce', apbgf_admin.nonce);
 	formData.append('csv_file', file);

 	if (file.type !== 'text/csv') {
 		$('#apbgf-customer-import-form').find('.apbgf-response').addClass('error');
 		$('#apbgf-customer-import-form').find('.apbgf-response').html('Invalid file type. Please select a CSV file.');
 		return;
 	}

 	if (file.size > 2000000) {
 		$('#apbgf-customer-import-form').find('.apbgf-response').addClass('error');
 		$('#apbgf-customer-import-form').find('.apbgf-response').html('File size exceeds the maximum limit of 2MB.');            
 		return;
 	}

 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		contentType: false,
 		processData: false,
 		beforeSend: function () {
 			$('#apbgf-customer-import-form').append('<div class="apbgf-modal-overlay" />');
 			$('#apbgf-customer-import-form').find('.apbgf-response').html('');
 			$('.apbgf-response').removeClass('error').removeClass('success');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				//console.log(response);
 			$('#apbgf-customer-import-form').find('.apbgf-response').addClass(response.status);
 			$('#apbgf-customer-import-form').find('.apbgf-response').html(response.message);
 			if ( 'success' == response.status ) {
 				
 			}
 		},
 		complete: function () {
 			$('.apbgf-modal-overlay').remove();
 		}
 	});
 });

	//add Customer ajax
 $('#apbgf-customer-form').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		fname: {
 			required: true
 		},
 		lname: {
 			required: true
 		},
 		field: {
 			required: true,
 			email: true
 		},	    
 	},
 	highlight: function(element, errorClass) {			
 		$(element).addClass('errorBorder');	
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_customer';
 		} else {
 			action = 'apbgf_add_customer';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-customer-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-customer-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-customer-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
					//console.log(response);
 				$('#apbgf-customer-form').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-customer-form').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-customer-form')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}

 });

	//add Staff Details ajax
 $('#apbgf-staff-form-details').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		fname: {
 			required: true
 		},
 		lname: {
 			required: true
 		},
 		field: {
 			required: true,
 			email: true
 		},	    
 	},
 	highlight: function(element, errorClass) {			
 		$(element).addClass('errorBorder');	
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_staff';
 		} else {
 			action = 'apbgf_add_staff';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-staff-form-details').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-staff-form-details').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-staff-form-details').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
					//console.log(response);
 				$('#apbgf-staff-form-details').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-staff-form-details').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-staff-form-details')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}
 });

	/*$('#apbgf-staff-form-details').on( 'submit', function( event ) {

		event.preventDefault();
		var post_id = '';
		var action = '';

		if ( $(this).find('.post_id').length > 0 ) {
			post_id = $(this).find('.post_id').val();
		}

		if ( post_id != '' ) {
			action = 'apbgf_edit_staff';
		} else {
			action = 'apbgf_add_staff';
		}

		var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
		$.ajax({
			url: apbgf_admin.ajaxurl,
			type: 'POST',
			data: formData,
			beforeSend: function () {
				$('#apbgf-staff-form-details').append('<div class="apbgf-modal-overlay" />');
				$('#apbgf-staff-form-details').find('.apbgf-response').html('');
				$('.apbgf-response').removeClass('error').removeClass('success');
			},
			success: function (response) {
				var response = $.parseJSON(response);
				//console.log(response);
				$('#apbgf-staff-form-details').find('.apbgf-response').addClass(response.status);
				$('#apbgf-staff-form-details').find('.apbgf-response').html(response.message);
				if ( 'success' == response.status ) {
					$('#apbgf-staff-form-details')[0].reset();
					location.reload();
				}
			},
			complete: function () {
				$('.apbgf-modal-overlay').remove();
			}
		});
	});*/


	//add Staff Services ajax
 $('#apbgf-staff-form-services').on( 'submit', function( event ) {

 	event.preventDefault();
 	var post_id = '';
 	var action = 'apbgf_add_staff_services';

 	if ( $(this).find('.post_id').length > 0 ) {
 		post_id = $(this).find('.post_id').val();
 	}		

 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		beforeSend: function () {
 			$('#apbgf-staff-form-services').append('<div class="apbgf-modal-overlay" />');
 			$('#apbgf-staff-form-services').find('.apbgf-response').html('');
 			$('.apbgf-response').removeClass('error').removeClass('success');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				//console.log(response);
 			$('#apbgf-staff-form-services').find('.apbgf-response').addClass(response.status);
 			$('#apbgf-staff-form-services').find('.apbgf-response').html(response.message);
 			if ( 'success' == response.status ) {
					//$('#apbgf-staff-form-services')[0].reset();
					//location.reload();
 			}
 		},
 		complete: function () {
 			$('.apbgf-modal-overlay').remove();
 		}
 	});
 });


	//add Staff Timings ajax
 $('#apbgf-staff-form-timings').on( 'submit', function( event ) {


	event.preventDefault();
	var $form = $(this);
	var bookingType = $('#apbgf-booking_type').val();
	var showError = false;
	var errorFields = [];

	// Only validate timing fields if not 'fullday'
	if (bookingType !== 'fullday') {
		// Validate start/end time, duration, interval, capacity fields
		$form.find('.form-start-time-slots input, .form-end-time-slots input, #apbgf-duration, #apbgf-interval, .form-slots-capacity input').each(function() {
			if (!$(this).hasClass('form-time-slots-disabled') && $(this).is(':visible')) {
				if ($(this).prop('required') && !$(this).val()) {
					showError = true;
					errorFields.push(this);
				}
			}
		});
	}

	// Show error if needed
	$form.find('.errorBorder').removeClass('errorBorder');
	if (showError) {
		$(errorFields).addClass('errorBorder');
		$form.find('.apbgf-response').addClass('error').html('Please fill all required timing fields.');
		return;
	}

	var post_id = '';
	var action = 'apbgf_add_staff_timings';
	if ($form.find('.post_id').length > 0) {
		post_id = $form.find('.post_id').val();
	}
	var formData = $form.serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
	$.ajax({
		url: apbgf_admin.ajaxurl,
		type: 'POST',
		data: formData,
		beforeSend: function () {
			$('#apbgf-staff-form-timings').append('<div class="apbgf-modal-overlay" />');
			$('#apbgf-staff-form-timings').find('.apbgf-response').html('');
			$('.apbgf-response').removeClass('error').removeClass('success');
		},
		success: function (response) {
			var response = $.parseJSON(response);
			$('#apbgf-staff-form-timings').find('.apbgf-response').addClass(response.status);
			$('#apbgf-staff-form-timings').find('.apbgf-response').html(response.message);
			if ('success' == response.status) {
				//$('#apbgf-staff-form-timings')[0].reset();
				//location.reload();
			}
		},
		complete: function () {
			$('.apbgf-modal-overlay').remove();
		}
	});
});

	//add Staff Spl Timings ajax
	// $('#apbgf-staff-form-spl-day').on( 'submit', function( event ) {

	// 	event.preventDefault();
	// 	var post_id = '';
	// 	var action = 'apbgf_add_staff_spl_timings';

	// 	if ( $(this).find('.post_id').length > 0 ) {
	// 		post_id = $(this).find('.post_id').val();
	// 	}		

	// 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;

	// 	console.log( formData );
 
	// 	$.ajax({
	// 		url: apbgf_admin.ajaxurl,
	// 		type: 'POST',
	// 		data: formData,
	// 		beforeSend: function () {
	// 			$('#apbgf-staff-form-spl-day').append('<div class="apbgf-modal-overlay" />');
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').html('');
	// 			$('.apbgf-response').removeClass('error').removeClass('success');
	// 		},
	// 		success: function (response) {
	// 			var response = $.parseJSON(response);
	// 			//console.log(response);
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').addClass(response.status);
	// 			$('#apbgf-staff-form-spl-day').find('.apbgf-response').html(response.message);
	// 			if ( 'success' == response.status ) {
	// 				//$('#apbgf-staff-form-spl-day')[0].reset();
	// 				//location.reload();
	// 			}
	// 		},
	// 		complete: function () {
	// 			$('.apbgf-modal-overlay').remove();
	// 		}
	// 	});
	// });

 

 	//add Location ajax
 	$('#apbgf-location-form').on( 'submit', function( event ) {

 		event.preventDefault();
 		var This = $(this);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_location';
 		} else {
 			action = 'apbgf_add_location';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-location-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-location-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-location-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
 				$('#apbgf-location-form').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-location-form').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-location-form')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	});

	//add Service ajax
 $('#apbgf-service-form').validate({
 	rules: {
		    // simple rule, converted to {required:true}
 		name: {
 			required: true		    	
 		},
 		category: {
 			required: true		    	
 		},		    
 	},
 	highlight: function(element, errorClass) {
 		$(element).addClass('errorBorder');		
 	},
 	success: function (label, element) {
 		$(element).removeClass('errorBorder');
 	},
 	submitHandler: function( form ) {
 		var This = $(form);
 		var post_id = '';
 		var action = '';

 		if ( $(This).find('.post_id').length > 0 ) {
 			post_id = $(This).find('.post_id').val();
 		}

 		if ( post_id != '' ) {
 			action = 'apbgf_edit_service';
 		} else {
 			action = 'apbgf_add_service';
 		}

 		var formData = $(This).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 		$.ajax({
 			url: apbgf_admin.ajaxurl,
 			type: 'POST',
 			data: formData,
 			beforeSend: function () {
 				$('#apbgf-service-form').find('.errorBorder').removeClass('errorBorder');
 				$('#apbgf-service-form').append('<div class="apbgf-modal-overlay" />');
 				$('#apbgf-service-form').find('.apbgf-response').html('');
 				$('.apbgf-response').removeClass('error').removeClass('success');
 			},
 			success: function (response) {
 				var response = $.parseJSON(response);
					//console.log(response);
 				$('#apbgf-service-form').find('.apbgf-response').addClass(response.status);
 				$('#apbgf-service-form').find('.apbgf-response').html(response.message);
 				if ( 'success' == response.status ) {
 					$('#apbgf-service-form')[0].reset();
 					location.reload();
 				}
 			},
 			complete: function () {
 				$('.apbgf-modal-overlay').remove();
 			}
 		});
 	}
 });
	// GB free version
 $('#apbgf_label_location').on('input', function() {
 	
 	if ($(this).val().length > 0) {
 		$('.gf_booking_apointments_listing').css('disabled', false);
 		$('.apbgf-booking-pro-version').show();

 	}
 	
 	

 })

 $('.apbgf-pro-cross').on('click', function(event) {

 	event.preventDefault();
 	$('.apbgf-booking-pro-version').hide();
 })
	// ================= / GB free version/ =======================
	//General settings
 $('.apbgf_setting_form').on('submit', function(event) {
 	event.preventDefault();

 	var action = 'apbgf_general_settings';		

 	var formData = $(this).serialize() + `&action=${action}&nonce=${apbgf_admin.nonce}`;
 	$.ajax({
 		url: apbgf_admin.ajaxurl,
 		type: 'POST',
 		data: formData,
 		beforeSend: function() {
 			$('body').append('<div id="apbgf-overlay" />');
				// $('.gf_booking_sidebar').removeClass('.activesidebar');
				// $('.gf_booking_overlayDiv').removeClass('.active');
 		},
 		success: function (response) {
 			var response = $.parseJSON(response);
				// console.log(response);
 			swalWithBootstrapButtons.fire(
 				response.status,
 				response.message,
 				response.status
 				);
 		},
 		complete: function() {
 			$('#apbgf-overlay').remove();
 		}
 	});
 });

 $.each( days, function( k, day ) {
 	$(document).on('change', `#apbgf_staff_timing_${day}_start`, function(e) {
 		var time_slots = new Array();
 		let start_time = parseTime($(`#apbgf_staff_timing_${day}_start`).val()),
 		end_time = parseTime($(`#apbgf_staff_timing_${day}_end`).val()),
 		duration = $('#apbgf-duration').val(),
 		interval = $('#apbgf-interval').val();

 		if ( duration == '' ) {
 			duration = $('#apbgf-duration').data('general');
 		}

 		if ( interval == '' ) {
 			interval = $('#apbgf-interval').data('general');
 		}

 		if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 			time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 		}

 		$(`#apbgf_staff_timing_${day}_break`).html('');

 		$.each( time_slots, function( i, v ) {											
 			$(`#apbgf_staff_timing_${day}_break`).append($('<option>', {
 				value: v,
 				text: v				
 			}));
 		});
 	});


 	$(document).on('change', `#apbgf_staff_timing_${day}_end`, function(e) {
 		var time_slots = new Array();
 		let start_time = parseTime($(`#apbgf_staff_timing_${day}_start`).val()),
 		end_time = parseTime($(`#apbgf_staff_timing_${day}_end`).val()),
 		duration = $('#apbgf-duration').val(),
 		interval = $('#apbgf-interval').val();

 		if ( duration == '' ) {
 			duration = $('#apbgf-duration').data('general');
 		}

 		if ( interval == '' ) {
 			interval = $('#apbgf-interval').data('general');
 		}

 		if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 			time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 		}

 		$(`#apbgf_staff_timing_${day}_break`).html('');

 		$.each( time_slots, function( i, v ) {
 			var val = v.split('-');
 			val = $.trim(val[0]);								
 			$(`#apbgf_staff_timing_${day}_break`).append($('<option>', {
 				value: val,
 				text: v				
 			}));
 		});
 	});

 });

 $('#apbgf-duration, #apbgf-interval').on('keyup copy paste change', function() {
		// console.log(`I triggered`);
 	$('.form-start-time-slots input[type="time"]').trigger('change');
 	$('.form-end-time-slots input[type="time"]').trigger('change');
 });

	/* Special Day start time & end time change create slots */
 $(document).on('change', `.apbgf_staff_spl_event_start`, function(e) {
 	var time_slots = new Array();
 	let start_time = parseTime($(this).val()),
 	id       = $(this).data('id'),
 	end_time = parseTime($(this).parent().siblings('.form-end-time-slots').find('.apbgf_staff_spl_event_end').val()),
 	duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').val(),
 	interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').val();

 	if ( duration == '' ) {
 		duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').data('general');
 	}

 	if ( interval == '' ) {
 		interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').data('general');
 	}

 	if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 		time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 	}

 	$(`#apbgf_staff_timing_${id}_break`).html('');

 	$.each( time_slots, function( i, v ) {											
 		$(`#apbgf_staff_timing_${id}_break`).append($('<option>', {
 			value: v,
 			text: v
 		}));
 	});
 });

 $(document).on('change', `.apbgf_staff_spl_event_end`, function(e) {
 	var time_slots = new Array();
 	let start_time = parseTime($(this).parent().siblings('.form-start-time-slots').find('.apbgf_staff_spl_event_start').val()),
 	id       = $(this).data('id'),
 	end_time = parseTime($(this).val()),
 	duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').val(),
 	interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').val();

 	if ( duration == '' ) {
 		duration = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-duration').data('general');
 	}

 	if ( interval == '' ) {
 		interval = $(this).parents('.spl_day_repeater_block').find('.apbgf-spl-interval').data('general');
 	}

 	if ( start_time != '' && end_time != '' && start_time < end_time && interval != '' && duration != '' ) {
 		time_slots = apbgf_split_time(start_time, end_time, duration, interval);
 	}

 	$(`#apbgf_staff_timing_${id}_break`).html('');

 	$.each( time_slots, function( i, v ) {											
 		$(`#apbgf_staff_timing_${id}_break`).append($('<option>', {
 			value: v,
 			text: v
 		}));
 	});
 });

 $('.apbgf-spl-duration, .apbgf-spl-interval').on('keyup copy paste change', function() {		
 	$(this).parents('.spl_day_repeater_block').find('.apbgf_staff_spl_event_start').trigger('change');
 	$(this).parents('.spl_day_repeater_block').find('.apbgf_staff_spl_event_end').trigger('change');
 });
});

 function getDatesInRange(startDate, endDate) {
 	
 	const dates = [];

 	startDate = new Date(startDate);
 	endDate = new Date(endDate);

 	if ( jQuery.trim(startDate) == '' || jQuery.trim(endDate) == '' ) {
 		return dates;
 	}

 	const date = new Date(startDate.getTime());	

 	while (date <= endDate) {
 		dates.push(moment(date, 'YYYY-MM-DD').format('YYYY-MM-DD'));
 		date.setDate(date.getDate() + 1);
 	}

 	return dates;
 }

 function parseTime(s) {
 	var c = s.split(':');
 	return parseInt(c[0]) * 60 + parseInt(c[1]);
 }

 function convertHours(mins){
 	var hour = Math.floor(mins/60);
 	var mins = mins%60;
 	var converted = pad(hour, 2)+':'+pad(mins, 2);
 	return converted;
 }

 function pad (str, max) {
 	str = str.toString();
 	return str.length < max ? pad("0" + str, max) : str;
 }

 function apbgf_split_time(start_time, end_time, duration = 5, interval = 5 ) {
 	
 	var i = 1,
 	formatted_time = '',
 	start_time = start_time,
 	end_time = end_time,
 	time_slots = new Array(),
 	duration = parseInt(duration),
 	interval = parseInt(interval);
 	
 	while ( (start_time + interval) < end_time ) {
 		if ( i > 1 ) {
 			start_time += interval;
 		}
 		
 		formatted_time = `${convertHours(start_time)} - ${convertHours(start_time + duration)}`;
 		
 		time_slots.push(formatted_time);

    	start_time += duration; //Endtime check

    	i++;
    }
    
    return time_slots;
}
