let number1 = document.getElementById('codeBox1');
let number2 = document.getElementById('codeBox2');
let number3 = document.getElementById('codeBox3');
let number4 = document.getElementById('codeBox4');


function getCodeBoxElement(index) {
  return document.getElementById('codeBox' + index);
}

function onKeyUpEvent(index,event) {

  const eventCode = event.which || event.keyCode;
  if (getCodeBoxElement(index).value.length === 1) {
    if (index !== 4) {
      getCodeBoxElement(index + 1).focus();
    } else {
      getCodeBoxElement(index).blur();
      // Submit code
      checkOtpCode(number1.value + number2.value + number3.value + number4.value)

    }
  }
  if (eventCode === 8 && index !== 1) {
    getCodeBoxElement(index - 1).focus();
  }
}

function onFocusEvent(index) {
  for (item = 1; item < index; item++) {
    const currentElement = getCodeBoxElement(item);
    if (!currentElement.value) {
      currentElement.focus();
      break;
    }
  }
}

function checkOtpCode(code) {

  

  let otpUrl = 'apps/verify-otp.php';

  let error_paragraph = document.getElementById('error');
  
  $.ajax({
      url: otpUrl,
      type: 'POST',
      data: { otp_code: code},
      success: function(response){


          
          if(response == 'failed'){
              error_paragraph.textContent = 'Failed to log you in';
          }else if(response == 'expired'){
              error_paragraph.textContent = 'Token expired, please try again';
          }else if(response == 'invalid_code'){

            error_paragraph.textContent = 'Invalid OTP code.';
              
          }else if(response == 'success'){
              
          setTimeout(() => {
            location.href = 'users/dashboard?page=dashboard';
          },2000);
          
          }else{
              alert(response)
          }
      }
  })

  
}