import {PixelioCartAbandonRecoveryMoreAjaxRequest} from "./pixelio_cart_abandon_recovery_more_ajax_request";

export class PixelioCartAbandonRecoveryMoreDeliveryInput {

	constructor() {
		const $btn = jQuery('#delivery-check-btn');
		const $input = jQuery('#delivery-postcode');
		const $result = jQuery('#delivery-result');
		if (!$btn.length || !$input.length) return;
		this.ajaxRequest = new PixelioCartAbandonRecoveryMoreAjaxRequest();
		var self = this;
		$btn.on('click', async function (e) {
			e.preventDefault();
			e.stopPropagation();
			const postcode = $input.val().trim();
			const productId = $input.attr('product-id');

			if (!postcode) {
				$result.html('<span class="error">Veuillez entrer un code postal</span>');
				return;
			}

			console.log("ok");


			$result.html('<span class="loading">Calcul en cours...</span>');
			$btn.prop('disabled', true);

			const formData = new FormData();
			formData.append('product_id', productId);
			formData.append('postcode', postcode);
			await self.ajaxRequest.makeAjaxRequest(
				'pixelio_calculate_delivery',
				formData,
				// ✅ success
				function (response) {
					const rates = response.data;

					let html = '';

					rates.forEach(rate => {
						html += `
                        <div class="delivery-rate">
                            <span>${rate.carrier}</span>
                            <strong>${rate.free ? 'Gratuit' : rate.price + '€'}</strong>
                        </div>
                    `;
					});

					$result.html(html);
					$btn.prop('disabled', false);
				},
				function (response) {
					const message = response?.data || 'Erreur';
					$result.html('<span class="error">' + message + '</span>');
					$btn.prop('disabled', false);
				},
			);

		});
	}
}
