document.addEventListener('DOMContentLoaded', function() {
  const formEl = document.querySelector('form');
  if (!formEl) return;

  formEl.addEventListener('submit', async function(e) {
    e.preventDefault();

    const form = e.target;
    const formData = new FormData(form);

    // Ambil CSRF token dari meta tag (lebih aman untuk file statis)
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    const headers = {};
    if (csrfToken) headers['X-CSRF-TOKEN'] = csrfToken;

    const response = await fetch(form.action, {
      method: 'POST',
      headers,
      body: formData
    });

    const data = await response.json();

    if (data.snap_token) {
      // Panggil Midtrans Snap Popup
      snap.pay(data.snap_token, {
        onSuccess: function(result) {
          // Redirect ke halaman success sesuai route
          window.location.href = '/orders/' + result.order_id + '/success';
        },
        onPending: function() {
          alert('Pembayaran sedang diproses...');
        },
        onError: function() {
          alert('Terjadi kesalahan dalam pembayaran.');
        },
        onClose: function() {
          alert('Anda menutup pembayaran sebelum selesai.');
        }
      });
    } else {
      // Jika metode bukan Midtrans (Transfer / COD), gunakan redirect_url bila tersedia
      if (data.redirect_url) {
        window.location.href = data.redirect_url;
      } else {
        window.location.reload();
      }
    }
  });
});