
var SendContact = {
  init: function (form) {
    this.form     = $(form);
    this.url      = this.form.attr('action');
    this.loading  = this.form.find('#loading');
    this.bindEvents();
  },

  bindEvents: function () {
    this.form.on("submit", (e) => this.handleSubmit(e));
  },

  handleSubmit: function(event, form) {
    event.preventDefault();
    const formData = new FormData(this.form[0]);
    this.loading.fadeIn('fast');

    $.ajax({
      url: this.url,
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      dataType: "json",
      success: (response) => this.handleSuccess(response, form),
      error: (error) => this.handleError(form)
    });
  },
  
  handleSuccess: function(response, form) {
    this.loading.fadeOut('fast');
    if (response && response.success) {
      this.notify("success", "Thành công", response.message);
      this.clearForm(form);
      this.form.find(".error").removeClass("error");
    } else {
      if (response.field) {
        this.form.find(`[name="${response.field}"]`).addClass("error").focus();
      }
      this.notify("warning", "Thông báo", response.message);
    }
  },

  handleError: function(form) {
    this.loading.fadeOut('fast');
    this.notify("error", "Thất bại", "Có lỗi xảy ra, vui lòng thử lại.");
  },

  clearForm: function (form) {
    this.form[0].reset();
  },

  notify: function(status, title, text) {
    notifyOptions.status = status;
    notifyOptions.title = title;
    notifyOptions.text = text;
    new Notify(notifyOptions);
  }
};