// source --> https://govmedics.com/wp-content/plugins/quote-for-woocommerce//assets/public/js/wc-quote-front.js?ver=3.0.1 
jQuery(document).ready(function () {
	"use strict";
	var ajaxUrl  = wc_quote_vars.ajax_url;
	var nonce    = wc_quote_vars.nonce;
	var redirect = wc_quote_vars.redirect;
	var hide_cart_all = wc_quote_vars.hide_cart_all;
	var pageurl  = wc_quote_vars.redirect_url;
	var postid =  wc_quote_vars.post_id;


	// ======= Html to pdf custom pdf sprint 2.7 Start ======
	// let pdfOpt = {
	// 	margin: 20,
    //     filename: 'custom.pdf',
    //     image: { type: 'jpeg', quality: 1,},
    //     html2canvas: { scale: 1 },
    // };

	var pdfOpt = {
		margin: [0.3, 0.5, 0.3, 0.5],
		filename: "custom" + ".pdf",
		image: { type: "jpeg", quality: 1 },
		// Added after option to add spacing after page break
		pagebreak: { avoid: "tr", mode: "css", before: ".wp-block-column", after: "1cm" },
		html2canvas: { scale: 4, useCORS: true, dpi: 192, letterRendering: true },
		// Added putTotalPages option to add page number
		jsPDF: { unit: "in", format: "a4", orientation: "portrait", putTotalPages: true },
	  };
	// ======= Html to pdf custom pdf sprint 2.7 End ======

	var quote_list_ids=[];
	jQuery('.widget_quote_list').each(function(){
		quote_list_ids.push( jQuery(this).attr('id'));
	});

	var quote_icon_ids=[];
	jQuery('.widget_quote_icon').each(function(){
		quote_icon_ids.push( jQuery(this).attr('id'));
	});

	jQuery('div.menu ul').append( '<li>' + jQuery('li.wc-quote-li a:eq(1)').text() + '</li>' );

	jQuery(document).on( 'change', '.variation_id', function (e) {

		if( !jQuery(this).val() ){
			return;
		}

		jQuery( '.wc_quote_single_page' ).addClass( 'disabled wc-variation-is-unavailable' );
		
		var variation_id = parseInt( jQuery(this).val() );
		var current_button = jQuery(this);

		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action       : 'wc_check_availability_of_quote',
				nonce        : nonce,
				variation_id : variation_id,
			},
			success: function ( response ) {
				if( false === response.success ){
					jQuery( '.wc_quote_single_page' ).addClass( 'disabled wc-variation-is-unavailable' );
				} else if ( true === response.success ) {
					jQuery( '.wc_quote_single_page' ).removeClass( 'disabled' );
				}
				
			},
			error: function (response) {
				current_button.removeClass('loading');
				current_button.css('opacity', '1' );
				current_button.css('border', '1px solid red' );
			}
		});

	});
	
	// jQuery('.wc_quote_converty_to_order_button button').click( function (e) {
	// 	jQuery(this).addClass('loading');
	// 	jQuery('table.quote_details').css( 'opacity', '0.67' );

	// });

	jQuery('div.wc_quote_fields input:not([type="submit"]), div.wc_quote_fields textarea, div.wc_quote_fields select').each( function(){

		var current_button = jQuery(this);

		if( !current_button.val() || current_button.val().length < 1 ){

			if( 'required' === current_button.attr('required')  ) {
				current_button.css('border-left', '2px solid #ca1010');
			}
		} else {
			current_button.css('border-left', '2px solid green');
		}
	});

	jQuery( document ).on( 'focusout', 'div.wc_quote_fields input, div.wc_quote_fields textarea, div.wc_quote_fields select', function(ev) {

		var current_button = jQuery(this);

		if( !current_button.val() || current_button.val().length < 1 ){

			if( 'required' === current_button.attr('required')  ) {
				current_button.css('border-left', '2px solid #ca1010');
			}

			return;
		}
		else {
			current_button.css('border-left', '2px solid green');
		}

		// jQuery.ajax({
		// 	url: ajaxUrl,
		// 	type: 'POST',
		// 	data: {
		// 		action   : 'cache_quote_fields',
		// 		nonce    : nonce,
		// 		form_data : jQuery(this).closest('form').serialize(),
		// 	},
		// 	success: function (response) {
		// 		current_button.css('border-left', '2px solid green');
		// 	},
		// 	error: function (response) {
		// 		current_button.css('border-left', '2px solid #ca1010');
		// 	}
		// });
	});


	// =================================================
	// ========== custom pdf sprint 2.7 start ==========
	// =================================================

	// For Pdf download from url 
	// example : http://local-projects.local/download-pdf/?quote_id=361&pdf_type=bronze&wcquote_email_pdf=yes&template_name=bronze
	

	(()=>{
		var element = document.getElementById('wcquote_pdf_template_content');
			
				if (!element) {
					return;
				}
				try {
				
					const url = new URL(window.location.href);
					const templateName = url.searchParams.get('template_name');
			
					if (templateName) {
						// pdfOpt.filename = templateName;
						const date = new Date();
						const formattedDate = date.toISOString().replace(/[-:]/g, '').split('T')[0]; // YYYYMMDD
						const formattedTime = date.toTimeString().split(' ')[0].replace(/:/g, ''); // HHMMSS
						pdfOpt.filename = `quote-pdf-download-${formattedDate}-${formattedTime}.pdf`;
						
						html2pdf().from(element).set(pdfOpt).save().then(() => {
							setTimeout( function() {
								window.close();
							}, 2000);
						});
					}
					
					
				} catch (error) {
					console.log(error)
				}
	})();

	

	
	// =================================================
	// =========== custom pdf sprint 2.7 End ===========
	// =================================================

	jQuery('.my_account_quotes a.wc-quote-download').click( function (e) {
		e.preventDefault();
		if( jQuery(this).hasClass('disabled') ){
			return;
		}
		jQuery(this).addClass('loading');
		jQuery(this).css('opacity', '0.7' );
		var current_button = jQuery(this);
		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action   : 'wcquote_download_account_quote_pdf',
				nonce    : nonce,
				quote_id : current_button.data('quote_id'),
			},
			success: function (response) {
				current_button.removeClass('loading');
				current_button.addClass('loaded disabled');
				current_button.css('border', '1px solid green' );
				
				// ======= Html to pdf custom pdf sprint 2.7 Start ======
				
				// console.log(response.pdf_content,"============================");
				if(response.pdf_content){

					// Set a default filename if none is provided
					pdfOpt.filename = response.file_name ? response.file_name : 'default-quote.pdf';
					
					try {
						// Generate and download the PDF using html2pdf

						
						// =====================================================
						/* >=> Resolve Caution Canvas2D: Multiple readback 
							operations using getImageData are faster Start <=< */
						// =====================================================
						
						const originalGetContext = HTMLCanvasElement.prototype.getContext;
						
						HTMLCanvasElement.prototype.getContext = function (type, options) {
							if (type === '2d') {
								options = options || {};
								options.willReadFrequently = true; // Enable the attribute
							}
							return originalGetContext.call(this, type, options);
						};
						// =====================================================
						// ================ Resolve Caution End ================
						// =====================================================
						// Open a new window
						const newWindow = window.open('', '_blank');
						if (!newWindow) {
							console.error("Failed to open a new window.");
							return;
						}
						
						// Create a hidden div using jQuery
						const $hiddenDiv = jQuery('<div id="hiddenDiv"></div>');
						$hiddenDiv.html(response.pdf_content); // Set the content
						jQuery('body').append($hiddenDiv); // Append it to the body

						
						html2pdf()
						.from($hiddenDiv[0])
						.set(pdfOpt)
						.toPdf()
						.get('pdf')
						.then((pdf) => {
							jQuery('#hiddenDiv').remove();
							newWindow.close(); // Close the new window if the element is not found

							// Open PDF in a new browser window
							// const pdfBlob = pdf.output('blob');
							// const pdfURL = URL.createObjectURL(pdfBlob);
							// window.open(pdfURL, '_blank');

							// Optionally, trigger download after opening
							pdf.save();
						});

						// html2pdf().from(response.pdf_content).set(pdfOpt).save();
						console.log("PDF generated and downloaded successfully.");

					} catch (error) {
						// Log the error and inform the user
						console.error("Error generating the PDF:", error);
						alert("Failed to generate the PDF. Please try again.");
					}
					
					return;
				}
				// ======= Html to pdf custom pdf sprint 2.7 End ======

				window.open( response );

			},
			error: function (response) {
				current_button.removeClass('loading');
				current_button.css('opacity', '1' );
				current_button.css('border', '1px solid red' );
			}
		});
	});
	jQuery(window).on('load', function(){
			if( 1 == hide_cart_all ) {
	   jQuery('.wp-block-button.wc-block-grid__product-add-to-cart a.ajax_add_to_cart').hide();
	}

	});
	jQuery(document).on('click', 'button.wc_quote_update_quote_btn', function (e) {
		e.preventDefault();

		let invalid = false;
		let hasError = false;
		jQuery('form.wc-quote-form input[name^="quote_qty"]').each(function () {
			let qty = parseInt(jQuery(this).val());
			console.log(qty);
			if (isNaN(qty) || qty <= 0) {
				invalid = true;
			}
		});

		// Validate offered prices (must be >= 0)
		jQuery('form.wc-quote-form input[name^="offered_price"]').each(function () {
			let price = parseFloat(jQuery(this).val());
			if (isNaN(price) || price < 0) {
				hasError = true;
			}
		});

		if (hasError) {
			alert('Offered price cannot be negative. Please correct it.');
			return;
		}

		if (invalid) {
			alert('Quantity must be at least 1'); // optional
			return;
		}

		if ( jQuery(this).hasClass('loading') ) {
			return;
		}

		jQuery(this).addClass('loading');
		var current_button = jQuery(this);

		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			dataType: 'JSON',
			data: {
				action   : 'wcquote_update_quote_items',
				nonce    : nonce,
				form_data : jQuery('form.wc-quote-form').serialize(),
				quote_id : current_button.data('quote_id'),
				quote_list_ids: quote_list_ids,
				quote_icon_ids: quote_icon_ids,
				post_id: postid
			},
			
			success: function (response) {
				
				current_button.removeClass('loading');
				current_button.addClass('disabled');

				if( response['quote_empty'] ){
					// location.reload();
				}

				
				jQuery('table.wc-quote-form__contents').replaceWith( response['quote-table'] );
				jQuery('table.table_quote_totals').replaceWith( response['quote-totals'] );
				jQuery('li.wc-quote-li').replaceWith( response['mini-quote'] );

				jQuery.each(response['quote-widget-list'], function(k,v){
					jQuery('#'+ k + ' table.wc-quote-widget__contents').replaceWith( v );
				})
				
				jQuery.each(response['quote-widget-icon'], function(k,v){
					jQuery('#'+ k + ' div.wc-quote-icon').replaceWith( v );
				})

				if ( response['quote-widgets-elementor'] ) {
					jQuery('.elementor.elementor-'+ postid ).html( response['quote-widgets-elementor'] );
				}
				jQuery('div.woocommerce-notices-wrapper').html(response['message'] );
				jQuery('body').animate({
					scrollTop: jQuery('div.woocommerce-notices-wrapper').offset().top,
				}, 500
				);
				
			},

			error: function (response) {
				current_button.removeClass('loading');	
				current_button.addClass('disabled');
			}
		});
	});

	jQuery(document).on('click', 'a.wc_quote_add_to_cart', function () {

		var redirect_url = jQuery(this).attr('data-url');
		if( jQuery(this).hasClass('loading') ){
			return;
		}
		jQuery(this).addClass('loading');
		var current_button = jQuery(this);
		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action: 'wcquote_add_to_cart',
				nonce: nonce
			},
			success: function (response) {

				if ( 'success' == jQuery.trim(response) ) {

					window.location.href = redirect_url;

				} else if( 'failed' == jQuery.trim(response) ){

					location.reload();
					
				} else {

					current_button.removeClass('loading');

				}	
			}
		});
	});

	jQuery(document).on('click', '.build-quote-button', function () {

		var redirect_url = jQuery(this).attr('data-url');
		if( jQuery(this).hasClass('loading') ){
			return;
		}
		jQuery(this).addClass('loading');
		var current_button = jQuery(this);
		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action: 'wcquote_build_quote',
				nonce: nonce
			},
			success: function (response) {

				if ( 'success' == jQuery.trim(response) ) {

					window.location.href = redirect_url;

				} else if( 'failed' == jQuery.trim(response) ){

					location.reload();
					
				} else {

					current_button.removeClass('loading');

				}	
			}
		});
	});

	jQuery(document).on('click', '.quote-btn', function (e) {
		e.preventDefault();
	// jQuery(this).attr('disabled', true);

		if( jQuery(this).hasClass('loading') ){
			return false;
		}

		jQuery(this).parent().find('a.added_to_quote').remove();

		if (jQuery(this).is('.product_type_simple') || jQuery(this).is('.product_type_variable') || jQuery(this).is('.product_type_subscription')) {

			var productId = jQuery(this).attr('data-product_id');
			var quantity = 1;

			// WCPT table quantity
			var wcptQty = jQuery(this)
				.closest('tr.wcpt-row')
				.find('input.qty')
				.val();

			if (wcptQty !== undefined && wcptQty !== '') {
				quantity = parseInt(wcptQty, 10);
			} 
			else {

				// Try normal WooCommerce form quantity
				var formQty = jQuery(this)
					.closest('form')
					.find('input.qty')
					.val();

				if (formQty !== undefined && formQty !== '') {
					quantity = parseInt(formQty, 10);
				} 
				else {
					// Astra loop fallback (if form qty not found)
					var astraQty = jQuery(this)
						.closest('.astra-shop-summary-wrap, li.product')
						.find('input.qty')
						.first()
						.val();

					if (astraQty !== undefined && astraQty !== '') {
						quantity = parseInt(astraQty, 10);
					}
				}
			}

			// Safety check
			if (isNaN(quantity) || quantity < 1) {
				quantity = 1;
			}

			// Trigger a custom event to allow modification of quantity.
            var quantityEvent = jQuery.Event('modify_quantity');
            quantityEvent.quantity = quantity;

            jQuery(document).trigger(quantityEvent, [jQuery(this)]);
            
            // Use the potentially modified quantity.
            quantity = quantityEvent.quantity;

			jQuery(this).addClass('loading');
			var current_button = jQuery(this);
			jQuery.ajax({
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: 'wcquote_add_to_quote',
					product_id: productId,
					quote_list_ids: quote_list_ids,
					quote_icon_ids: quote_icon_ids,
					post_id: postid,
					quantity: quantity,
					nonce: nonce
				},
				success: function (response) {
					
					if ( 'success' == jQuery.trim(response) ) {
						if ( "1" == redirect ) {

							window.location.href = pageurl;
						} else {

							location.reload();
						}
						
					} else if( 'failed' == jQuery.trim(response) ){

						location.reload();
						
					} else {
						jQuery('.hide_on_quote').remove();
						current_button.removeClass('loading');
						if ( current_button.parent().find( '.added_to_quote' ).length === 0 ) {

							if ( response['browse_list'] == null ) {
								jQuery('.quote-btn[data-product_id="' + productId + '"]').show();
							}else{
								current_button.after( response['browse_list'] );
								jQuery('.quote-btn[data-product_id="' + productId + '"]').hide();	
							}
						}
						jQuery('.wc-quote-li').replaceWith(response['mini-quote']);
						jQuery('table.wc-quote-form__contents').replaceWith( response['quote-table'] );
						jQuery('table.table_quote_totals').replaceWith( response['quote-totals'] );
						
						jQuery.each(response['quote-widget-list'], function(k,v){
							if (jQuery('#'+ k + ' table.wc-quote-widget__contents').length > 0){
								jQuery('#'+ k + ' table.wc-quote-widget__contents').replaceWith( v );
							}
							else{
								jQuery('#'+ k).append( v );
								
							}
							
						});
						
						jQuery.each(response['quote-widget-icon'], function(k,v){
							if (jQuery('#'+ k + ' div.wc-quote-icon').length > 0){
								jQuery('#'+ k + ' div.wc-quote-icon').replaceWith( v );
								
							}
							else{
								jQuery('#'+ k).append( v );
								
							}
							
						});
						
						jQuery('.elementor.elementor-'+ postid ).replaceWith( response['quote-widgets-elementor'] );
						if ( "1" == redirect ) {
							window.location.href = pageurl;
						}
					}	
					
				}
				
			});

		}
	});


	jQuery(document).on('click', '.wc_quote_single_page', function ($) {

		var current_button = jQuery(this);
		var action_name = '';
		var productId = jQuery(this).attr('data-product_id');
		

		if( current_button.hasClass('loading') ){
			return;
		}

		current_button.closest('form').find('a.added_to_quote').remove();

		if (current_button.is('.product_type_variable')) {
			if( current_button.hasClass('disabled') ){
				return;
			}
			action_name = 'wcquote_add_to_quote_variable';
		} else {
			action_name = 'wcquote_add_to_quote_single';
		}

		current_button.addClass('loading');

		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action: action_name,
				form_data : current_button.closest('form').serialize(),
				product_id: productId,
				quote_list_ids: quote_list_ids,
				quote_icon_ids: quote_icon_ids,
				post_id: postid,
				nonce: nonce,
			},
			success: function (response) {

				if ( 'success' == jQuery.trim(response) ) {
					if ( "1" == redirect ) {

						window.location.href = pageurl;
					} else {

						location.reload();
					}
					
				} else if( 'failed' == jQuery.trim(response) ){

					location.reload();
					
				} else {
					jQuery('.hide_on_quote').remove();
					current_button.removeClass('loading');
					if ( current_button.parent().find( '.added_to_quote' ).length === 0 ) {

						if ( response['browse_list'] == null ) {
							jQuery('.wc_quote_single_page[data-product_id="' + productId + '"]').show();
						}else{
							current_button.after( response['browse_list'] );
							jQuery('.wc_quote_single_page[data-product_id="' + productId + '"]').hide();
						}
					}
					
					jQuery('.wc-quote-li').replaceWith(response['mini-quote']);

					jQuery.each(response['quote-widget-list'], function(k,v){
						if (jQuery('#'+ k + ' table.wc-quote-widget__contents').length > 0){
							jQuery('#'+ k + ' table.wc-quote-widget__contents').replaceWith( v );
						}
						else{
							jQuery('#'+ k).append( v );
							
						}
						
					});
					
					jQuery.each(response['quote-widget-icon'], function(k,v){
						if (jQuery('#'+ k + ' div.wc-quote-icon').length > 0){
							jQuery('#'+ k + ' div.wc-quote-icon').replaceWith( v );
							
						}
						else{
							jQuery('#'+ k).append( v );
							
						}
						
					});
					// elementor widget
					jQuery('.elementor.elementor-'+ postid ).replaceWith( response['quote-widgets-elementor'] );
					if ( "1" == redirect ) {
						window.location.href = pageurl;
					}
				}

			}

		});
	});

	jQuery(document).on('click', '.wc-quote-remove', function (event) {
		
		"use strict";
		event.preventDefault();
		var quoteKey = jQuery(this).data('cart_item_key');
		if( jQuery(this).closest('li.mini_quote_item').css('opacity') == 0.5 ){
			return;
		}
		
		jQuery(this).closest('li.mini_quote_item').css('opacity', '0.5' );

		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action: 'wcquote_remove_quote_item',
				quote_key: jQuery(this).data('cart_item_key'),
				quote_list_ids: quote_list_ids,
				quote_icon_ids: quote_icon_ids,
				post_id: postid,
				nonce: nonce
			},
			success: function (response) {
				
				if ( response['quote_empty'] ) {
					location.reload();
				}

				jQuery('table.wc-quote-form__contents').replaceWith( response['quote-table'] );		
				jQuery('li.wc-quote-li').replaceWith( response['mini-quote'] );	
				jQuery('table.table_quote_totals').replaceWith( response['quote-totals'] );
				jQuery.each(response['quote-widget-list'], function(k,v){
					jQuery('#'+ k + ' table.wc-quote-widget__contents').replaceWith( v );
				})
				
				jQuery.each(response['quote-widget-icon'], function(k,v){
					jQuery('#'+ k + ' div.wc-quote-icon').replaceWith( v );
				})

				// elementor widget
				jQuery('.elementor.elementor-'+ postid ).replaceWith( response['quote-widgets-elementor'] );
				jQuery('div.woocommerce-notices-wrapper').html(response['message'] );
				
			}
		});
	});


	jQuery(document).on('click', '.wc-quote-remove-item', function (event) {
		event.preventDefault();
		
		var quoteKey = jQuery(this).data('cart_item_key');

		if( jQuery(this).closest('tr').css('opacity') == 0.5 ){
			return;
		}

		jQuery(this).closest('tr').css('opacity', '0.5' );

		jQuery.ajax({
			url: ajaxUrl,
			type: 'POST',
			data: {
				action: 'wcquote_remove_quote_item',
				quote_key: jQuery(this).data('cart_item_key'),
				quote_list_ids: quote_list_ids,
				quote_icon_ids: quote_icon_ids,
				post_id: postid,
				nonce: nonce
			},
			success: function (response) {
				
				if( response['quote_empty'] ){
					location.reload();
				}

				
				jQuery('table.wc-quote-form__contents').replaceWith( response['quote-table'] );
				jQuery('li.wc-quote-li').replaceWith( response['mini-quote'] );
				jQuery('table.table_quote_totals').replaceWith( response['quote-totals'] );
				
				jQuery.each(response['quote-widget-list'], function(k,v){
					jQuery('#'+ k + ' table.wc-quote-widget__contents').replaceWith( v );
				})
				
				jQuery.each(response['quote-widget-icon'], function(k,v){
					jQuery('#'+ k + ' div.wc-quote-icon').replaceWith( v );
				})

				// elementor widget
				// elementor widget
				if ( response['quote-widgets-elementor'] ) {
					jQuery('.elementor.elementor-'+ postid ).html( response['quote-widgets-elementor'] );
				}
				jQuery('div.woocommerce-notices-wrapper').html(response['message'] );
				// jQuery('body').animate({
			    //     scrollTop: jQuery('div.woocommerce-notices-wrapper').offset().top
			    // 	}, 500
			    // );
			}
		});
	});

	if (jQuery('li.wc-quote-li').length > 1) {
	    jQuery('li.wc-quote-li').not(':first').remove();
	}
});