/** Sibs function to show feedback pop up
	*
	* @package Sibs/js
	*/

jQuery(function($) {
	$(document).ready(function() {
		var sibsBearerTokenAuthenticationSBO = null;
		var stepsWizard = null;
		var urlAux = ""; // add /pt
		var endURL = window.location.pathname;

		if (endURL.search("^\/[[A-Za-z]{2}") >= 0) { // check if find /pt/
			urlAux = endURL.replace(/^\//g, "");
			urlAux = urlAux.replace(/\/.*/g, "");
			urlAux = urlAux + "/";
		}
		var selectAmbiente = {
			'DEV': 'DEV',
			'TST': 'TST',
			'QLY': 'QLY',
			'CER': 'CER',
			'PRD': 'PRD'
		};

		/*
			in progresss
		*/
		$('.setup-applepay-domain').click(function(event) {
			event.preventDefault()

			$.ajax({
				type: 'POST',
				url: ajaxurl,
				data: {
					action: 'wc_sibs_onboard_applepay_domain',
				},
				success: function(response) {
					let message = ''
					const setup_button = $('.setup-applepay-domain')
					if (!response.success && response.message) {
						message = response.message
					}

					if (response.success) {
						setup_button.text('Success')
						setup_button.prop('disabled', true)
						return true
					}

					$('.setup-applepay-domain-error')
						.show()
						.text('Setup Failed: ' + message)
				},
			})
		})

		// function to generate random unique id
		function uuid() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random() * 16 | 0,
					v = c == 'x' ? r : (r & 0x3 | 0x8);
				return v.toString(16);
			});
		}

		var userID = uuid();
		jQuery("#show_debug_info").hide();

		$("#show_log").click(function() {
			jQuery("#show_debug_info").toggle();
		});

		jQuery("#webhookurl").click(function(event) {
			event.preventDefault();
		});

		function showLoading() {
			jQuery(".lds-ring").css("visibility", "visible");
		}

		function hideLoading() {
			jQuery(".lds-ring").css("visibility", "hidden");
		}

		//open wizard
		jQuery("#openWizard").click(function(event) {
			jQuery('.switch').hide();
			jQuery("#sibsConfigurationModal").show();
		});

		//close wizard
		jQuery(".closeModal").click(function(event) {
			jQuery('.switch').show();
			jQuery("#sibsConfigurationModal").hide();
		});

		//create steps function
		stepsWizard = jQuery("#wizard").steps({
			headerTag: "h2",
			bodyTag: "section",
			enablePagination: false,
			transitionEffect: "slideLeft",
			autoFocus: true,
		});

		var sibsRadioConf = $("input[name=sibsconfigurationRadio]");

		sibsRadioConf.change(function(e) {
			var valueCheckedSibsRadio = sibsRadioConf.filter(":checked").val();

			if (typeof valueCheckedSibsRadio === "undefined") {
				return false;
			}

			if (valueCheckedSibsRadio == "Automatic") {
				jQuery('.sibs-settings').hide();
				jQuery('#sibsConfigurationWizard').show();
			} else {
				jQuery('#sibsConfigurationWizard').hide();
				jQuery('.sibs-settings').show();
			}
		});

		sibsRadioConf.trigger("change");

		jQuery.each(selectAmbiente, function(key, value) {
			$('#fenvironment')
				.append($('<option>', {
						value: key
					})
					.text(value));
		});

		var loginSibs = jQuery("#loginSibs");
		var passwordSibs = jQuery("#passwordSibs");

		//take default environment
		var defaultEnvironment = jQuery('select[name="sibs_stg_general_environment"]').val();
		$('#fenvironment').val(defaultEnvironment).change();

		//check if is a valid email
		function isEmail(email) {
			var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			return regex.test(email);
		}

		//show erros
		function addErrorClass($place) {
			jQuery($place).addClass("error");
			jQuery($place).prev().addClass("error");
		}

		// hide errors
		function removeErrorClass($place) {
			jQuery($place).removeClass("error");
			jQuery($place).prev().removeClass("error");
		}

		// restart steps just when trying to login
		function restartSteps() {
			sibsBearerTokenAuthenticationSBO = null;
			var tab0 = jQuery("#wizard-t-0");
			var tab1 = jQuery("#wizard-t-1");
			var tab2 = jQuery("#wizard-t-2");
			var tab3 = jQuery("#wizard-t-3");

			var currentIndex = stepsWizard.steps('getCurrentIndex');

			for (var i = 0; i < currentIndex; i++) {
				stepsWizard.steps('previous');
			}

			jQuery("#divLoginSibs").show();
			jQuery("#activateLoginSibs").hide();

			tab1.parent().removeClass("done");
			tab1.parent().addClass("disabled");
			tab2.parent().removeClass("done");
			tab2.parent().addClass("disabled");
			tab3.parent().removeClass("done");
			tab3.parent().addClass("disabled");
		}

		// first tab - login
		jQuery("#firstLoginSibs").click(function(event) {
			var errorLoginSibs = jQuery("#errorLoginSibs");
			var errorPassSibs = jQuery("#errorPassSibs");
			var errorMessage = "";
			var ok = true;

			if (loginSibs.val() == "" || !isEmail(loginSibs.val())) {
				ok = false;

				errorMessage = (loginSibs.val() == "") ?
					__("E-mail is required", TRANSLATE) :
					__("Incorrect E-mail format", TRANSLATE);

				addErrorClass("#loginSibs");
				errorLoginSibs.html(errorMessage);
				errorLoginSibs.show();
			} else {
				removeErrorClass("#loginSibs");
				errorLoginSibs.hide();
			}

			if (passwordSibs.val() == "") {
				ok = false;

				errorMessage = __("Password is required", TRANSLATE);

				addErrorClass("#passwordSibs");
				errorPassSibs.html(errorMessage);
				errorPassSibs.show();
			} else {
				removeErrorClass("#passwordSibs");
				errorPassSibs.hide();
			}

			var defaultEnvironment = jQuery('#fenvironment').val();

			if (ok) {
				showLoading();
				$.ajax({
					type: "POST",
					url: urlAPISIBS + "/api.php",
					cache: false,
					async: true,
					crossDomain: true,
					// The key needs to match your method's input parameter (case-sensitive).
					data: ({
						"action": "LoginSBO",
						"deviceID": userID,
						"serverMode": defaultEnvironment,
						"login": loginSibs.val(),
						"pass": passwordSibs.val()
					}),
					success: function(data) {
						var obj = jQuery.parseJSON(data);
						sibsBearerTokenAuthenticationSBO = obj.return.token;

						hideLoading();

						if (obj.return.NxtFlow == "OK") {
							wizardTerminals();
						} else {
							jQuery("#divLoginSibs").hide();
							jQuery("#activateLoginSibs").show();
						}
					},
					error: function(errMsg) {
						sibsBearerTokenAuthenticationSBO = null;

						addErrorClass("#loginSibs");
						addErrorClass("#passwordSibs");

						errorMessage = __("Unable to log in with the data provided", TRANSLATE);

						errorPassSibs.html(errorMessage);
						errorPassSibs.show();

						hideLoading();
					}
				});
			}

		});

		// first tab - activate SMS
		jQuery("#secondLoginSibs").click(function(event) {
			var activationCodeSibs = jQuery("#activationCode");
			var errorActivationCode = jQuery("#errorActivationCode");
			var errorMessage = "";
			var ok = true;

			if (activationCodeSibs.val() == "") {
				ok = false;

				errorMessage = __("Activation Code is required", TRANSLATE);

				addErrorClass("#activationCode");
				errorActivationCode.html(errorMessage);
				errorActivationCode.show();
			} else {
				removeErrorClass("#passwordSibs");
				errorActivationCode.hide();
			}

			if (ok) {
				showLoading();
				$.ajax({
					type: "POST",
					url: urlAPISIBS + "/api.php",
					cache: false,
					async: true,
					crossDomain: true,
					// The key needs to match your method's input parameter (case-sensitive).
					data: ({
						"action": "ActivateSMSCode",
						"deviceID": userID,
						"serverMode": defaultEnvironment,
						"code": activationCodeSibs.val()
					}),
					headers: {
						"Authorization": sibsBearerTokenAuthenticationSBO
					},
					success: function(data) {
						wizardTerminals();
						errorActivationCode.hide();
						hideLoading();
					},
					error: function(errMsg) {
						addErrorClass("#activationCode");

						errorMessage = __("Unable to activate login with the code provided", TRANSLATE);
						errorActivationCode.html(errorMessage);
						errorActivationCode.show();
						hideLoading();
					}
				});
			}
		});

		// first tab - resend SMS
		jQuery("#requestNewcode").click(function(event) {
			var alertMessage = "";

			showLoading();
			$.ajax({
				type: "POST",
				url: urlAPISIBS + "/api.php",
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "ResendSMSCode",
					"deviceID": userID,
					"serverMode": defaultEnvironment
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					hideLoading();
					alertMessage = __("New code will be sent via SMS", TRANSLATE);
					alert(alertMessage);
				},
				error: function(errMsg) {
					hideLoading();
					alertMessage = __("Error when requesting new code via SMS", TRANSLATE);
					alert(alertMessage);
				}
			});

		});

		// second tab - wizard show terminals
		function wizardTerminals() {
			var alertMessage = "";

			stepsWizard.steps("next");
			showLoading();
			$.ajax({
				type: "POST",
				url: urlAPISIBS + "/api.php",
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "TerminalList",
					"deviceID": userID,
					"serverMode": defaultEnvironment
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					var terminalInfo = jQuery.parseJSON(data);

					jQuery("#selectTerminalOptions").html("");
					jQuery("#selectTerminalOptions").append('<option value="">' + __("Select Terminal", TRANSLATE) + '</option>');

					jQuery.each(terminalInfo.return.terminalList, function(i, val) {
						jQuery("#selectTerminalOptions").append('<option value="' + val.optionData + '">' + val.description + '</option>');
					});

					hideLoading();
				},
				error: function(errMsg) {
					hideLoading();

					alertMessage = __("No terminal have been found", TRANSLATE);
					alert(alertMessage);
				}
			});
		}

		//confirm selection of terminal
		jQuery("#terminalTabButton").click(function(event) {
			var alertMessage = "";
			var selectedTerminal = jQuery("#selectTerminalOptions");

			if (selectedTerminal.val() != "") {
				wizardFieldsUnconfirmed(selectedTerminal.val());
			} else {
				alertMessage = __("Select Terminal", TRANSLATE);
				alert(alertMessage);
			}
		});

		// third tab - show fields fullfilled
		function wizardFieldsUnconfirmed(mrchInfo) {
			var alertMessage = "";
			var explode = mrchInfo.split('-');

			jQuery("#unconfirmedBearerToken").val();
			jQuery("#unconfirmedIdTerminal").val(explode[0]);

			showLoading();
			$.ajax({
				type: "POST",
				url: urlAPISIBS + "/api.php",
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "WebhooksList",
					"deviceID": userID,
					"serverMode": defaultEnvironment,
					"login": loginSibs.val(),
					"pass": passwordSibs.val(),
					"TermnlCd": explode[0],
					"AccptrCd": explode[1],
					"MrchntCd": explode[2]
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					webhookInfo = jQuery.parseJSON(data);
					jQuery("#selectClientIDWebhookSecret").html("");

					jQuery.each(webhookInfo.return.webhookList, function(i, val) {
						var selectWebhookValue = val.clientID + "(DivSepSIBS)" + val.webhookSecret + "(DivSepSIBS)" + val.bearerToken;
						jQuery("#selectClientIDWebhookSecret").append('<option value="' + selectWebhookValue + '">' + val.description + '</option>');
					});

					jQuery("#selectClientIDWebhookSecret").trigger("change");
					stepsWizard.steps("next");

					hideLoading();
				},
				error: function(errMsg) {
					jQuery("#selectClientIDWebhookSecret").html("");
					jQuery("#selectClientIDWebhookSecret").append('<option value="">' + __("Neither Client ID nor Webhook Secret have been found", TRANSLATE) + '</option>');
					jQuery("#selectClientIDWebhookSecret").trigger("change");

					hideLoading();

					alertMessage = __("Neither Client ID nor Webhook Secret have been found", TRANSLATE);
					alert(alertMessage);
				}
			});
		}

		// fourth tab - Fill fields
		jQuery("#selectClientIDWebhookSecret").change(function(event) {
			var selectClientIDWebhookSecretVal = jQuery(this).val();
			var unconfirmedClientId = jQuery("#unconfirmedClientId");
			var unconfirmedWebhookSecret = jQuery("#unconfirmedWebhookSecret");
			var unconfirmedBearerToken = jQuery("#unconfirmedBearerToken");

			if (selectClientIDWebhookSecretVal != "") {
				var explode = selectClientIDWebhookSecretVal.split('(DivSepSIBS)');

				if (explode[0] != "" && !unconfirmedClientId.hasClass("sibsBlockedField")) {
					unconfirmedClientId.addClass("sibsBlockedField");
				} else if (explode[0] == "") {
					unconfirmedClientId.removeClass("sibsBlockedField");
				}

				if (explode[1] != "" && !unconfirmedWebhookSecret.hasClass("sibsBlockedField")) {
					unconfirmedWebhookSecret.addClass("sibsBlockedField");
				} else if (explode[1] == "") {
					unconfirmedWebhookSecret.removeClass("sibsBlockedField");
				}

				unconfirmedClientId.val(explode[0]);
				unconfirmedWebhookSecret.val(explode[1]);
				unconfirmedBearerToken.val(explode[2]);
			} else {
				unconfirmedClientId.removeClass("sibsBlockedField");
				unconfirmedWebhookSecret.removeClass("sibsBlockedField");
				unconfirmedClientId.val("");
				unconfirmedWebhookSecret.val("");
				unconfirmedBearerToken.val("");
			}
		});

		jQuery("#unconfirmedData").click(function(event) {
			showLoading();

			var alertMessage = "";
			var unconfirmedIdTerminal = jQuery("#unconfirmedIdTerminal").val();
			var unconfirmedBearerToken = jQuery("#unconfirmedBearerToken").val();
			var unconfirmedClientId = jQuery("#unconfirmedClientId").val();
			var unconfirmedWebhookSecret = jQuery("#unconfirmedWebhookSecret").val();

			if (unconfirmedIdTerminal == "" || unconfirmedBearerToken == "" ||
				unconfirmedClientId == "" || unconfirmedWebhookSecret == "") {
				hideLoading();

				alertMessage = __("All fields must be fulfilled", TRANSLATE);
				alert(alertMessage);
				return false;
			}

			jQuery('input[name="sibs_stg_general_merchant_no"]').val(unconfirmedIdTerminal);
			jQuery('textarea[name="sibs_stg_general_bearer_token"]').val(unconfirmedBearerToken);
			jQuery('input[name="sibs_stg_general_client_id"]').val(unconfirmedClientId);
			jQuery('select[name="sibs_stg_general_environment"]').val(defaultEnvironment);
			jQuery('input[name="sibs_stg_general_webhook_secret"]').val(unconfirmedWebhookSecret);
			jQuery('input[name="sibs_save"]').click();

			hideLoading();
		});

		// return tab
		jQuery(".previousWizard").click(function(event) {
			stepsWizard.steps("previous");
		});

		// restart steps when closing window
		jQuery(".closeModal").click(function(event) {
			restartSteps();
		});

		jQuery(".done").click(function(event) {
			event.stopPropagation();
			return false;
		});
	});
});