$(document).ready(function () {
  function showLoader() {
    $("#loader-wapper").css("display", "flex");
    $("#loader_inner").css("display", "flex");
  }

  function hideLoader() {
    $("#loader-wapper").css("display", "none");
    $("#loader_inner").css("display", "flex");
  }

  function handleSubmit(event, formId) {
    event.preventDefault();

    var $form = $(formId);
    var formData = $form.serialize();
    var formAction = $form.attr("action");

    // Perform basic client-side validation
    if (!validateForm($form)) {
      Swal.fire({
        icon: "error",
        title: "Oops...",
        text: "Please fill out all fields correctly.",
      });
      hideLoader(); // Hide loader if validation fails
      return;
    }

    showLoader();

    $.ajax({
      url: formAction,
      method: "POST",
      data: formData,
      dataType: "json",
      success: function (response) {
        hideLoader();
        if (!response.error) {
          var formDataArray = $form.serializeArray();
          var formDataText = "";
          $.each(formDataArray, function (i, field) {
            formDataText += field.name + ": " + field.value + "\n";
          });
          $form[0].reset();
          Swal.fire({
            icon: "success",
            title: "Success!",
            text: formDataText,
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Oops...",
            text: response.message,
          });
        }
      },
      error: function () {
        hideLoader();
        Swal.fire({
          icon: "error",
          title: "Request failed",
          text: "Please try again.",
        });
      },
    });
  }

  function validateForm($form) {
    var isValid = true;

    // Check if all required fields are filled out
    $form.find("[required]").each(function () {
      if (!$(this).val()) {
        isValid = false;
        return false; // Exit each loop if a field is invalid
      }
    });

    return isValid;
  }

  $("#appoimentForm").on("submit", function (event) {
    handleSubmit(event, "#appoimentForm");
  });

  $("#contactForm").on("submit", function (event) {
    handleSubmit(event, "#contactForm");
  });

  $("#questionForm").on("submit", function (event) {
    if (typeof $("#gridCheck:checked").val() == "undefined") {
      Swal.fire({
        icon: "error",
        title: "Oops...",
        text: "Please select Terms & Conditions And Privacy Policy.",
      });
      return false;
    }
    handleSubmit(event, "#questionForm");
  });

  $(".newsletter-form").on("submit", function (event) {
    handleSubmit(event, ".newsletter-form");
  });

  $("#whatsappForm").on("submit", function (event) {
    handleSubmit(event, "#whatsappForm");
  });
});
