
jQuery(document).ready(function ($) {

	$.ajax({
		url: pixelio_vars.api_is_available,
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
			'x-api-key': pixelio_vars.api_key
		},
		success: function (data) {
			if (data.available) {
				$('#pixelio-cart-abandon-recovery-more-beta-signup-container').show();
			}else{
				$('#pixelio-cart-abandon-recovery-more-beta-signup-container').hide();

			}
		}
	});

	/* ------------------------------
	   2. FAQ Toggle
	--------------------------------*/
	$('#pixelio-cart-abandon-recovery-more-beta-faq-toggle').on('click', function (e) {
		e.preventDefault();
		$('.pixelio-cart-abandon-recovery-more-beta-faq').toggle();
	});

	/* ------------------------------
	   3. Checkbox Join Beta
	--------------------------------*/
	$('#pixelio-cart-abandon-recovery-more-join-beta').on('change', function () {
		$('.pixelio-cart-abandon-recovery-more-beta-preference').toggle(this.checked).trigger('change');
		if(this.checked){
			$('input[name="comm_method"]').prop('checked', false);
		}
		$('.pixelio-cart-abandon-recovery-more-beta-extra-fields').hide();
		$('input[name="email_username"]').hide();
	});

	/* ------------------------------
	   4. Radio Communication Method
	--------------------------------*/
	$('input[name="comm_method"]').on('change', function () {
		$('.pixelio-cart-abandon-recovery-more-beta-extra-fields').show();
		if ($(this).val() === 'email') {
			$('input[name="email_username"]').show();
		} else {
			$('input[name="email_username"]').hide();
		}
	});

	/* ------------------------------
	   5. Bouton Signup
	--------------------------------*/
	$('#pixelio-cart-abandon-recovery-more-beta-signup-btn').on('click', function () {

		const joinBeta = $('#pixelio-cart-abandon-recovery-more-join-beta');
		if (!joinBeta.is(':checked')) {
			alert(pixelio_vars.msg_join_beta);
			return;
		}

		const commMethod = $('input[name="comm_method"]:checked');
		if (!commMethod.length) {
			alert(pixelio_vars.msg_select_comm);
			return;
		}

		let payload = {
			preferred_communication: commMethod.val()
		};

		if (joinBeta.is(':checked')) {
			payload.consent_definition = joinBeta.parent().text().trim();
		}

		if (commMethod.val() === 'email') {
			const email = $('input[name="email_username"]').val().trim();
			if (!email) {
				alert(pixelio_vars.msg_email_required);
				return;
			}
			payload.email = email;
		}
		payload.language = pixelio_vars.language;
		const btn = $('#pixelio-cart-abandon-recovery-more-beta-signup-btn');
		btn.prop('disabled', true).text(pixelio_vars.msg_signing_up);

		$.ajax({
			url: pixelio_vars.api_signup,
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'x-api-key': pixelio_vars.api_key
			},
			data: JSON.stringify(payload),
			success: function (data) {

				if (data.success) {
					let successMsg = $('<p>')
						.text(pixelio_vars.msg_success)
						.css({ fontWeight: 600, color: '#0D367A' });

					$('.pixelio-cart-abandon-recovery-more-beta-signup-wrapper').append(successMsg);

					setTimeout(() => {
						$('.pixelio-cart-abandon-recovery-more-beta-signup-wrapper').hide();
					}, 5000);

				} else {
					let errorMsg = $('<p>')
						.text(pixelio_vars.msg_error)
						.css({ color: 'red' });

					$('.pixelio-cart-abandon-recovery-more-beta-signup-wrapper').append(errorMsg);
				}
			},
			error: function () {
				alert(pixelio_vars.msg_server_error);
			},
			complete: function () {
				btn.prop('disabled', false).text('Sign Up');
			}
		});
	});

	/* ------------------------------
	   6. Récupération des quotas
	--------------------------------*/
	$.ajax({
		url: pixelio_vars.api_quota,
		method: 'GET',
		headers: {
			'Content-Type': 'application/json',
			'x-api-key': pixelio_vars.api_key
		},
		success: function (quotas) {
			const revenusMaxTexte = quotas.revenusMax === -1 ? '∞' : quotas.revenusMax + '€';
			const emailsMaxTexte = quotas.emailsMax === -1 ? '∞' : quotas.emailsMax;

			const emailPercent = quotas.emailsMax === -1
				? 100
				: Math.min((quotas.emailsSents / quotas.emailsMax) * 100, 100);

			const revenusPercent = quotas.revenusMax === -1
				? 100
				: Math.min((quotas.revenus / quotas.revenusMax) * 100, 100);

			$("#pixelio-cart-abandon-recovery-more-emails-bar")
				.css("width", emailPercent + "%")
				.closest(".pixelio-cart-abandon-recovery-more-quota-horizontal")
				.find(".pixelio-cart-abandon-recovery-more-quota-label strong")
				.text(quotas.emailsSents + " / " + emailsMaxTexte);

			$("#pixelio-cart-abandon-recovery-more-revenus-bar")
				.css("width", revenusPercent + "%")
				.closest(".pixelio-cart-abandon-recovery-more-quota-horizontal")
				.find(".pixelio-cart-abandon-recovery-more-quota-label strong")
				.text(quotas.revenus + "€ / " + revenusMaxTexte);
			if (((parseFloat(quotas.emailsMax)>-1 && (parseInt(quotas.emailsSents) > parseInt(quotas.emailsMax)))) || (parseFloat(quotas.revenusMax)> -1 && (parseFloat(quotas.revenus) > parseFloat(quotas.revenusMax)))) {
				$(".pixelio-cart-abandon-recovery-more-quota-footer").show();
			}else{
				$(".pixelio-cart-abandon-recovery-more-quota-footer").hide();

			}
		},
		error: function () {

		}
	});

	function resetOrDisconnect(disconnect) {
		$.ajax({
			url: ajaxurl,
			method: 'POST',
			data: {action: 'pixelio_reset_first_config', 'pixelio_disconnect': disconnect,					_ajax_nonce: pixelio_vars.nonce},
			success: function (response) {
				if (response.success) {
					window.location.href = 'admin.php?page=rivio-first-config';
				} else {
					alert(pixelio_vars.ajaxError);
				}
			},
			error: function () {
				alert(pixelio_vars.strings.ajaxError + ' ' + error);
			}
		});
	}

	/* ------------------------------
		   7. Reset first config
		--------------------------------*/
	$('#pixelio-cart-abandon-recovery-more-reset-first-config').on('click', function (e) {
		e.preventDefault();
		resetOrDisconnect(false);
	});

	$('#pixelio-cart-abandon-recovery-more-disconnect-first-config').on('click', function (e) {
		e.preventDefault();
		resetOrDisconnect(true);
	});


	/* ------------------------------
	   8. Menu toggle
	--------------------------------*/
	$('#pixelio-cart-abandon-recovery-more-settings-btn').on('click', function () {
		$('#pixelio-cart-abandon-recovery-more-submenu').toggle();
	});

});
