// assets/verify-email.js

document.addEventListener('DOMContentLoaded', function () {
  const emailInput = document.querySelector('input[name="email"]');
  const sendCodeBtn = document.createElement('button');
  sendCodeBtn.type = 'button';
  sendCodeBtn.textContent = 'Send Verification Code';

  const codeInput = document.createElement('input');
  codeInput.type = 'text';
  codeInput.name = 'email_code';
  codeInput.placeholder = 'Enter code';
  codeInput.style.display = 'none';

  const verifyBtn = document.createElement('button');
  verifyBtn.type = 'button';
  verifyBtn.textContent = 'Verify';
  verifyBtn.style.display = 'none';

  const statusSpan = document.createElement('span');

  emailInput.parentNode.appendChild(sendCodeBtn);
  emailInput.parentNode.appendChild(codeInput);
  emailInput.parentNode.appendChild(verifyBtn);
  emailInput.parentNode.appendChild(statusSpan);

  sendCodeBtn.addEventListener('click', () => {
    fetch('verify-email.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'email=' + encodeURIComponent(emailInput.value)
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          statusSpan.textContent = 'Code sent to email.';
          codeInput.style.display = 'inline';
          verifyBtn.style.display = 'inline';
        } else {
          statusSpan.textContent = data.error;
        }
      });
  });

  verifyBtn.addEventListener('click', () => {
    fetch('verify-code.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'code=' + encodeURIComponent(codeInput.value)
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          statusSpan.textContent = '✅ Verified';
          verifyBtn.disabled = true;
          sendCodeBtn.disabled = true;
          codeInput.readOnly = true;
          window.emailVerified = true;
        } else {
          statusSpan.textContent = '❌ Invalid code';
        }
      });
  });

  // Block final submit if email is not verified
  const form = document.getElementById('applicationForm');
  form.addEventListener('submit', (e) => {
    if (!window.emailVerified) {
      e.preventDefault();
      alert('Please verify your email before proceeding.');
    }
  });
});
