/* ===== Enquiry form handler (per PHP-Contact-Form-Spec) =====
   USE_PHP = true  -> posts to send.php (PHP host) — current setup
   USE_PHP = false -> posts to Web3Forms (static host); needs access_key in the form
   If JS is off, the plain <form action="send.php"> still works (PHP redirects ?sent=1/0). */
var USE_PHP = true;
var PHP_ENDPOINT = 'send.php';

(function () {
  var form = document.getElementById('enquiry');
  if (!form) return;
  var resultEl = document.getElementById('form-result');
  var btn = form.querySelector('button[type=submit]');

  function setMsg(text, ok) {
    if (!resultEl) return;
    resultEl.textContent = text;
    resultEl.className = 'form-msg ' + (ok === true ? 'ok' : ok === false ? 'err' : '');
  }

  form.addEventListener('submit', function (e) {
    e.preventDefault();
    setMsg('Sending…', null);
    if (btn) { btn.disabled = true; btn.dataset.label = btn.textContent; btn.textContent = 'Sending…'; }

    var formData = new FormData(form);
    var endpoint, fetchOpts;

    if (USE_PHP) {
      endpoint = PHP_ENDPOINT;
      fetchOpts = {
        method: 'POST',
        body: formData,
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
      };
    } else {
      endpoint = 'https://api.web3forms.com/submit';
      var obj = {}; formData.forEach(function (v, k) { obj[k] = v; });
      fetchOpts = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(obj)
      };
    }

    fetch(endpoint, fetchOpts)
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (data && data.success) {
          form.reset();
          setMsg('Thank you — your message has been sent. We\u2019ll reply to your email soon.', true);
        } else {
          setMsg('Sorry, that didn\u2019t go through. Please try again or email info@tdl.com.my.', false);
        }
      })
      .catch(function () {
        setMsg('Sorry, that didn\u2019t go through. Please try again or email info@tdl.com.my.', false);
      })
      .then(function () {
        if (btn) { btn.disabled = false; btn.textContent = btn.dataset.label || 'Send message'; }
      });
  });
})();
