/*!
 * CartNinja Recovery - Public JS
 * Source file included in this plugin package.
 * Not minified - this is the full source.
 */

(function ($) {
	'use strict';

	var timer = null;
	var hasCapturedCheckoutData = false;

	function hasValue(value) {
		return !!String(value || '').trim();
	}

	function hasCheckoutContactDetails() {
		return hasValue($('#billing_phone').val()) || hasValue($('#billing_email').val());
	}

	function hasCheckoutConsent() {
		return $('#cartninja_checkout_consent').is(':checked');
	}

	function captureFields(extra) {
		var payload = {
			action: 'cartninja_capture_checkout_fields',
			nonce: cartninjaPublic.nonce,
			email: $('#billing_email').val() || '',
			phone: $('#billing_phone').val() || '',
			first_name: $('#billing_first_name').val() || '',
			country_code: $('#billing_country').val() || '+91',
			consent: hasCheckoutConsent() ? 'yes' : 'no',
			source: 'checkout'
		};

		payload = $.extend(payload, extra || {});

		if (payload.consent !== 'yes' || (!payload.email && !payload.phone)) {
			return $.Deferred().reject().promise();
		}

		return $.post(cartninjaPublic.ajaxUrl, payload);
	}

	$(document).on('input change', '#billing_email, #billing_phone, #billing_first_name, #billing_country, #cartninja_checkout_consent', function () {
		clearTimeout(timer);

		if (!hasCheckoutConsent() || !hasCheckoutContactDetails()) {
			hasCapturedCheckoutData = false;
			return;
		}

		timer = window.setTimeout(function () {
			captureFields().done(function () {
				hasCapturedCheckoutData = true;
			});
		}, 700);
	});

	$(function () {
		if (hasCheckoutConsent() && hasCheckoutContactDetails()) {
			captureFields().done(function () {
				hasCapturedCheckoutData = true;
			});
		}
	});
})(jQuery);
