$(document).ready(function () {
  let $inputs = $(".falso-lead-input");
  let sequencia =
    $inputs.length > 0 ? parseInt($inputs.last().attr("data-id")) : 0;

  $(document).on("click", "#adicionar-falso-lead-btn", function () {
    let novoLead = $("#base-falso-lead").clone();
    let novoLeadInput = novoLead.find("input");
    novoLead.removeClass("hidden");
    novoLeadInput.attr("data-id", -1);
    novoLeadInput.attr("data-deletar", 0);
    novoLeadInput.attr("id", "falso-lead-" + sequencia);
    sequencia++;
    $("#falsos-leads").append(novoLead);
  });

  $(document).on("click", ".deletar-falso-lead-btn", function () {
    let $falsoLead = $(this).parents(".falso-lead");
    let $input = $falsoLead.find("input");
    $input.attr("data-deletar", 1);
    $falsoLead.addClass("hidden");
  });

  function validarSomenteNumeros(str) {
    // Verifica se a string contém apenas dígitos e tem no máximo 10 caracteres
    return /^\d{1,10}$/.test(str);
  }

  $(document).on("click", "#salvar-falsos-leads", function () {
    let dados = [];

    $(".falso-lead-input").each(function (i, obj) {
      obj = $(obj);

      if (obj.val() !== "") {
        dados.push([
          obj.attr("id"),
          obj.attr("data-id"),
          obj.attr("data-deletar"),
          obj.val(),
        ]);
      }
    });

    const numeroGrande = dados.find((item) => {
      return (
        validarSomenteNumeros(item[3].replace(/\D/g, "")) &&
        item[3].replace(/\D/g, "")?.length > 9
      );
    });

    if (numeroGrande?.length > 0 && numeroGrande[2] === "0") {
      toastr.error(`Número ${numeroGrande[3]} é maior que 9 dígitos!`);
      return;
    }

    $(document).ready(function () {
      $.ajax({
        type: "POST",
        url: "action/salvar_falsos_leads",
        data: "leads=" + JSON.stringify(dados),
        success: function (data) {
          let $preloader = $(".preloader");

          if (data === "-1") {
            $preloader.css({ display: "none" });
            window.location.href = "./";
            return;
          }
          if (data.substring(0, 2) === "-2") {
            $preloader.css({ display: "none" });
            toastr.clear();
            toastr.error(data.substring(2));
            return;
          }

          if (data !== "") {
            let resultado = JSON.parse(data);
            $.each(resultado, function (index, lead) {
              $("#" + lead[0]).attr("data-id", lead[1]);
            });
          }

          $preloader.css({ display: "none" });
          toastr.clear();
          toastr.success("Dados salvos com sucesso.");
        },
        beforeSend: function () {
          $(".preloader").css({ display: "block" });
        },
        complete: function () {
          $(".preloader").css({ display: "none" });
        },
        error: function () {
          $(".preloader").css({ display: "none" });
          toastr.clear();
          toastr.error("Houve um erro ao salvar.");
        },
      });
    });
  });
});
