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

	$(document).on('change', '.apbgf_service', function() {
		let val = $(this).find('option:selected').text().trim().toLowerCase();
	
		if ( 'other' === val ) {
			$(this).siblings('.apbgf_service_other_wrapper').show();			
		} else {
			$(this).siblings('.apbgf_service_other_wrapper').hide();
		}
	});


	$(document).on('click', '#apbgf-fancy-calendar a.apbgf-month-changer', function(e) {
		e.preventDefault();

		var is_admin = 'false';
		var location_id = '';
		var service_category_id = '';
		var service_id = '';
		var staff_id = '';
		var form_id = '';
		var month = $(this).data('month');
		var prior_months = 	apbgf_calendar.prior_months;

		if ( $('body').hasClass('gravity-booking_page_apbgf-calendar') ) {
			is_admin = '1';			
		}

		if ( $('.apbgf_location').length > 0 ) {
			location_id = $('.apbgf_location').val();
		}

		if ( $('.apbgf_service_category').length > 0 ) {
			service_category_id = $('.apbgf_service_category').val();
		}

		if ( $('.apbgf_service').length > 0 ) {
			service_id = $('.apbgf_service').val();
		}

		if ( $('.apbgf_staff').length > 0 ) {
			staff_id = $('.apbgf_staff').val();
		}

		if ( $('.apbgf_form_id').length > 0 ) {
			form_id = $('.apbgf_form_id').val();
		}
		

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

		$.ajax({
			url: apbgf_calendar.ajaxurl,
			async: true,		
			type: 'POST',
			data:data,
			dataType: 'HTML',			
			beforeSend: function() {
				overlay.appendTo(document.body);
				overlay_inside.appendTo('div.apbgf-cal-container');
			},
			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() {
				overlay.remove();
				overlay_inside.remove();				
				apbgf_selected_dates();
				// apbgf_disabled_booked_days(staff_id);
			}
		});
	});

	function apbgf_selected_dates() {
		var selected_bookings = $('#apbgf_selected_bookings');
		selected_bookings.find('.apbgf_selected_booking').each(function(){			
			var date = $(this).find('.apbgf_selected_dates').val();
			var parent_td = $(`input.apbgf-hdn[value="${date}"]`).parent('td');
			$(parent_td).addClass('apbgf-selected');
		});
	}

	function apbgf_disabled_booked_days(staff_id) {
	    $('#apbgf-fancy-calendar tbody tr td.apbgf-available').each(function(i, v) {
	        var This = $(this);
	        var d = $(This).find('input[type="hidden"].apbgf-hdn').val();
	        var data = {
	            action: 'apbgf_check_booked_slots_per_day', 
	            nonce: apbgf_calendar.nonce,
	            date: d,
	            staff_id: staff_id
	        };
	        $.post(apbgf_calendar.ajaxurl, data, function( success ) {
	            if ( !success ) {
	                $(This).removeClass('apbgf-available').addClass('apbgf-not-available');
	                $(This).find('input[type="hidden"].apbgf-hdn').remove();
	            }
	        });
	    });
	}
	// Remove Slots on double click
	$(document).on('dblclick',  'ul.apbgf-slot-list > li:not(.apbgf-unavailable) > span:not(.apbgf-tooltip-text)', function() {

		var slot_time =  $(this).text();
		if( $('#apbgf_selected_bookings').find('.apbgf_selected_booking').length >= 1) {
			var element = $('.apbgf_delete_booking')[0];
			var form_id = $(element).parents('form').find('.apbgf_form_id').val();
				
			var time = $(`#apbgf_time_${form_id}`).val();
			var date = $(element).data('date');
			var price = $(element).data('price');
			var qty = parseInt($(document).find('.apbgf_selected_costs').length)-1;
			var total_cost = price * qty;
			$(`#apbgf_cost_${form_id}`).val(total_cost).trigger('change');
			// Trigger gf total
			if( typeof gformInitPriceFields == 'function' ) {
				gformInitPriceFields($(`gform_${form_id}`)); // will trigger "gform_product_total" filter
			}

			if ( $('#apbgf_selected_bookings').find('.apbgf_selected_booking').length <= 0 ) {
				$(`#apbgf_date_${form_id}`).val(0);
				$(`#apbgf_slot_${form_id}`).val(0);
				$(`#apbgf_cost_${form_id}`).val(0);
				$(`#apbgf_booking_type_${form_id}`).val('');
			}

			var slots = time.split(',');
			remaining_slots = [];
			
			if( slots.includes( slot_time ) ) {
				remaining_slots = slots.filter(item => item !== slot_time);

				 $(`#apbgf_time_${form_id}`).val(remaining_slots);
				 $(`#apbgf_slot_${form_id}`).val(remaining_slots.length);
				 $(this).removeClass('apbgf-selected');
				 
				 var selected_slot = $(this).data('selected_slot_number');
				 $(`.booking_slot_number_${selected_slot}`).remove();
			}
		}
		else { 
			$('ul.apbgf-slot-list > li > span ~ input.apbgf-selected-capacity').removeClass('show');
			$('ul.apbgf-slot-list > li > span ~ input.apbgf-selected-capacity').attr('disabled', true);
			$('ul.apbgf-slot-list > li > span ~ input.apbgf-selected-capacity').val('');
			$(this).parent('li').find('span').removeClass('apbgf-selected');
			if($('.apbgf_date_input').val() !='') {
				$('.apbgf_date_input').val('')
			}
			if($('.apbgf_time_input').val() !='') {
				$('.apbgf_time_input').val('')
			}
			if($('.apbgf_slot_input').val() !='') {
				$('.apbgf_slot_input').val('')
			}
			if($('.apbgf_cost_input').val() !='') {
				$('.apbgf_cost_input').val('')
			}
		}
	});
	// end
	$(document).on('click', 'ul.apbgf-slot-list > li:not(.apbgf-unavailable) > span:not(.apbgf-tooltip-text)', function() {
		var form_id = '';
		var multipleByStaff = jQuery('#multiple-by-staff').val();

	

		if ( $('.apbgf_form_id').length > 0 ) {
			form_id = $('.apbgf_form_id').val();
		}
		$(this).css({'user-select' : 'none'});

			$('ul.apbgf-slot-list > li > span').removeClass('apbgf-selected');
			$('ul.apbgf-slot-list > li > span ~ input.apbgf-selected-capacity').removeClass('show');
			$('ul.apbgf-slot-list > li > span ~ input.apbgf-selected-capacity').attr('disabled', true);
			$(this).parent('li').find('span').addClass('apbgf-selected');
			if ( $(this).siblings('input.apbgf-selected-capacity').length > 0 ) {
				$(this).siblings('input.apbgf-selected-capacity').addClass('show');
				$(this).siblings('input.apbgf-selected-capacity').removeAttr('disabled');
			}

			var time = '';
			if ( $(this).siblings('input.apbgf-selected-time').length > 0 ) {
				time = $(this).siblings('input.apbgf-selected-time').val();
			}

			var cost = 0.00;
			if ( $(this).siblings('input.apbgf-selected-price').length > 0 ) {
				cost = $(this).siblings('input.apbgf-selected-price').val();
			}

			var capacity = '';
			if ( $(this).siblings('input.apbgf-selected-capacity').length > 0 ) {
				capacity = $(this).siblings('input.apbgf-selected-capacity').val();
				cost = cost * capacity;			
			}

			$(this).siblings('input.apbgf-selected-capacity').on('input', function () {
				$(this).parent('li').find('span.apbgf-selected').trigger('click');
				$(this).focus();
				capacity = $(this).siblings('input.apbgf-selected-capacity').val();
				cost = cost * capacity;		
			});

			var date = '';
			if ( $(this).siblings('input.apbgf-selected-date').length > 0 ) {
				date = $(this).siblings('input.apbgf-selected-date').val();
			}		
			$(`#apbgf_date_${form_id}`).val(date);
			$(`#apbgf_time_${form_id}`).val(time);
			$(`#apbgf_slot_${form_id}`).val(capacity);
			$(`#apbgf_cost_${form_id}`).val(cost);
		
		
		// Trigger gf total
		if( typeof gformInitPriceFields == 'function' ) {
			gformInitPriceFields($(`gform_${form_id}`)); // will trigger "gform_product_total" filter
		}

	});

	/**
	 * Process Appointment Tax
	 */
	if( typeof gformInitPriceFields == 'function' ) {		
		gform.addFilter( 'gform_product_total', function( total, formId ) {		

			if ( $('.apbgf_cost_input').length > 0 && $('.apbgf_cost_input').val() >= 0 ) {
				var cost = $('.apbgf_cost_input').val();
				// Cost Fields
				total += Math.max( 0, parseFloat( cost ) );

				if ( jQuery( '#gf_total_no_discount_' + formId ).length > 0 ) {
					jQuery( '#gf_total_no_discount_' + formId ).val( total );
					window['new_total_' + formId] = total;
				}

				if ( $('.apbgf_cost_input').length > 0 ) {
					$('.apbgf_cost_input').val(cost);
				}				

				return total;
			}

			if ( jQuery( '#gf_total_no_discount_' + formId ).length > 0 ) {
				jQuery( '#gf_total_no_discount_' + formId ).val( total );
				window['new_total_' + formId] = total;
			}
			
			return total;
		}, 40 );		 //coupons applied at 50
	}

	$(document).on('keyup copy paste', '.apbgf-selected-capacity', function() {		
		$(this).parent('li').find('span.apbgf-selected').trigger('click');
		$(this).focus();
	});

	$(document).on('click', '.apbgf_delete_booking', function() {		
		var form_id = $(this).parents('form').find('.apbgf_form_id').val();
		var date = $(this).data('date');
		var price = $(this).data('price');
		var parent_td = $(`input.apbgf-hdn[value="${date}"]`).parent('td');
		$(this).parent('.apbgf_selected_booking').remove();
		var qty = parseInt($(document).find('.apbgf_selected_costs').length);
		var total_cost = price * qty;
		$(`#apbgf_cost_${form_id}`).val(total_cost).trigger('change');
		// Trigger gf total
 		if( typeof gformInitPriceFields == 'function' ) {
 			gformInitPriceFields($(`gform_${form_id}`)); // will trigger "gform_product_total" filter
  		}

  		if ( $('#apbgf_selected_bookings').find('.apbgf_selected_booking').length <= 0 ) {
  			$(`#apbgf_date_${form_id}`).val(0);
			$(`#apbgf_slot_${form_id}`).val(0);
			$(`#apbgf_cost_${form_id}`).val(0);
			$(`#apbgf_booking_type_${form_id}`).val('');
  		}
		if( apbgf_calendar.multiple_custom_slot == '1'  ) {		
			var time = $(`#apbgf_time_${form_id}`).val();
		
			let timeSlots = time.split(',');
			// Remove the selected time slot from the list of time slots
			timeSlots = timeSlots.filter(item => item !== $(this).data('slot'));
	
			// console.log(jQuery(`.apbgf-selected-time[value="${$(element).data('slot')}"]`));
			if( jQuery(`.apbgf-selected-time[value="${$(this).data('slot')}"]`).parents('li.apbgf-tooltip').children('span')[0].classList.contains('apbgf-selected') ) {
				jQuery(`.apbgf-selected-time[value="${$(this).data('slot')}"]`).parents('li.apbgf-tooltip').children('span')[0].classList.remove('apbgf-selected');
			}
			$(`#apbgf_slot_${form_id}`).val(timeSlots.length);
			$(`#apbgf_time_${form_id}`).val(timeSlots);
		} else {
			$(`#apbgf_time_${form_id}`).val(0);
			$(parent_td).removeClass('apbgf-selected');
		}
	});

	$(document).on('click', 'td.apbgf-available:not(.apbgf-selected)', function() {
		var current = $(this);
		var parent_row = $(this).parent('tr');
		var parent_table = $(this).parents('table.apbgf-cal-table');
		var selected_dates_cont = $('#apbgf_selected_bookings');
		$('table.apbgf-cal-table td').removeClass('apbgf-caret-down');

		//conitnue from here on 26 June 2023
		if ( ! ($(this).find('input[data-multiple="enabled"]').length > 0) ) {
			$('table.apbgf-cal-table td').removeClass('apbgf-selected');
		}

		$(this).addClass('apbgf-selected');

		var location_id = '';
		var service_id = '';
		var staff_id = '';
		var form_id = '';
		var total_cost = 0;
		var date = $(this).find('.apbgf-hdn').val();		

		if ( $('.apbgf_location').length > 0 ) {
			location_id = $('.apbgf_location').val();
		}

		if ( $('.apbgf_service').length > 0 ) {
			service_id = $('.apbgf_service').val();
		}

		if ( $('.apbgf_staff').length > 0 ) {
			staff_id = $('.apbgf_staff').val();
		}

		if ( $('.apbgf_form_id').length > 0 ) {
			form_id = $('.apbgf_form_id').val();
		}

		$(`#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('');
		// if ( $(`#apbgf_booking_type_${form_id}`).length > 0 ) {
		// 	$(`#apbgf_booking_type_${form_id}`).remove();
		// }

		//alert(date);
		var data = {
			action: 'apbgf_show_slots_by_date',
			nonce: apbgf_calendar.nonce,
			date: date,			
			location_id: location_id,
			service_id: service_id,
			staff_id: staff_id,
			form_id: form_id
		}

		$.ajax({
			url: apbgf_calendar.ajaxurl,			
			type: 'POST',
			data:data,
			dataType: 'HTML',
			beforeSend: function() {
				overlay.appendTo(document.body);
				overlay_inside.appendTo('div.apbgf-cal-container');				
				$('#apbgf-timeslots-table-container-tr').remove();
				$('#apbgf-timeslots-table-container').remove();
				if( typeof gformInitPriceFields == 'function' ) {
		 			gformInitPriceFields($(`gform_${form_id}`)); // will trigger "gform_product_total" filter
		  		}
			},
			success: function(response) {
				var is_json = true;

				try {
					var obj = $.parseJSON(response);
					//console.log(obj);
				} catch(err) {
					is_json = false;
				}
				
				if ( is_json && 'fullday' == obj.booking_type ) { //if booking type is full day
					// debugger;
					var multiple = false;

					total_cost = obj.service_price;

					$(`#apbgf_date_${form_id}`).val(obj.date).trigger('change');
					$(`#apbgf_time_${form_id}`).val(obj.time).trigger('change');
					$(`#apbgf_slot_${form_id}`).val(1).trigger('change');
					$(`#apbgf_is_multiple_booking_${form_id}`).val(0).trigger('change');
					$(`#apbgf_booking_type_${form_id}`).val(obj.booking_type);								

					if ( '' == obj.html ) {
						$(`#apbgf_cost_${form_id}`).val(total_cost).trigger('change');
						// Trigger gf total
				 		if( typeof gformInitPriceFields == 'function' ) {
				 			gformInitPriceFields($(`gform_${form_id}`)); // will trigger "gform_product_total" filter
				  		}
					} else {
						if ( 'right' == apbgf_calendar.show_timeslot && ! (window.matchMedia("(max-width: 575px)").matches) ) {
							$(`<div id="apbgf-timeslots-table-container">${obj.html}</div>`).insertAfter(parent_table);
						} else {
							$(current).addClass('apbgf-caret-down');
							$(`<tr id="apbgf-timeslots-table-container-tr"><td colspan="7">${obj.html}</td></tr>`).insertAfter(parent_row);	
						}
					}					
				} else { //if booking type is custom
					if ( 'right' == apbgf_calendar.show_timeslot && ! (window.matchMedia("(max-width: 575px)").matches) ) {
						$(`<div id="apbgf-timeslots-table-container">${response}</div>`).insertAfter(parent_table);
					} else {
						$(current).addClass('apbgf-caret-down');
						$(`<tr id="apbgf-timeslots-table-container-tr"><td colspan="7">${response}</td></tr>`).insertAfter(parent_row);	
					}
					if ( $('#apbgf_selected_bookings').length > 0 ) {
						$('#apbgf_selected_bookings').html('');
					}			
				}
			},
			error: function(jqXHR, status, error) {
				if (jqXHR.status == 500) {
                	alert('Internal error: ' + jqXHR.responseText);
              	} else {
                  	alert('Unexpected error.');
              	}
			},
			complete: function() {
				overlay.remove();
				overlay_inside.remove();
			}
		});
	});

	

});