"use strict";

// Class definition
var KTWizard1 = function () {
	// Base elements
	var _wizardEl;
	var _formEl;
	var _wizardObj;
	var _validations = [];

	// Private functions
	var _initValidation = function () {
		// Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/
	}
	
	function passFunction(currentIndex)
	{
		var passAction = $('#passAction_' + currentIndex).val();
		if(passAction != null)
		{
			var actions = passAction.split(",");
			for(var num = 0; num < actions.length; num++)
			{
				var action_params = actions[num].split("<TO>");
				$('#' + action_params[1]).val($('#' + action_params[0]).val());
				//console.log('pass trigger' + action_params[1]);
				$('#' + action_params[1]).trigger('change');
			}
		}
	}
	
	function checkAge()
	{
		var kpField = $('#borang_kpbaru_semakan').val();
		if(kpField != null)
		{
			var info = processKP(kpField);
			var age = info[2];
			var program = Number($('#id_borang_program').val());
			if(program == 4)//OKU, then ignore
			{
				return true;
			}
			else if(program == 2 && age >= 60)//warga emas must 60 above
			{
				return true;
			}
			else if(program != 2 && program != 4 && age >= 18) //other program 18 above
			{
				return true;
			}
			else
			{
				swal.fire({
					text: "Umur pemohon tidak menepati syarat permohonan.",
					icon: "error",
					buttonsStyling: false,
					confirmButtonText: "OK!",
					customClass: {
						confirmButton: "btn font-weight-bold btn-light-primary"
					}
				}).then(function() {
				});
				return false;
			}
		}
		return true;
	}
	
	function equalFunction(currentIndex)
	{
		var equalAction = $('#equalAction_' + currentIndex).val();
		if(equalAction != null)
		{
			var actions = equalAction.split(",");
			for(var num = 0; num < actions.length; num++)
			{
				var action_params = actions[num].split("<EQUAL>");
				if($('#' + action_params[0]).val() != $('#' + action_params[1]).val())
				{
					swal.fire({
						text: "Info not match",
						icon: "error",
						buttonsStyling: false,
						confirmButtonText: "OK!",
						customClass: {
							confirmButton: "btn font-weight-bold btn-light-primary"
						}
					}).then(function() {
						$('#' + action_params[0]).focus();										
						$('#' + action_params[0] + '_label').css("color", "red");
					});
					return false;
				}
			}
		}
		return true;
	}
	
	function blockFunction(wizard, currentIndex)
	{
		var blockAction = $('#blockAction_' + currentIndex).val();
		if(blockAction != null)
		{
			var info = blockAction.split("<TR>");
			var param = 'checkInfo=' + $('#' + info[2]).val();
			param += '&borangitem=' + info[0];
			param += '&program=' + $('#id_borang_program').val();
			param += '&type=' + (info[1]==1?'blok':'check');
			$.ajax({
				type: "POST", 
				url: 'general-borang_pullinfo.php', 
				data: param,
				success: function(res){
					var allResult = JSON.parse(res);
					//console.log(allResult);
					if(allResult.block==1)
					{
						//console.log('hgere');
						swal.fire({
							text: allResult.message,
							icon: "error",
							buttonsStyling: false,
							confirmButtonText: "OK!",
							customClass: {
								confirmButton: "btn font-weight-bold btn-light-primary"
							}
						}).then(function() {
							//console.log('hgere');
						});
					}
					else
					{
						if(allResult.idToSet != '')
						{
							$('#' + allResult.idToSet).val(allResult.value);
						}
						saveFunction(wizard, currentIndex);
					}
				}
			});  //end ajax
		}
		else
		{
			saveFunction(wizard, currentIndex)
		}
	}
	
	function saveFunction(wizard, currentIndex)
	{
		var saveAction = $('#saveAction_' + currentIndex).val();
		if(saveAction != null)
		{
			//script_url<BRE>borang_div<BRE>table_name<BRE>id_table<BRE>id_insert<BRE>id_update
			var actions = saveAction.split("<BRE>");
			$(this).prop("disabled",true);
			//enabled all disabled input
			var disabled = $('#borangForm_' + currentIndex).find(':input:disabled').removeAttr('disabled');
			var param = $('#borangForm_' + currentIndex).serialize();
			disabled.attr('disabled', 'disabled');
			param += '&program=' + $('#id_borang_program').val();
			param += '&id_pemohon=' + $('#id_pemohon_borang').val();
			param += '&active=' + $('#active').val();
			param += '&current_id=' + $('#currentIdValue_' + currentIndex).val();
			param += '&borang_div=' + actions[1];
			param += '&table=' + actions[2];
			if(actions.length >= 3) param += '&id_table=' + actions[3];
			if(actions.length >= 4) param += '&id_insert=' + actions[4];
			if(actions.length >= 5) param += '&id_update=' + actions[5];
			//console.log(param);
			$.ajax({
				type: "POST", 
				url: actions[0], 
				data: param,
				success: function(res){
					if(res > 0)
					{
						if($('#updateIdAction_' + currentIndex).val() != "")
						{
							$('#' + $('#updateIdAction_' + currentIndex).val()).val(res);
						}
						$('#currentIdValue_' + currentIndex).val(res);
						pullFunction(wizard, currentIndex);
					}
					else
					{
						swal.fire({
							text: "Error. " + res,
							icon: "error",
							buttonsStyling: false,
							confirmButtonText: "OK!",
							customClass: {
								confirmButton: "btn font-weight-bold btn-light-primary"
							}
						}).then(function() {
							
						});
					}
					
				} 
			});  //end ajax
		}
		else
		{
			pullFunction(wizard, currentIndex);
		}
	}

	function pullFunction(wizard, currentIndex)
	{
		//console.log($('#isInfoPulled_' + (currentIndex + 1)).val());
		//always pull info if flag is not 1
		if($('#isInfoPulled_' + (currentIndex + 1)).val() == 0)
		//var pullInfoAction = $('#pullInfoAction_' + currentIndex).val();
		//if(pullInfoAction != null && ($('#divPemohonId_' + (currentIndex + 1)).val() != $('#id_pemohon_borang').val()))
		{
			console.log('pull action here');
			//var info = pullInfoAction.split("<TR>");
			var param = 'checkInfo=' + $('#id_pemohon_borang').val();
			//param += '&table=' + info[2];
			//param += '&column=' + info[3];
			param += '&nextDiv=' + $('#divKey_' + (currentIndex + 1)).val();
			param += '&program=' + $('#id_borang_program').val();
			param += '&type=pull';
			$.ajax({
				type: "POST", 
				url: 'general-borang_pullinfo.php', 
				data: param,
				success: function(res){
					var allResult = JSON.parse(res);
					//console.log(allResult);
					for(var count = 0; count < allResult.length; count++)
					{
						if(allResult[count][2] == 3) //datatable, load it
						{
							$('#' + allResult[count][0] + '_reloadbtn').click();
						}
						else
						{
							$('#' + allResult[count][0]).val(allResult[count][1]);
							if(allResult[count][2] == 2)
							{
								$('#' + allResult[count][0]).trigger('change');
							}
						}
							
					}
					$('#isInfoPulled_' + (currentIndex + 1)).val('1'); //set to 1 so wont pull again
					if($('#formReadOnly').val() == '1')
					{
						wizard.goTo(wizard.getStep());
					}
					else
					{
						wizard.goTo(wizard.getNewStep());
					}
					KTUtil.scrollTop();
				} 
			});  //end ajax
		}
		else
		{
			wizard.goTo(wizard.getNewStep());
			KTUtil.scrollTop();
		}
	}
	
	var _initWizard = function () {
		// Initialize form wizard
		_wizardObj = new KTWizard(_wizardEl, {
			startStep: 1, // initial active step number
			clickableSteps: false  // allow step clicking
		});

		// Validation before going to next page
		_wizardObj.on('change', function (wizard) {
			if (wizard.getStep() > wizard.getNewStep()) {
				return; // Skip if stepped back
			}
			
			var currentIndex = wizard.getStep() - 1;
			
			if($('#formReadOnly').val() == '1')
			{
				console.log(currentIndex);
				pullFunction(wizard, currentIndex);
				console.log(wizard.getStep());
				//console.log(wizard.getNewStep());
				//wizard.goTo(wizard.getStep());
				KTUtil.scrollTop();
				return;
			}
			
			var formValidator = JSON.parse($('#formValidator_' + currentIndex).val());
			
			//STEP 1
			// Validate form before change wizard step
			var validator = _validations[wizard.getStep() - 1]; // get validator for currnt step

			if (checkInput(formValidator))
			{
				var isProceed = true;
				
				//STEP 2
				//check if got any pass action
				passFunction(currentIndex);
				
				//STEP 3
				//check if got any equal action
				isProceed = equalFunction(currentIndex);
				
				//check age if any
				isProceed = checkAge();
				
				//STEP 4
				//check if got any block / pullinfo action
				if(isProceed)
				{
					isProceed = blockFunction(wizard, currentIndex);
				}
				/*
				console.log('after step 4');
				console.log(isProceed);
				//STEP 5
				//check if got any save action
				if(isProceed)
				{
					saveFunction(currentIndex);
				}
				
				if(isProceed)
				{
					//always pull info for next step if not same id_pemohon
					pullFunction(wizard.getStep());
				}
				
				if(isProceed)
				{
					//proceed to next
					wizard.goTo(wizard.getNewStep());
					KTUtil.scrollTop();
				}
				*/
			}

			return false;  // Do not change wizard step, further action will be handled by he validator
		});

		// Change event
		_wizardObj.on('changed', function (wizard) {
			KTUtil.scrollTop();
		});

		// Submit event
		_wizardObj.on('submit', function (wizard) {
			
			var currentIndex = wizard.getStep() - 1;
			var formValidator = JSON.parse($('#formValidator_' + currentIndex).val());
			
			//STEP 1
			// Validate form before change wizard step
			var validator = _validations[wizard.getStep() - 1]; // get validator for currnt step

			if (checkInput(formValidator))
			{
				if( $('#borang_carahantar').val() == 2 && Number($('#file_count_borang_muat_naik').val()) < 1)
				{
					swal.fire({
						text: "Sila muat naik dokumen yang diperlukan",
						icon: "error",
						buttonsStyling: false,
						confirmButtonText: "OK!",
						customClass: {
							confirmButton: "btn font-weight-bold btn-light-primary"
						}
					}).then(function() {
						
					});
				}
				else
				{
					Swal.fire({
						text: "Adakah anda pasti maklumat telah lengkap?.",
						icon: "success",
						showCancelButton: true,
						buttonsStyling: false,
						confirmButtonText: "Ya dan Hantar!",
						cancelButtonText: "Batal",
						customClass: {
							confirmButton: "btn font-weight-bold btn-primary",
							cancelButton: "btn font-weight-bold btn-default"
						}
					}).then(function (result) {
						if (result.value) {
							var param = 'id_pemohon=' + $('#id_pemohon_borang').val();
							param += '&program=' + $('#id_borang_program').val();
							param += '&borang_carahantar=' + $('#borang_carahantar').val();
							$.ajax({
								type: "POST", 
								url: "general-borang_submit.php", 
								data: param,
								success: function(res){
									if(res == 888)
									{
										swal.fire({
											text: "Permohonan berjaya.",
											icon: "success",
											buttonsStyling: false,
											confirmButtonText: "OK!",
											customClass: {
												confirmButton: "btn font-weight-bold btn-light-primary"
											}
										}).then(function() {
											window.location.reload();
										});
									}
									else if(res == 999) //for pemohon after success borang
									{
										swal.fire({
											text: "Permohonan berjaya. Sila Cetak dan Hantar Borang Permohonan Yang Lengkap Dengan Lampirannya ke Pejabat/Jabatan berhampiran yang dinyatakan. Permohonan Tidak Akan Diproses Tanpa Penghantaran Borang Permohonan yang Lengkap",
											icon: "success",
											buttonsStyling: false,
											confirmButtonText: "OK!",
											customClass: {
												confirmButton: "btn font-weight-bold btn-light-primary"
											}
										}).then(function() {
											window.location.href = "index_pemohon.php";
										});
									}
									else
									{
										swal.fire({
											text: "Error. " + res,
											icon: "error",
											buttonsStyling: false,
											confirmButtonText: "OK!",
											customClass: {
												confirmButton: "btn font-weight-bold btn-light-primary"
											}
										}).then(function() {
											
										});
									}
									
								} 
							});  //end ajax
						} else if (result.dismiss === 'cancel') {
							Swal.fire({
								text: "Permohonan ini tidak diteruskan!.",
								icon: "error",
								buttonsStyling: false,
								confirmButtonText: "Ok!",
								customClass: {
									confirmButton: "btn font-weight-bold btn-primary",
								}
							});
						}
					});
				}
			}
		});
	}

	return {
		// public functions
		init: function () {
			_wizardEl = KTUtil.getById('kt_wizard');
			_formEl = KTUtil.getById('kt_form');

			_initValidation();
			_initWizard();
		}
	};
}();

jQuery(document).ready(function () {
	KTWizard1.init();
});
