import { InobyFunctions } from "@assets/js/lib/inoby-functions";
import $ from "jquery";

$(() => {
  $('form[id^="contact_form"]').on("submit", (e) => {
    e.preventDefault();
    const form = e.target;
    const data = Object.fromEntries(new FormData(form).entries());

    // reset errors and message box
    $(form).find(".form-group").children("input, textarea").removeClass("error").siblings("span.error").remove();
    $(form).find(".message-box").removeClass("success error").text("");

    InobyFunctions.wpSendData("inoby_contact_form", data)
      .done((data, status) => {
        $(form).find(".message-box").addClass("success").text(data.message).fadeIn();
      })
      .fail((xhr, status, err) => {
        // get response data
        const response = xhr.responseJSON;

        // print message from server
        $(form).find(".message-box").addClass("error").text(response.message).fadeIn();

        // user error -> show errors
        if (xhr.status === 400) {
          // get errors from response
          const errors = response.errors;
          if (!errors) return;

          // print errors to form
          errors.forEach((err) => {
            const errElement = $("<span></span>").addClass("error").text(err.message);
            $(form).find(`[name=${err.field}]`).addClass("error").before(errElement);
          });
        }
      })
      .always(() => {
        setTimeout(() => {
          $(form).find(".message-box").fadeOut();
        }, 5000);
      });
  });
});
