const form = document.getElementById("charge_form");
const sendchargeBtn = document.getElementById("sendchargeBtn");

const handleResponse = function (response) {
  removeErrors();
  switch (response.code) {
    case "CHARGE_ADD_SUCCESSFULLY":
      Alert("Succès", response.msg, "success");
      Notify(response.msg, "success");
      sendchargeBtn.disabled = false;

    case "CHARGE_INVALID_FORM":
      handleErrors(response.errors);
      sendchargeBtn.disabled = false;
      break;
  }
};
const handleErrors = function (errors) {
  if (errors.length === 0) return;

  for (const key in errors) {
    let element = document.querySelector(`#charges_${key}`);
    element.classList.add("is-invalid");

    let div = document.createElement("div");
    div.classList.add("invalid-feedback", "d-block");
    div.innerText = errors[key];

    element.after(div);
  }
};
const removeErrors = function () {
  const invalidFeedBackElements =
    document.querySelectorAll(".invalid-feedback");
  const isInvalidElements = document.querySelectorAll(".is-invalid");

  invalidFeedBackElements.forEach((element) => element.remove());
  isInvalidElements.forEach((element) =>
    element.classList.remove("is-invalid")
  );
};
const submitForm = (e) => {
  e.preventDefault();
  sendchargeBtn.disabled = true;
  fetch(e.target.action, {
    body: new FormData(e.target),
    method: "POST",
  })
    .then((response) => response.json())
    .then((json) => {
      handleResponse(json);
    })
    .catch((error) => Notify("Une erreur est survenue", "danger"))
    .finally(() => {});
};

form.addEventListener("submit", submitForm);

const swalInit = swal.mixin({
  buttonsStyling: false,
  customClass: {
    confirmButton: "btn btn-primary",
    cancelButton: "btn btn-light",
    denyButton: "btn btn-light",
    input: "form-control",
  },
  willClose: function () {
    window.location.href = document.location.href;
  },
});
const Alert = (title, msg, type) => {
  swalInit.fire({
    title: title,
    text: msg,
    icon: type,
    showCloseButton: true,
  });
};
const Notify = (msg, type) => {
  new Noty({
    text: msg,
    type: type,
  }).show();
};
