(function ($) {
	'use strict';

	function downloadPdfBase64(base64, filename) {
		var binary = atob(base64);
		var array = new Uint8Array(binary.length);
		for (var i = 0; i < binary.length; i++) {
			array[i] = binary.charCodeAt(i);
		}
		var blob = new Blob([array], { type: 'application/pdf' });
		var url = window.URL.createObjectURL(blob);
		var anchor = document.createElement('a');
		anchor.href = url;
		anchor.download = filename;
		document.body.appendChild(anchor);
		anchor.click();
		window.URL.revokeObjectURL(url);
		document.body.removeChild(anchor);
	}

	$(function () {
		if (typeof devikitSellsyOrder === 'undefined') {
			return;
		}

		$('#devikit-sellsy-create-invoice').on('click', function () {
			var $btn = $(this);
			var orderId = $btn.data('order-id');
			var $loading = $('#devikit-sellsy-loading');
			var $error = $('#devikit-sellsy-error');

			$btn.prop('disabled', true);
			$loading.addClass('is-visible').show();
			$error.text('');

			$.post(devikitSellsyOrder.ajaxUrl, {
				action: 'devikit_sellsy_create_invoice',
				order_id: orderId,
				nonce: devikitSellsyOrder.nonces.create
			})
				.done(function (response) {
					if (response && response.success) {
						window.location.reload();
						return;
					}
					$error.text(
						response && response.data && response.data.message
							? response.data.message
							: devikitSellsyOrder.i18n.createFail
					);
				})
				.fail(function () {
					$error.text(devikitSellsyOrder.i18n.createFail);
				})
				.always(function () {
					$btn.prop('disabled', false);
					$loading.removeClass('is-visible').hide();
				});
		});

		$('#devikit-sellsy-download-pdf').on('click', function () {
			var $btn = $(this);
			var invoiceId = $btn.data('invoice-id');
			var orderId = $btn.data('order-id');
			var originalText = $btn.text();

			$btn.prop('disabled', true).text(devikitSellsyOrder.i18n.downloading);

			$.post(devikitSellsyOrder.ajaxUrl, {
				action: 'devikit_sellsy_download_pdf',
				invoice_id: invoiceId,
				order_id: orderId,
				nonce: devikitSellsyOrder.nonces.pdf
			})
				.done(function (response) {
					if (response && response.success && response.data && response.data.pdf) {
						downloadPdfBase64(response.data.pdf, response.data.filename || 'sellsy-invoice.pdf');
					} else {
						window.alert(
							response && response.data && response.data.message
								? response.data.message
								: devikitSellsyOrder.i18n.pdfFail
						);
					}
				})
				.fail(function () {
					window.alert(devikitSellsyOrder.i18n.pdfFail);
				})
				.always(function () {
					$btn.prop('disabled', false).text(originalText);
				});
		});
	});
})(jQuery);
