$(document).ready(function () {
  setTimeout(function () {
    jQuery("#timeoutmsg").hide();
  }, 7000);

  var form = $("#contactForm");

  $("#contactForm").validate({
    rules: {
      name: "required",
      email: {
        required: true,
        email: true,
        regex: true,
      },
      subject: {
        required: true,
        minlength: 10,
        maxlength: 5000,
      },
      message: {
        required: true,
        minlength: 10,
        maxlength: 5000,
      },
    },

    messages: {
      name: "Please enter your name",
      email: {
        required: "Please enter your email address",
        email: "Please enter a valid email address",
        regex: "Please enter a valid email address",
      },
      subject: {
        required: "Please enter subject",
        minlength: "Please enter at least 10 characters or more",
        maxlength: "Maximum limit is 5000 characters",
      },
      message: {
        required: "Please enter your comment",
        minlength: "Please enter at least 10 characters or more",
        maxlength: "Maximum limit is 5000 characters",
      },
    },
    errorPlacement: function (error, element) {
      error.insertAfter(element.parent());
    },
    submitHandler: function (form) {
      //function to disable multiclicks

      submitEnquiry();
      return false; // Prevent default form submission
    },
    invalidHandler: function (event, validator) {
      // This will be called when the form is invalid
      event.preventDefault(); // Prevent form submission
    },
  });
  // Custom email regex validation method
  $.validator.addMethod(
    "regex",
    function (value, element) {
      // Adjust the regex as needed for your requirements
      var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return emailRegex.test(value);
    },
    "Please enter a valid email"
  );
  $.validator.addMethod(
    "pattern",
    function (value, element) {
      return (
        this.optional(element) || /^\+?[1-9]\d{1,4}[\s]?\d{7,10}$/.test(value)
      );
    },
    "Please enter a valid phone number."
  );
});

function executeRecaptcha() {
  try {
    grecaptcha
      .execute(recaptchaSiteKey, {
        action: "validate_captcha",
      })
      .then(function (token) {
        document.getElementById("g-recaptcha-response").value = token;
      });
  } catch (e) {
    console.error("reCAPTCHA error:", e);
  }
}

$(document).ready(function () {
  grecaptcha.ready(function () {
    // do request for recaptcha token
    // response is promise with passed token
    executeRecaptcha();
  });
});

function submitEnquiry() {
  var form = $("#contactForm");
  executeRecaptcha();

  if (form.valid()) {
    $("#submt_btn").addClass("disabled");
    $("#submit_txt").text("Submitting...");

    $.ajax({
      type: "POST",
      url: "form-handler.php",
      data: {
        formdata: form.serialize(),
        _token: $('meta[name="csrf-token"]').attr("content"),
      },
      dataType: "json",
      success: function (data) {
        // form[0].reset();
        // Swal.fire('Success!', data.message, 'success');
        Swal.fire("Success!", data.message, "success").then(() => {
          window.location.reload();
        });
      },
      error: function (xhr, status, error) {
        console.error("Ajax error:", error);
        Swal.fire("Error!", "Something went wrong. Please try again.", "error");
      },
    });
  }
}

// function submitEnquiry() {
//     var form = $("#contactForm");

//     if (form.valid()) {
//         $("#submt_btn").addClass('disabled');
//         $("#submit_txt").text('Submitting...');

//         // Get reCAPTCHA token first
//         grecaptcha.execute(recaptchaSiteKey, {
//             action: 'submit'
//         }).then(function(token) {
//             // Add token to form data
//             var formData = form.serialize();
//             formData += '&g-recaptcha-response=' + token;

//             $.ajax({
//                 type: "POST",
//                 url: 'form-handler.php',
//                 data: {
//                     'formdata': formData,
//                     '_token': $('meta[name="csrf-token"]').attr('content')
//                 },
//                 dataType: 'json',
//                 success: function(response) {
//                     if (response.success) {
//                         form[0].reset();
//                         Swal.fire('Success!', response.message, 'success');
//                     } else {
//                         Swal.fire('Error!', response.errors.join('\n'), 'error');
//                     }
//                     $("#submt_btn").removeClass('disabled');
//                     $("#submit_txt").text('Send Message');
//                 },
//                 error: function(xhr, status, error) {
//                     console.error('Ajax error:', error);
//                     Swal.fire('Error!', 'Something went wrong. Please try again.', 'error');
//                     $("#submt_btn").removeClass('disabled');
//                     $("#submit_txt").text('Send Message');
//                 }
//             });
//         });
//     }
// }
