<!DOCTYPE html>
<html>

<!-- 
TO-DO LIST:
  * sanitize inputs to prevent CORS / XSS
-->

<head>
  <%- include("../partials/header.ejs") %>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
      integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://kit.fontawesome.com/c65a03b059.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/validator@13.5.2/validator.min.js"></script>
</head>

<body>

  <%- include("../partials/nav.ejs") %>
    <div class="section" id="loginForm" style="padding-left: 10rem; padding-right: 10rem;">

      <div class="block" style="padding-left: 15rem; padding-right: 15rem;">
        <h1 class="title">Sign Up</h1>
        <div class="box">

          <div class="field">
            <label class="label">First Name</label>
            <div class="control">
              <input type="text" class="input" placeholder="Enter your first name" id="userFirstName">
            </div>
          </div>

          <div class="field">
            <label class="label">Last Name</label>
            <div class="control">
              <input type="text" class="input" placeholder="Enter your last name" id="userLastName">
            </div>
          </div>

          <div class="field">
            <label class="label">Email</label>
            <div class="control has-icons-left">
              <input type="email" class="input" placeholder="Enter your account's email" id="userEmail">
              <span class="icon is-small is-left">
                <i class="fas fa-envelope"></i>
              </span>
            </div>
          </div>

          <div class="field">
            <label class="label">Password</label>
            <div class="control has-icons-left">
              <input type="password" class="input" placeholder="Enter your account's password" id="userPassword">
              <span class="icon is-small is-left">
                <i class="fas fa-lock"></i>
              </span>
            </div>
          </div>

          <div class="field">
            <label class="label">Confirm Password</label>
            <div class="control has-icons-left">
              <input type="password" class="input" placeholder="Re-enter your account's password"
                id="userConfirmPassword">
              <span class="icon is-small is-left">
                <i class="fas fa-lock"></i>
              </span>
            </div>
          </div>

          <div class="field">
            <label class="label">Select User Type</label>
            <div class="control">
              <div class="select">
                <select id="userType">
                  <option value="student">Student</option>
                  <option value="parent">Parent</option>
                  <!-- option value="admin">Admin</option -->
                </select>
              </div>
            </div>
          </div>

          <div class="field">
            <label class="label">Your Student ID (only enter if you are a student)</label>
            <div class="control">
              <input type="text" class="input" placeholder="Enter your student ID without spaces" id="userStudentId">
            </div>
          </div>

        </div>
        <button class="button is-dark" id="signupButton" onclick="attemptSignUp()">Sign Up</button>
      </div>
    </div>
    </div>

    <script>
      function attemptSignUp() {
        //clear error messages
        $('.validation-error, .signup-error').remove();

        //get all values
        let userFirstName = document.getElementById('userFirstName').value;
        let userLastName = document.getElementById('userLastName').value;
        let userEmail = document.getElementById('userEmail').value;
        let userPassword = document.getElementById('userPassword').value;
        let userConfirmPassword = document.getElementById('userConfirmPassword').value;
        let userType = document.getElementById('userType').value;
        let userStudentId = document.getElementById('userStudentId').value;

        // validate all inputs, throwing error if invalid
        if (userFirstName.length === 0) {
          $('#signupButton').after('<article id="firstNameError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">Do not forget your first name!</div></article>');
        } else if (userLastName.length === 0) {
          $('#signupButton').after('<article id="lastNameError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">Don\'t forget your last name!</div></article>');
        } else if (!validator.isEmail(userEmail)) {
          $('#signupButton').after('<article id="emailError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">The email you entered was invalid!</div></article>');
        } else if (userPassword !== userConfirmPassword) {
          $('#signupButton').after('<article id="passwordMatchError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">The passwords you entered don\'t match!</div></article>');
        } else if (userPassword.length < 6) {
          $('#signupButton').after('<article id="passwordError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">The password must be 6 characters long!</div></article>');
        } else if (!validator.isAlpha(userFirstName + userLastName)) {
          $('#signupButton').after('<article id="alphaError" class="message is-warning is-normal validation-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Error</p></div><div class="message-body">Your name can only include letters!</div></article>');
        } else {

          // since valid, try to signup with server

          axios.post('/auth/register', {
            fullName: userFirstName + " " + userLastName,
            firstName: userFirstName,
            lastName: userLastName,
            email: userEmail,
            password: userPassword,
            group: userType,
            studentId: userStudentId
          })
            .then(response => {
              if (response.status === 200) {
                $('#signupButton').after('<article id="signupSuccess" class="message is-success is-normal" style="margin-top: 2rem"> <div class="message-header"><p>Sign Up Success :)</p></div><div class="message-body">Your account has been registered. Please go to the login page and enter your account details. After you do this, you\'ll receive a confirmation link in your email inbox. Once you have confirmed your email, you can fully login to your account!</div></article>');
                $('#signupButton').prop("disabled", true);
              }
            })
            .catch(error => {
              console.log("error");
              console.log(error);
              if (error.response.status === 500 && error.response.data.includes("database")) {
                $('#signupButton').after('<article id="databaseError" class="message is-danger is-normal signup-error" style="margin-top: 2rem"> <div class="message-header"><p>Database Error</p></div><div class="message-body">Our database had some issues. Please try again in a few minutes. If the issue persists, contact support.</div></article>');
              } else if (error.response.status === 401 && error.response.data === "Error: User with this email already exists") {
                $('#signupButton').after('<article id="duplicateError" class="message is-danger is-normal signup-error" style="margin-top: 2rem"> <div class="message-header"><p>Duplicate User Error</p></div><div class="message-body">A user with this email already exists. If you forgot your password, please go to the login page and select the Forgot Password option to reset it.</div></article>');
              } else if (error.response.status === 400) {
                $('#signupButton').after('<article id="joiValidationError" class="message is-danger is-normal signup-error" style="margin-top: 2rem"> <div class="message-header"><p>Input Validation Error</p></div><div class="message-body">One of the values you provided us (such as your email, name, password or user type) was found to be invalid. Please try again. If the issue persists, contact</div></article>');
              } else {
                $('#signupButton').after('<article id="unknownError" class="message is-danger is-normal signup-error" style="margin-top: 2rem"> <div class="message-header"><p>Server Error</p></div><div class="message-body">Our servers had some unknown issues. Please try again in a few minutes. If the issue persists, contact support.</div></article>');
              }
            })
        }
      }
    </script>

</body>

<%- include("../partials/footer.ejs") %>

</html>