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


jQuery(function($) {
	$(document).ready(function() {
		var sibsBearerTokenAuthenticationSBO = null;
		var stepsWizard = null;
		var terminalInfo = null;
		//get store url
		var urlStore = document.location.protocol + "//" + window.location.hostname + "/";
		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 urlAPISIBS = urlStore + urlAux + "modules/sibs/controllers/admin/sibs-api.php";
		
		// 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: "h3",
			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('#sibscriterion_form').hide();
				jQuery('#sibsConfigurationWizard').show();
			} else {
				jQuery('#sibsConfigurationWizard').hide();
				jQuery('#sibscriterion_form').show();
			}
		});

		sibsRadioConf.trigger("change");

		//set all tabs info
		jQuery('#wizard-p-0').html(
			"<p> \
				<h3>Login to your SIBS BackOffice</h3> \
			</p> \
			<div id=\"divLoginSibs\"> \
				<form id=\"formLoginSibs\"> \
					<div class=\"div-fields-content\"> \
						<p> \
							<label for=\"fmail\">Email:</label> \
							<input type=\"text\" value=\"\" placeholder=\"Enter your Email\" id=\"loginSibs\"> \
							<label id=\"errorLoginSibs\" class=\"error\"></label> \
						</p> \
						<p> \
							<label for=\"fpass\">Password:</label> \
							<input type=\"password\" value=\"\" placeholder=\"Enter your password\" id=\"passwordSibs\"> \
							<label id=\"errorPassSibs\" class=\"error\"></label> \
						</p> \
					</div> \
					<div class=\"div-fields-content\"> \
						<p> \
							<label for=\"fenvironment\">Environment:</label>  \
							<select name=\"fenvironment\" id=\"fenvironment\"> \
								<option value=\"DEV\">DEV</option> \
								<option value=\"TST\">TST</option> \
								<option value=\"CER\">CER</option> \
								<option value=\"QLY\">QLY</option> \
								<option value=\"LIVE\">LIVE</option> \
							</select> \
						</p> \
					</div> \
					<div class=\"div-fields-content\"> \
						<p> \
							<button type=\"button\" id=\"firstLoginSibs\">Login</button> \
						</p> \
					</div> \
				</form> \
			</div> \
			<div id=\"activateLoginSibs\"> \
				<p>Enter the activation code you received via SMS</p> \
				<form id=\"formActvateLoginSibs\"> \
					<p> \
						<label for=\"fcode\">Activation Code:</label> \
						<input type=\"text\" value=\"\" placeholder=\"Enter your activation code\" id=\"activationCode\"> \
						<label id=\"errorActivationCode\" class=\"error\"></label> \
					</p> \
					<p> \
						<button type=\"button\" id=\"secondLoginSibs\">Confirm</button> \
						<button type=\"button\" id=\"requestNewcode\" class=\"whiteButton\">Request new code</button> \
					</p> \
				</form> \
			</div>"
		);
		jQuery('#wizard-p-1').html(
			"<p> \
				<h3>Select the terminal you want to configure</h3> \
			</p> \
			<p> \
				<select id=\"selectTerminalOptions\"> \
					<option value=\"\">Loading ...</option> \
				</select> \
			</p> \
			<p> \
				<button type=\"button\" id=\"terminalTabButton\">Next</button> \
			</p>"
		);
		jQuery('#wizard-p-2').html(
			"<p> \
				<h3>Check the data and change the Webhook if necessary</h3> \
			</p> \
			<p> \
				<label>Selecione o Webhook:</label> \
				<select id=\"selectClientIDWebhookSecret\" style=\"width: 100%\"> \
					<option value=\"\">Loading...</option> \
				</select> \
			</p> \
			<div class=\"div-fields-content\"> \
				<p class=\"p-fields-content-left\"> \
					<label>Terminal ID:</label> \
					<input type=\"text\" placeholder=\"Terminal ID\" id=\"unconfirmedIdTerminal\" style=\"width: 100%\" class=\"sibsBlockedField\" /> \
				</p> \
				<p class=\"p-fields-content-right\"> \
					<label>Bearer Token:</label> \
					<input type=\"text\" placeholder=\"Bearer Token\" id=\"unconfirmedBearerToken\" style=\"width: 100%\" class=\"sibsBlockedField\" /> \
				</p> \
			</div> \
			<div class=\"div-fields-content\"> \
				<p class=\"p-fields-content-left\"> \
					<label>Client ID:</label> \
					<input type=\"text\" placeholder=\"Client ID\" id=\"unconfirmedClientId\" style=\"width: 100%\" class=\"sibsBlockedField\" /> \
				</p> \
				<p class=\"p-fields-content-right\"> \
					<label>Webhook Secret:</label> \
					<input type=\"text\" placeholder=\"Webhook Secret\" id=\"unconfirmedWebhookSecret\" style=\"width: 100%\" class=\"sibsBlockedField\" /> \
				</p> \
			</div> \
			<div class=\"div-fields-content\"> \
				<p> \
					<button type=\"button\" class=\"previousWizard whiteButton\">Back</button> \
					<button type=\"button\" id=\"unconfirmedData\">Finish</button> \
				</p> \
			</div>"
		);

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

		//take default environment
		var defaultEnvironment = jQuery('#SIBS_CC_SERVER').val();
		if (defaultEnvironment == "LIVE") {
			jQuery('#fenvironment').val(defaultEnvironment);
		} else {
			defaultEnvironment = "TEST";
		}

		//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");

		}
		// second tab - wizard show terminals
		function wizardTerminals() {
			stepsWizard.steps("next");
			showLoading();
			$.ajax({
				type: "POST",
				url: urlAPISIBS,
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "terminalList",
					"deviceID": userID,
					"ambiente": defaultEnvironment
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					terminalInfo = jQuery.parseJSON(data);
					jQuery("#selectTerminalOptions").html("");
					jQuery("#selectTerminalOptions").append('<option value="">Select Terminal</option>');
					jQuery.each(terminalInfo.return.terminalList, function(i, val) {
						jQuery("#selectTerminalOptions").append('<option value="' + val.optionData + '">' + val.description + '</option>');
					});
					hideLoading();
				},
				error: function(errMsg) {
					hideLoading();
					alert("None terminal have been found.");
				}
			});
		}
		// third tab - show fields fullfilled
		function wizardFieldsUnconfirmed(mrchInfo) {
			var explode = mrchInfo.split('-');
			showLoading();
			jQuery("#unconfirmedBearerToken").val();
			jQuery("#unconfirmedIdTerminal").val(explode[0]);
			$.ajax({
				type: "POST",
				url: urlAPISIBS,
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "webhooksList",
					"deviceID": userID,
					"ambiente": defaultEnvironment,
					"TermnlCd": explode[0],
					"AccptrCd": explode[1],
					"mrchntcd": explode[2],
					"login": loginSibs.val(),
					"pass": passwordSibs.val()
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					webhookInfo = jQuery.parseJSON(data);
					jQuery("#selectClientIDWebhookSecret").html("");
					jQuery.each(webhookInfo.return.terminalList, function(i, val) {
						jQuery("#selectClientIDWebhookSecret").append('<option value="' + val.optionData + '">' + 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</option>');
					jQuery("#selectClientIDWebhookSecret").trigger("change");
					hideLoading();
					alert("Neither Client ID nor Webhook Secret have been found. Please try again later");
				}
			});
		}

		jQuery("#selectClientIDWebhookSecret").change(function(event) {
			var selectClientIDWebhookSecret = jQuery(this).val();
			var unconfirmedClientId = jQuery("#unconfirmedClientId");
			var unconfirmedWebhookSecret = jQuery("#unconfirmedWebhookSecret");
			var unconfirmedBearerToken = jQuery("#unconfirmedBearerToken");
			if (selectClientIDWebhookSecret != "") {
				var explode = selectClientIDWebhookSecret.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("");
			}
		});

		// ajax for the first login
		jQuery("#firstLoginSibs").click(function(event) {
			var errorLoginSibs = jQuery("#errorLoginSibs");
			var errorPassSibs = jQuery("#errorPassSibs");
			var ok = true;

			if (loginSibs.val() == "" || !isEmail(loginSibs.val())) {
				addErrorClass("#loginSibs");
				if (loginSibs.val() == "") {
					errorLoginSibs.html("E-mail é obrigatório");
				} else {
					errorLoginSibs.html("Formato de e-mail incorreto");
				}
				errorLoginSibs.show();
				ok = false;
			} else {
				removeErrorClass("#loginSibs");
				errorLoginSibs.hide();
			}

			if (passwordSibs.val() == "") {
				addErrorClass("#passwordSibs");
				if (passwordSibs.val() == "") {
					errorPassSibs.html("Palavra-passe é obrigatório");
				}
				errorPassSibs.show();
				ok = false;
			} else {
				removeErrorClass("#passwordSibs");
				errorPassSibs.hide();
			}

			if (ok) {
				showLoading();
				defaultEnvironment = jQuery('#fenvironment').val();
				$.ajax({
					type: "POST",
					url: urlAPISIBS,
					cache: false,
					async: true,
					crossDomain: true,
					// The key needs to match your method's input parameter (case-sensitive).
					data: ({
						"action": "LoginSBO",
						"deviceID": userID,
						"ambiente": 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) {
						//alert(errMsg);
						addErrorClass("#loginSibs");;
						addErrorClass("#passwordSibs");
						errorPassSibs.html("Unable to log in with the data provided");
						errorPassSibs.show();
						sibsBearerTokenAuthenticationSBO = null;
						hideLoading();
					}
				});
			}

		});

		// ajax for actvating login
		jQuery("#secondLoginSibs").click(function(event) {
			var activationCodeSibs = jQuery("#activationCode");
			var errorActivationCode = jQuery("#errorActivationCode");
			var ok = true;

			if (activationCodeSibs.val() == "") {
				addErrorClass("#activationCode");
				if (activationCodeSibs.val() == "") {
					errorActivationCode.html("Activation Code is mandatory");
				}
				errorActivationCode.show();
				ok = false;
			} else {
				removeErrorClass("#passwordSibs");
				errorActivationCode.hide();
			}

			if (ok) {
				showLoading();
				$.ajax({
					type: "POST",
					url: urlAPISIBS,
					cache: false,
					async: true,
					crossDomain: true,
					// The key needs to match your method's input parameter (case-sensitive).
					data: ({
						"action": "ActivateCode",
						"deviceID": userID,
						"ambiente": defaultEnvironment,
						"code": activationCodeSibs.val()
					}),
					headers: {
						"Authorization": sibsBearerTokenAuthenticationSBO
					},
					success: function(data) {
						//alert(data);
						//Successcode
						wizardTerminals();
						errorActivationCode.hide();
						hideLoading();
					},
					error: function(errMsg) {
						//alert(errMsg);
						addErrorClass("#activationCode");;
						errorActivationCode.html("Unable to activate login with the code provided");
						errorActivationCode.show();
						hideLoading();
					}
				});
			}
		});

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

		// ajax for requesting new code
		jQuery("#requestNewcode").click(function(event) {
			showLoading();
			$.ajax({
				type: "POST",
				url: urlAPISIBS,
				cache: false,
				async: true,
				crossDomain: true,
				// The key needs to match your method's input parameter (case-sensitive).
				data: ({
					"action": "ReSendCode",
					"deviceID": userID,
					"ambiente": defaultEnvironment
				}),
				headers: {
					"Authorization": sibsBearerTokenAuthenticationSBO
				},
				success: function(data) {
					hideLoading();
					alert("New code will be sent via SMS");
				},
				error: function(errMsg) {
					hideLoading();
					alert("Error when requesting new code via SMS");
				}
			});
		});

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

			if (selectedTerminal.val() != "") {
				wizardFieldsUnconfirmed(selectedTerminal.val());
			} else {
				alert("Select a terminal");
			}
		});

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

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

		// see all unconfirmed info before confirm
		jQuery("#unconfirmedData").click(function(event) {
			showLoading();
			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 == "") {
				alert("All fields must be fulfilled");
				hideLoading();
				return false;
			}

			jQuery("#SIBS_GENERAL_TERMINALID").val(unconfirmedIdTerminal);
			jQuery("#SIBS_GENERAL_BEARER").val(unconfirmedBearerToken);
			jQuery("#SIBS_GENERAL_CLIENTID").val(unconfirmedClientId);
			jQuery("#SIBS_MULTIBANCO_SECRET").val(unconfirmedWebhookSecret);
			jQuery('#SIBS_CC_SERVER').val(defaultEnvironment);
			jQuery('#SIBS_MBWAY_SERVER').val(defaultEnvironment);
			jQuery('#SIBS_MULTIBANCO_SERVER').val(defaultEnvironment);
			jQuery("#module_form").submit();

			hideLoading();
		});
	});
});