import {
	PixelioCartAbandonRecoveryMoreUpdate
} from "../components/pixelio_cart_abandon_recovery_more_update_popup";
jQuery(function ($) {
	const table = $('#pixelio-rgpd-table');

	if (table.length && $.fn.DataTable) {
		table.DataTable({
			order: [[3, 'desc']],
			pageLength: 25
		});
	}

	function showLoader() {
		$('#pixelio-cart-abandon-recovery-more-loader-overlay').css('display', 'flex');
	}

	function hideLoader() {
		$('#pixelio-cart-abandon-recovery-more-loader-overlay').hide();
	}

	function runRgpdAction(action, contactId, confirmMessage) {
		if (!window.confirm(confirmMessage)) {
			return;
		}
		console.log(action, contactId);
		showLoader();

		$.post(pixelioRgpd.ajaxUrl, {
			action: action,
			contact_id: contactId,
			nonce: pixelioRgpd.nonce
		})
			.done(function (response) {
				if (!response || !response.success) {
					alert(response?.data?.message || 'Unexpected error.');
					return;
				}

				if (action === 'pixelio_rgpd_export_contact') {
					const blob = new Blob(
						[JSON.stringify(response.data, null, 2)],
						{ type: 'application/json' }
					);

					const url = URL.createObjectURL(blob);
					const link = document.createElement('a');

					link.href = url;
					link.download = 'rivio-gdpr-export-contact-' + contactId + '.json';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);

					URL.revokeObjectURL(url);
					return;
				}

				alert(response.data.message || 'Done.');
				window.location.reload();
			})
			.fail(function () {
				alert('Request failed.');
			})
			.always(function () {
				hideLoader();
			});
	}

	$(document).on('click', '.pixelio-rgpd-export', function () {
		runRgpdAction(
			'pixelio_rgpd_export_contact',
			$(this).data('contact-id'),
			'Export all personal data for this contact?'
		);
	});

	$(document).on('click', '.pixelio-rgpd-unsubscribe', function () {
		runRgpdAction(
			'pixelio_rgpd_unsubscribe_contact',
			$(this).data('contact-id'),
			'Unsubscribe this contact from all marketing emails?'
		);
	});

	$(document).on('click', '.pixelio-rgpd-anonymize', function () {
		runRgpdAction(
			'pixelio_rgpd_anonymize_contact',
			$(this).data('contact-id'),
			'Anonymize this contact? This action cannot be undone.'
		);
	});
});
