"use strict";

$(function() {
	
	//! -- [{ Authentication }] --
	
	(function() {
		
		let $form = $('#auth-form[data-type]');
		if( !$form.length ) return;
		
		let action = $form.attr('action');
		let type = $form.attr('data-type');
		
		$form.on('submit', function(e) {
			
			// prevent default send request;
			e.preventDefault();
			
			// Show Loader;
			Notiflix.Loading.circle();
			
			// create FormData Object;
			let formData = new FormData( $form.get(0) );
			formData.set('type', type);
			
			// send request;
			$.ajax({
				url: action,
				type: 'POST',
				cache: false,
				processData: false,
				contentType: false,
				data: formData,
				success: function(response) {
					
					// remove Loader;
					Notiflix.Loading.remove();
					
					try {
						
						let result = JSON.parse( response );
						let type = result.status ? 'success' : 'failure';
						
						let option = {
							message: result.message,
							centerVertical: true,
							className: 'text-center',
							closeButton: !result.status
						};
						
						if( result.status ) {
							option.callback = function() {
								Notiflix.Loading.circle();
								if( result.data['redirect'] ) 
									window.location.href = result.data['redirect'];
								else window.location.reload();
							};
						};
						
						bootbox.alert(option);
						
					} catch( err ) {
						
						toastr.error( 'A critical error occured' );
						
						console.log( err );
						
					};
					
				}
			});
			
		});
		
	})();
	
	// if vcode;
	
	(function() {
		
		$('[data-vcode]').click(function() {
			bootbox.prompt({
				title: "Resend Confirmation Email?",
				inputType: 'email',
				callback: function(value) {
					if( !value || value.trim() == '') return;
					Notiflix.Loading.hourglass();
					$.ajax({
						url: uss._ajax + '/resend-vcode.php',
						data: {
							email: value,
							nonce: uss._nonce
						},
						method: 'POST',
						success: function(response) {
							Notiflix.Loading.remove();
							let result = JSON.parse(response);
							bootbox.alert({
								title: uss.platform,
								message: result.message 
							});
						}
					});
				},
				message: "<div class='mb-1'>Please enter your account email address</div>",
				centerVertical: true,
				className: 'animate__animated animate__pulse'
			});
		});
		
	})();
	
});