<template>
	<form v-if="active === 'register'" onsubmit = "event.preventDefault(); return false" id="register-form">
		<h3>Registration</h3>
		<div>{{errorMessage}}</div>
		<div>
		<label for='sender_name'>Name</label>
		<input id='register-name' required type='name' name='sender_name' placeholder=''
		spellcheck='false'>
		</div>
		<div>
		<label for='sender_email'>Email</label>
		<input v-on:input="checkPasswords" id='register-email' required type='email' name='sender_email' placeholder=''
		spellcheck='false'>
		</div>
		<div>
		<label for='sender_password'>Password</label>
		<input v-on:input="checkPasswords" id='register-password' required type='password' name='sender_password'
		placeholder='' spellcheck='false'>
		</div>
		<div>
		<label for='confirm_password'>Confirm Password</label>
		<input v-on:input="checkPasswords" id='confirm-password' required type='password'
		name='sender_password' placeholder='' spellcheck='false'>
		</div>
		<button @click="register($event)" class="submit-btn" type="submit">Submit</button>
	</form>
	<form v-if="active === 'forgot'" v-on:submit="forgotPassword" id="forgot-form">
	<h3>Forgot Password</h3>
	<div>
	<label for='sender_email'>Email</label>
	<input id='forgot-email' required type='email' name='sender_email' placeholder=''
	spellcheck='false'>
	</div>
	<button class="submit-btn" type="submit">Submit</button>
	</form>
	<img v-if="active === 'loading'" type="image/svg+xml" class="loading-icon" src="../../images/loading.svg" alt=""/>
	<div v-if="active === 'register-completed'">
		<img class="medium-icon" src="../../images/checked2.svg" alt="">
		<h3>Success!</h3>
		<p>A verification link has been sent to your inbox.</p>
	</div>
	<div v-if="active === 'forgot-completed'">
		<img class="medium-icon" src="../../images/checked2.svg" alt="">
		<h3>Success!</h3>
		<p>A password reset link has been sent.</p>
	</div>
	<div v-if="active === 'error'">
		<img class="medium-icon" src="../../images/warning-colored.svg" alt="">
		<h3>An Error Occured.</h3>
		<p>{{`${error}: ${errorMessage}`}}</p>
	</div>
	<div v-on:click="closeArea" class="cancel-button"></div>
</template>

<script>
function getCookie(name) {
  var re = new RegExp(name + "=([^;]+)")
  var value = re.exec(document.cookie)

  let v = (value != null) ? unescape(value[1]) : null
  return v
}

function getToken() {
	return fetch("/sanctum/csrf-cookie", {
		method: 'GET'
	}).then( () => {
		this.token = this.getCookie('XSRF-TOKEN')
		return this.token
	})
}
	function register(event) {
		event.preventDefault();
		event.stopPropagation();

		this.errorMessage = ''
		let name = document.getElementById("register-name").value
		let email = document.getElementById("register-email").value
		let password = document.getElementById("register-password").value
		let password_confirmation = document.getElementById("confirm-password").value

		this.active = 'loading'

		this.getToken().then(() => {fetch("/register", {
			method: 'POST',
			headers: {'Content-Type': 'application/json',
			'Accept': 'application/json',
			'X-XSRF-TOKEN': this.token},
			body: JSON.stringify({"name": name,
			"email": email,
			"password": password,
			"password_confirmation": password_confirmation})})
		.then(response => {
			//Give completed or error
			if (response.ok) {
				this.active = 'register-completed'
			} else if (response.status != 500) {
				response.json().then((e) => {
					try {
						for (let i in e.errors) {
							this.errorMessage = e.errors[i].flat().join("\n") +
							"\n" + this.errorMessage
						}
					} catch (x) {
						this.errorMessage = e.message
						}
					})
					this.active = 'register'
			} else {
				this.errorMessage = response.statusText
				this.active = 'register'
				}
		});
		})
		return false
	}

	function checkPasswords() {
		let passInput = document.getElementById('register-password')
		let passInput2 = document.getElementById('confirm-password')
		if (passInput.value != passInput2.value) {
			passInput2.setCustomValidity('Passwords must be matching')
		} else {
			passInput2.setCustomValidity('');
		}
	}

	function forgotPassword(event) {
		let email = document.getElementById("forgot-email").value
		this.active = 'loading'
		fetch("/forgot-password", {
			method: 'POST',
			headers: {'Content-Type': 'application/json',
			'Accept': 'application/json',
			'X-XSRF-TOKEN': this.token},
			body: JSON.stringify({"email": email})})
		.then(response => {
			if (response.ok) {
				this.active = 'forgot-completed'
			} else {
				this.error = response.status
				this.errorMessage = response.statusText
				this.active = 'error'
			}
			/* console.log(response.json()) */
		});
		event.preventDefault();
	}

	module.exports = {
		data() {
		return {active: 'register', token: '', errorMessage: ''}
		},
		methods: {
			getToken,
			getCookie,
			register,
			checkPasswords,
			forgotPassword,
			closeArea() {
				document.querySelector(".register-area").classList.remove("active")
			},
		},
		mounted() {
			this.getToken()			
		}
	}
</script>
