/**
 * PPDB REGISTRATION FORM & AJAX HANDLER
 */

document.addEventListener('DOMContentLoaded', () => {
  const ppdbForm = document.getElementById('ppdbForm');
  const alertContainer = document.getElementById('ppdbAlert');

  if (ppdbForm) {
    ppdbForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      const submitBtn = ppdbForm.querySelector('button[type="submit"]');
      const originalText = submitBtn.innerHTML;

      // Collect Form Data
      const formData = {
        nama: document.getElementById('namaSiswa').value,
        whatsapp: document.getElementById('nomorWa').value,
        email: document.getElementById('emailSiswa') ? document.getElementById('emailSiswa').value : '',
        asalSekolah: document.getElementById('asalSekolah').value,
        pilihanJurusan: document.getElementById('pilihanJurusan').value,
        jenisKelamin: document.getElementById('jenisKelamin') ? document.getElementById('jenisKelamin').value : 'Laki-laki',
        alamat: document.getElementById('alamatSiswa') ? document.getElementById('alamatSiswa').value : ''
      };

      try {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Memproses...';

        const response = await fetch('/api/ppdb/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formData)
        });

        const result = await response.json();

        if (alertContainer) {
          alertContainer.style.display = 'block';
          if (result.success) {
            alertContainer.className = 'alert alert-success';
            
            let waButton = '';
            if (result.adminNotifyLink) {
              waButton = `<a href="${result.adminNotifyLink}" target="_blank" class="btn btn-success" style="display: inline-block; margin-top: 1rem;"><i class="fa-brands fa-whatsapp"></i> Konfirmasi Pendaftaran via WhatsApp</a>`;
            }

            alertContainer.innerHTML = `
              <div style="background: rgba(16, 185, 129, 0.15); border: 1px solid #10B981; color: #065F46; padding: 1.25rem; border-radius: 12px; margin-bottom: 1.5rem;">
                <h4 style="margin-bottom: 0.5rem; font-size: 1.1rem; color: #065F46;"><i class="fa-solid fa-circle-check"></i> Pendaftaran Berhasil!</h4>
                <p>Nomor Registrasi Anda: <strong>${result.registrationId}</strong></p>
                <p>${result.message}</p>
                ${waButton}
              </div>
            `;
            ppdbForm.reset();
          } else {
            alertContainer.className = 'alert alert-danger';
            alertContainer.innerHTML = `
              <div style="background: rgba(239, 68, 68, 0.15); border: 1px solid #EF4444; color: #991B1B; padding: 1.25rem; border-radius: 12px; margin-bottom: 1.5rem;">
                <p><i class="fa-solid fa-triangle-exclamation"></i> ${result.message}</p>
              </div>
            `;
          }
        }
      } catch (err) {
        console.error(err);
        if (alertContainer) {
          alertContainer.style.display = 'block';
          alertContainer.innerHTML = `
            <div style="background: rgba(239, 68, 68, 0.15); border: 1px solid #EF4444; color: #991B1B; padding: 1.25rem; border-radius: 12px; margin-bottom: 1.5rem;">
              <p><i class="fa-solid fa-wifi"></i> Gagal terhubung ke server. Silakan coba lagi.</p>
            </div>
          `;
        }
      } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
      }
    });
  }
});
