//PHP pages URL to variables
let phpCheckURL = 'checkIdEmail.php';
let registerPHP = 'registerPH.php';

const pass = document.getElementById('userPass');
const rePass = document.getElementById('userRePass');
const repassDiv = document.getElementById('repassDiv');
const passCheck = document.getElementById('passCheck');
const termBox = document.getElementById('termbox');
//was intended to be used to make the button disable if we didn't check the termsBox
//but I didn't used it for now 
const registerBtn = document.getElementById('register')

const parag = document.querySelector('.parag');
const parag2 = document.querySelector('.parag2');

const formReg = document.querySelector('.formReg');
formReg.addEventListener('submit', function(event) {
    event.preventDefault();
    
    //checks if the two passwords match if they do continue to submit form
    if (pass.value != rePass.value) {
        passCheck.textContent = "Passwords don't match";
        passCheck.style.color = 'red';
    } else {
        const formData = new FormData(formReg);
        checkIdEmail(formData);
    }
});

//checks to see if the userName and email are used
// if they aren't calls register function
async function checkIdEmail(formData) {
    const response = await fetch (phpCheckURL, 
    {
        method: 'POST',
        body: formData
    });
    const phpResponse = await response.text();
    if (phpResponse.includes('nameUsed') && phpResponse.includes('emailUsed')) {
        parag.textContent = 'Username and email already used for registration';
    } else 
    if (phpResponse.includes('nameUsed')) {
        parag.textContent = 'Username already used';
    } else if (phpResponse.includes('emailUsed')) {
        parag.textContent = 'Email already used for registration';
    } else {
        register(formData);
    }
}

// sends the form data to a php page to insert it in a database
async function register(formData) {
    const response = await fetch (registerPHP, 
    {
        method: 'POST',
        body: formData
    });
    const phpResponse = await response.text();
    parag.textContent = phpResponse;
    if(phpResponse.includes("Registration successfull.")) {
        saveAndGo();
    }
}
 
function saveAndGo() {
    localStorage.setItem('smartCamUser', userName.value);
    localStorage.setItem('smartCamPass', userPass.value);
    setTimeout(function(){window.location.href = "../index.html";}, 3000);
  }
  
  