jQuery( document ).ready(function($) {	
	const overlay = jQuery('<div id="apbgf-overlay"> </div>');

	function apbgf_show_overlay() {
		apbgf_hide_overlay();
		overlay.appendTo( document.body );
	}

	function apbgf_hide_overlay() {
		$( '#apbgf-overlay' ).remove();
	}

	function apbgf_gform_init_prices( form_id ) {
		if ( typeof gformInitPriceFields !== 'function' || ! form_id ) {
			return;
		}
		var $form = $( '#gform_' + form_id );
		if ( $form.length ) {
			gformInitPriceFields( $form );
		}
	}

	function apbgf_reset_data(form_id) {
		$(`#apbgf_cost_${form_id}`).val(0).trigger('change');
		$(`#apbgf_date_${form_id}`).val(0);
		$(`#apbgf_time_${form_id}`).val(0);
		$(`#apbgf_slot_${form_id}`).val(0);
		$(`#apbgf_cost_${form_id}`).val(0);
		$(`#apbgf_booking_type_${form_id}`).val('');
		apbgf_gform_init_prices( form_id );

  		//if multiple booking erase it.
 		$('#apbgf_selected_bookings').html('');
 	}

 	$(document).on('change', '.apbgf_location', function (e) {
 		var post_id = $(this).val() === '' ? 'all' : $(this).val();
 		var action = 'apbgf_get_service_category_by_location';
 		

 		if (post_id !== '' && post_id !== 'all') {
 			$('.apbgf_location_input').val(post_id);
			
 			$.ajax({
 				url: apbgf_common.ajaxurl,
 				type: 'POST',
 				data: `form_id=${apbgf_common.form_id}&post_id=${post_id}&action=${action}&nonce=${apbgf_common.nonce}`,
 				beforeSend: function () {
 					apbgf_show_overlay();
 					$(`.apbgf_service_category`).html(`<option>${apbgf_common.loadingText}</option>`);
 				},
 				success: function (response) {
					
 					if (typeof response === 'string') {
 						response = $.parseJSON(response);
 					}

 					if (response.status === 'success') {
 						$(`.apbgf_service_category`).html($('<option>', {
 							value: 0,
 							text: apbgf_common.all_service_category_text
 						}));

 						$.each(response.data, function (i, v) {
 							let flag = (apbgf_common.default_service_category && v.ID == apbgf_common.default_service_category) || v.ID == response.selected_service_category_id;
 							$(`.apbgf_service_category`).append($('<option>', {
 								value: v.ID,
 								text: v.name,
 								selected: flag
 							}));
 						});
 					} else {
 						$(`.apbgf_service_category`).html($('<option>', {
 							value: 'no',
 							text: apbgf_common.no_service_category_text
 						}));
 					}
 				},
 				error: function () {
 					$(`.apbgf_service_category`).html($('<option>', {
 						value: 'no',
 						text: apbgf_common.no_service_category_text
 					}));
 				},
 				complete: function () {
 					apbgf_hide_overlay();
 					$('.apbgf_service_category').trigger('change');
 				}
 			});
 		}
 	});

 	$(document).on('change', '.apbgf_service_category', function (e) {
 		var term_id = $(this).val() === '' ? 0 : $(this).val();
 		var location_id = $('.apbgf_location').val();
 		var service_category_id = $('.apbgf_service_category').val();
 		var action = 'apbgf_get_service_by_service_category';
 		

 		if (term_id !== '' && term_id !== 'null') {
 			$('.apbgf_service_category_input').val( term_id );

 			$.ajax({
 				url: apbgf_common.ajaxurl,
 				type: 'POST',
 				data: `form_id=${apbgf_common.form_id}&term_id=${term_id}&location_id=${location_id}&service_category_id=${service_category_id}&action=${action}&nonce=${apbgf_common.nonce}`,
 				beforeSend: function () {
 					apbgf_show_overlay();
 					$(`.apbgf_service`).html(`<option>${apbgf_common.loadingText}</option>`);
 				},
 				success: function (response) {
 					
 					if (typeof response === 'string') {
 						response = $.parseJSON( response );
 					}

 					if (response.status === 'success') {
 						$(`.apbgf_service`).html($('<option>', {
 							value: 'all',
 							text: apbgf_common.all_service_text
 						}));

 						$.each(response.data, function (i, v) {
 							let flag = (apbgf_common.default_service && v.ID == apbgf_common.default_service) || v.ID == response.selected_service_id;
 							$(`.apbgf_service`).append($('<option>', {
 								value: v.ID,
 								text: v.post_title,
 								selected: flag
 							}));
 						});
 					} else {
 						$(`.apbgf_service`).html($('<option>', {
 							value: 'no',
 							text: apbgf_common.no_service_text
 						}));
 					}
 				},
 				error: function () {
 					$(`.apbgf_service`).html($('<option>', {
 						value: 'no',
 						text: apbgf_common.no_service_text
 					}));
 				},
 				complete: function () {
 					apbgf_hide_overlay();
 					$('.apbgf_service').trigger('change');
 				}
 			});
 		} else {
 			apbgf_hide_overlay();
 		}
 	});

 	$(document).on('change', '.apbgf_service', function (e) {
 		var post_id = $(this).val() === '' ? 'all' : $(this).val();
 		var location_id = $('.apbgf_location').val();
 		var action = 'apbgf_get_staff_by_service_and_location';
 	

 		if (post_id !== '' && post_id !== 'null') {
 			$('.apbgf_service_input').val(post_id);

 			$.ajax({
 				url: apbgf_common.ajaxurl,
 				type: 'POST',
 				data: `form_id=${apbgf_common.form_id}&post_id=${post_id}&location_id=${location_id}&action=${action}&nonce=${apbgf_common.nonce}`,
 				beforeSend: function () {
 					apbgf_show_overlay();
 					$(`.apbgf_staff`).html(`<option>${apbgf_common.loadingText}</option>`);
 				},
 				success: function (response) {
 					if (typeof response === 'string') {
 						response = $.parseJSON(response);
 					}

 					if (response.status === 'success') {
 						$(`.apbgf_staff`).html($('<option>', {
 							value: 'all',
 							text: apbgf_common.all_staff_text
 						}));

 						$.each(response.data, function (i, v) {
 							let flag = (apbgf_common.default_staff && v.ID == apbgf_common.default_staff) || v.ID == response.selected_staff_id;
 							$(`.apbgf_staff`).append($('<option>', {
 								value: v.ID,
 								text: v.post_title,
 								selected: flag
 							}));
 						});
 					} else {
 						$(`.apbgf_staff`).html($('<option>', {
 							value: 'no',
 							text: apbgf_common.no_staff_text
 						}));
 					}
 				},
 				error: function () {
 					$(`.apbgf_staff`).html($('<option>', {
 						value: 'no',
 						text: apbgf_common.no_staff_text
 					}));
 				},
 				complete: function () {
 					apbgf_hide_overlay();
 					$('.apbgf_staff').trigger('change');
 				}
 			});
 		} else {
 			apbgf_hide_overlay();
 		}
 	});

 	$(document).on('change', '.apbgf_staff', function (e) {
 		var post_id = $(this).val() === '' ? 'all' : $(this).val();
 		var location_id = $('.apbgf_location').val();
 		var service_category_id = $('.apbgf_service_category').val();
 		var service_id = $('.apbgf_service').val();
 		var form_id = $(this).parents('form').find('.apbgf_form_id').val();
 		

 		var prior_months = apbgf_common.prior_months;

    if (apbgf_common.is_admin === 'no') { // This will work for frontend only when staff value is triggered.
    	if (post_id !== '' && post_id !== 'null' && apbgf_common.loadingText !== post_id) {
    		$('.apbgf_staff_input').val(post_id);

    		var data = {
    			action: 'apbgf_month_changer',
    			nonce: apbgf_calendar.nonce,
    			is_admin: apbgf_common.is_admin,
    			form_id: apbgf_common.form_id,
    			location_id: location_id,
    			service_id: service_id,
    			service_category_id: service_category_id,
    			staff_id: post_id,
    			prior_months: prior_months
    		}

    		$.ajax({
    			url: apbgf_calendar.ajaxurl,
    			type: 'POST',
    			data: data,
    			dataType: 'HTML',
    			beforeSend: function () {
    				apbgf_show_overlay();
    			},
    			success: function (response) {
    				$('#apbgf-fancy-calendar').html(response);
    			},
    			error: function (jqXHR, status, error) {
    				if (jqXHR.status === 500) {
    					alert('Internal error: ' + jqXHR.responseText);
    				} else {
    					alert('Unexpected error.');
    				}
    			},
    			complete: function () {
    				apbgf_hide_overlay();
    				apbgf_reset_data(form_id);
    			}
    		});
    	} else {
    		apbgf_hide_overlay();
    	}
    	} else { // This will work for backend only when staff value is triggered.
	    	apbgf_hide_overlay();

	    	if ($('#apbgf-fancy-calendar').length <= 0) {
	    		return false;
	    	}

	    	if (post_id !== '' && post_id !== 'null' && apbgf_common.loadingText !== post_id) {
	    		var date = $('#apbgf-fancy-calendar').find('#date').val();

	    		var data = {
	    			action: 'apbgf_month_changer',
	    			is_admin: apbgf_common.is_admin,
	    			nonce: apbgf_calendar.nonce,
	    			location_id: location_id,
	    			service_id: service_id,
	    			service_category_id: service_category_id,
	    			staff_id: post_id,
	    			date: date
	    		}

	    		$.ajax({
	    			url: apbgf_calendar.ajaxurl,
	    			type: 'POST',
	    			data: data,
	    			dataType: 'HTML',
	    			beforeSend: function () {
	    				apbgf_show_overlay();
	    			},
	    			success: function (response) {
	    				$('#apbgf-fancy-calendar').html(response);
	    			},
	    			complete: function () {
	    				apbgf_hide_overlay();
	    			}
	    		});
	    	} else {
	    		apbgf_hide_overlay();
	    	}
	    }
	});

	$( document ).on( 'gform_page_loaded gform_post_render gform_confirmation_loaded', function () {
		apbgf_hide_overlay();
	} );

	function apbgf_sync_booking_hidden_fields( $form ) {
		if ( ! $form || ! $form.length ) {
			return;
		}
		var $location = $form.find( '.apbgf_location' );
		if ( $location.length ) {
			$form.find( '.apbgf_location_input' ).val( $location.val() );
		}
		var $category = $form.find( '.apbgf_service_category' );
		if ( $category.length ) {
			$form.find( '.apbgf_service_category_input' ).val( $category.val() );
		}
		var $service = $form.find( '.apbgf_service' );
		if ( $service.length ) {
			$form.find( '.apbgf_service_input' ).val( $service.val() );
		}
		var $staff = $form.find( '.apbgf_staff' );
		if ( $staff.length ) {
			$form.find( '.apbgf_staff_input' ).val( $staff.val() );
		}
	}

	$( document ).on( 'gform_pre_submission', function ( event, form ) {
		apbgf_hide_overlay();
		apbgf_sync_booking_hidden_fields( $( '#gform_' + form.id ) );
	} );

 });