// source --> https://metershop.sk/wp-content/plugins/bonsai-woo-gauge-calibrations/view/js/main.js?ver=1777534669 
/**
 * v20240926
 */
jQuery(document).ready(function($) {





	// Target our custom service tooltips
	$('#_bbgau_calibration_service_field .bbgau-tooltip, #_bbgau_calibration_expiry_reminder_field .bbgau-tooltip').on('click', function(event) {
        // Check if the click is on the tooltip or its children, but not on the "learn more" link
        if ($(event.target).closest('.bbgau-tooltip').length && !$(event.target).closest('a').length) {
			// Prevent the click event from affecting the parent label and checkbox
			event.preventDefault();
			event.stopPropagation();
		}
	}); // on tooltip click





	// Update minicart total in Savoy and Kapee theme
	function updateMiniCartTotal() {

		// Initialize total
		let total = 0;

		// Threshold for free shipping and gift
		// NOTE: We use it for Kapee theme only, so we don't need to adjust it for other currencies
		const free_gift_threshold = 75;

		// console.log('');
		// console.log('updateMiniCartTotal 222');

		// Check if we are on a theme that needs this adjustment
		if (!$('body').hasClass('theme-kapee') && !$('body').hasClass('theme-savoy')) {
			return;
		}

		// GET current currency symbol (from the first cart item)
		let currencySymbol = $('.woocommerce-Price-currencySymbol').first().text().trim();
		// console.log('currencySymbol:',currencySymbol);

		// Update each mini cart product price
		$('.woocommerce-mini-cart-item').each(function() {
			let $this = $(this);
			let quantity = parseInt($this.find('.quantity .qty').val()) || 1;
			let productPrice = 0;

			if ($('body').hasClass('theme-savoy')) {
                // For Savoy, since the displayed product price is the total, we need to calculate the unit price
                let displayedTotalPriceText = $this.find('.woocommerce-Price-amount.amount').last().text().replace(/[^\d,.-]/g, '').replace(',', '.');
                let displayedTotalPrice = parseFloat(displayedTotalPriceText) || 0;
                productPrice = displayedTotalPrice / quantity; // Calculate unit price by dividing by quantity
            } else {
                // For Kapee, use the displayed price as is
                let productPriceText = $this.find('.woocommerce-Price-amount.amount').last().text().replace(/[^\d,.-]/g, '').replace(',', '.');
                productPrice = parseFloat(productPriceText) || 0;
            }

			// GET calibration price for 1 qty			
			let calibrationPrice = 0;
			if ($this.find('.bbgau-cart-item-desc').length > 0) {
				let calibrationPriceText = $this.find('.bbgau-cart-item-desc .woocommerce-Price-amount.amount').first().text().replace(/[^\d,.-]/g, '').replace(',', '.');
				// Remove any spaces in the number
				calibrationPriceText = calibrationPriceText.replace(/\s+/g, '');
				calibrationPrice = parseFloat(calibrationPriceText) || 0;
			}

			// Calculate total for this item (considering quantity and additional price if any)
			total += (productPrice + calibrationPrice) * quantity;

			// console.log('quantity:',quantity);
			// console.log('productPrice:',productPrice);
			// console.log('calibrationPrice:',calibrationPrice);
			// console.log('item Total:',total);

		});

		// Update the mini cart total
		let formattedTotal;
		if(currencySymbol == '€') {
			formattedTotal = total.toFixed(2).replace('.', ',') + " " + currencySymbol;
		} else {
			formattedTotal = new Intl.NumberFormat('cs-CZ').format(total) + " " + currencySymbol; // space for thousands
		}
    	$('.woocommerce-mini-cart__total .woocommerce-Price-amount.amount bdi').text(formattedTotal);

		// Kapee only: Calculate remaining amount for free shipping and gift
		if ($('body').hasClass('theme-kapee')) {

			// Calculate and update the progress bar
			let progressPercentage = (total / free_gift_threshold) * 100;
			progressPercentage = progressPercentage > 100 ? 100 : progressPercentage; // Cap at 100%
			$('.kapee-freeshipping-bar .progress-bar').css('width', progressPercentage + '%').text(Math.floor(progressPercentage) + '%');

			// Update the notice with the remaining amount
			if(total < free_gift_threshold) {
				let remainingAmount = free_gift_threshold - total;
				remainingAmount = remainingAmount > 0 ? remainingAmount : 0; // Ensure the remaining amount doesn't go below 0
				$('.kapee-freeshipping-bar .freeshipping-bar-msg .woocommerce-Price-amount.amount').text(remainingAmount.toFixed(2).replace('.', ',') + ' €');
			} else {
				let free_gift_success_text = 'Skvelé! Máte dopravu zadarmo a darček.';
				$('.kapee-freeshipping-bar .freeshipping-bar-msg').text(free_gift_success_text);
				$('.kapee-freeshipping-bar').addClass('completed');
			}
			
		} // if Kapee

	} // updateMiniCartTotal
	
	// Trigger the update when the document is ready and after any cart updates
	$(document).ready(updateMiniCartTotal);
	$(document.body).on('wc_fragments_loaded wc_fragments_refreshed updated_wc_div', updateMiniCartTotal);





	// Degradation calculator
	$("#bbgau-degradation-form .bbgau-input").change(function() {
		
		// Load data from fields
		if($("#bbgau-usage").val()) {
			
			var usage = $("#bbgau-usage").val();
			if( usage == 1 ) {
				var usage_factor	= 1;
			} else if( usage <= 20 ) {
				var usage_factor	= 2;
			} else if( usage > 20 ) {
				var usage_factor	= 3;
			}
			
		} else {
			var usage			= 0;
			var usage_factor	= 0;
		}
		if ($("#bbgau-wear").val()) {
			var wear		= $("#bbgau-wear").val();
		} else {
			var wear		= 0;
		}
		if ($("#bbgau-environment").val()) {
			var environment		= $("#bbgau-environment").val();
		} else {
			var environment		= 0;
		}
		if ($("#bbgau-sensitivity").val()) {
			var sensitivity		= $("#bbgau-sensitivity").val();
		} else {
			var sensitivity		= 0;
		}
		
		// check if all data has been set
		if( usage_factor !== 0 && wear !== 0 && environment !== 0 & sensitivity !== 0 ) {
			
			// calculate calibration factor
			var calibration_factor = ( usage_factor * wear ) + ( environment * sensitivity );
			
			// add to input
			$("#bbgau-factor").val(calibration_factor);
			
			// calculate calibration interval
			if( calibration_factor <= 2 ) {
				var calibration_interval	= 96;
			} else if( calibration_factor <= 4 ) {
				var calibration_interval	= 48;
			} else if( calibration_factor <= 7 ) {
				var calibration_interval	= 24;
			} else if( calibration_factor <= 10 ) {
				var calibration_interval	= 12;
			} else if( calibration_factor <= 15 ) {
				var calibration_interval	= 6;
			} else if( calibration_factor <= 18 ) {
				var calibration_interval	= 3;
			}
			
			// add to input
			$("#bbgau-interval").val(calibration_interval);
			
			// console.log('Usage: ' + usage + ', Usage factor: ' + usage_factor + ', Wear: ' + wear + ', Environment: ' + environment + ', Sensitivity: ' + sensitivity + ', Calibration factor: ' + calibration_factor);
			
		} // if
		
	}); // on input change




	
	// Change calibration notification status
	$('.bbgau-icon-button.change-calibration-notification-status').click(function(e) {

		e.preventDefault();

		var itemId = $(this).data('id');
		var itemButton = $('#bbgau-table-row-' + itemId + ' .change-calibration-notification-status');
		var itemIcon = itemButton.find('.dashicons');

		// CAL AJAX
		$.ajax({
			url: bbgau_ajax_object.ajax_url,
			type: 'POST',
			data: {
				action: 'bbgau_change_calibration_notification_status',  // Custom AJAX action
				id: itemId,
				nonce: bbgau_ajax_object.nonce  // Use nonce for security
			},
			success: function(response) {
				if (response.success) {
					alert(response.data.message);
					// Change the title
					itemButton.attr('title', response.data.title);
					// Change the icon
					itemIcon.removeClass('dashicons-bell dashicons-hidden').addClass(response.data.icon_class);						
				} else {
					alert(response.data.message);
				}
			}

		}); // ajax

	}); // change notification status clicked





	// Delete custom calibration
	$('.bbgau-icon-button.delete-calibration').click(function(e) {

		e.preventDefault();

		var itemId = $(this).data('id');
		var itemRow = $('#bbgau-table-row-' + itemId);

		// CONFIRM
		if(!confirm(bbgau_ajax_object.delete_confirm_text)) {
			return;
		}

		// CAL AJAX
		$.ajax({
			url: bbgau_ajax_object.ajax_url,
			type: 'POST',
			data: {
				action: 'bbgau_delete_custom_calibration',  // Custom AJAX action
				id: itemId,
				nonce: bbgau_ajax_object.nonce  // Use nonce for security
			},
			success: function(response) {
				if (response.success) {
					alert(response.data.message);
					// Animate and remove the row
					itemRow.fadeOut(400, function() {
						$(this).remove();
					});
				} else {
					alert(response.data.message);
				}
			}

		}); // ajax

	}); // delete clicked







	// Admin add-calibration form: AJAX lookup for product_id, customer_id, order_id
	function bbgauLookup( action, id, $result, onSuccess ) {
		console.log( '[bbgau] lookup: action=' + action + ', id=' + id );
		$result.text( '…' ).removeClass( 'bbgau-lookup-ok bbgau-lookup-error' );
		$.ajax({
			url: bbgau_ajax_object.ajax_url,
			type: 'POST',
			data: { action: action, id: id, nonce: bbgau_ajax_object.nonce },
			success: function( response ) {
				console.log( '[bbgau] response:', response );
				if ( response.success ) {
					onSuccess( response.data );
				} else {
					$result.text( '✗ ' + response.data.message ).addClass( 'bbgau-lookup-error' ).removeClass( 'bbgau-lookup-ok' );
				}
			},
			error: function( xhr, status, error ) {
				console.error( '[bbgau] ajax error: status=' + status + ', error=' + error + ', response=' + xhr.responseText );
				$result.text( '✗ Chyba spojenia.' ).addClass( 'bbgau-lookup-error' ).removeClass( 'bbgau-lookup-ok' );
			}
		});
	}

	// Product ID → fill product name field
	$('#bbgau-product-id').on('blur', function() {
		var id = parseInt( $(this).val() );
		var $result = $( '#bbgau-product-id-result' );
		console.log( '[bbgau] product-id blur, id=' + id );
		if ( !id || id <= 0 ) {
			$result.text( '' ).removeClass( 'bbgau-lookup-ok bbgau-lookup-error' );
			return;
		}
		bbgauLookup( 'bbgau_lookup_product', id, $result, function( data ) {
			$('#bbgau-product-name').val( data.name );
			$result.text( '✓' ).addClass( 'bbgau-lookup-ok' ).removeClass( 'bbgau-lookup-error' );
		});
	});

	// Customer ID → fill name + email fields
	$('#bbgau-customer-id').on('blur', function() {
		var id = parseInt( $(this).val() );
		var $result = $( '#bbgau-customer-id-result' );
		console.log( '[bbgau] customer-id blur, id=' + id );
		if ( !id || id <= 0 ) {
			$result.text( '' ).removeClass( 'bbgau-lookup-ok bbgau-lookup-error' );
			return;
		}
		bbgauLookup( 'bbgau_lookup_customer', id, $result, function( data ) {
			$('#bbgau-customer-name').val( data.name );
			$('#bbgau-customer-email').val( data.email );
			$result.text( '✓ ' + data.name + ' <' + data.email + '>' ).addClass( 'bbgau-lookup-ok' ).removeClass( 'bbgau-lookup-error' );
		});
	});

	// Order ID → show info span (date + billing name/company)
	$('#bbgau-order-id').on('blur', function() {
		var id = parseInt( $(this).val() );
		var $result = $( '#bbgau-order-id-result' );
		console.log( '[bbgau] order-id blur, id=' + id );
		if ( !id || id <= 0 ) {
			$result.text( '' ).removeClass( 'bbgau-lookup-ok bbgau-lookup-error' );
			return;
		}
		bbgauLookup( 'bbgau_lookup_order', id, $result, function( data ) {
			if ( data.order_date )       { $('#bbgau-order-date').val( data.order_date ); }
			if ( data.completed_date )   { $('#bbgau-shipment-date').val( data.completed_date ); }
			if ( data.customer_address ) { $('#bbgau-customer-address').val( data.customer_address ); }
			if ( data.usage_address )    { $('#bbgau-usage-address').val( data.usage_address ); }
			$result.text( '✓ ' + data.info ).addClass( 'bbgau-lookup-ok' ).removeClass( 'bbgau-lookup-error' );
		});
	});



}); // jQuery;