$(() => {
  $("#data-jornada").DataTable({
    ajax: {
      url: "../../controller/jornada.php?op=get",
      type: "GET",
    },
    serverSide: true,
    procesing: true,
    responsive: true,
    columns: [{ data: "nombre" }, { data: "descripcion" }, { data: "actions" }],
  });
});

const nuevo = () => {
  $("#register_form")[0].reset();
  $("#jornadadbk").val("");
  $("#modalJornada").modal("show");
};

const editar = (id) => {
  $.ajax({
    url: "../../controller/jornada.php?op=getById",
    type: "POST",
    data: { id: id },
    dataType: "json",
    success: function (data) {
      if (data.status == "success") {
        $("#jornadadbkedit").val(data.data.jornadadbk);
        $("#name_update").val(data.data.nombre);
        $("#description_update").val(data.data.descripcion);

        editJornada(data.data.jornadadbk);

        $("#editJornada").modal("show");
      } else {
        Swal.fire({
          title: "Error",
          text: data.message,
          icon: "error",
          confirmButtonText: "Aceptar",
        });
      }
    },
    error: function (data) {
      Swal.fire({
        title: "Error",
        text: data.message,
        icon: "error",
        confirmButtonText: "Aceptar",
      });
    },
  });
};

const editJornada = (id) => {
  const table = document.getElementById("jornada_table_update");

  fetch("../../controller/jornada.php?op=getJornadas&id=" + id, {
    method: "GET",
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data.data);

      table.innerHTML = "";

      $("#jornadadbkupdate").val(id);

      data.data.forEach((element) => {
        const row = table.insertRow();

        const cellDia = row.insertCell(0);
        const cellHoraInicio = row.insertCell(1);
        const cellHoraFin = row.insertCell(2);
        const cellActions = row.insertCell(3);

        const inputId = document.createElement("input");
        inputId.setAttribute("type", "hidden");
        inputId.setAttribute("name", "id_jornada[]");
        inputId.setAttribute("value", element.jdetalledbk);

        row.appendChild(inputId);

        const selectDia = document.createElement("select");
        selectDia.setAttribute("class", "form-control");
        selectDia.setAttribute("name", "dia[]");

        const optionLunes = document.createElement("option");
        optionLunes.value = "Lunes";
        optionLunes.innerHTML = "Lunes";

        const optionMartes = document.createElement("option");
        optionMartes.value = "Martes";
        optionMartes.innerHTML = "Martes";

        const optionMiercoles = document.createElement("option");
        optionMiercoles.value = "Miercoles";
        optionMiercoles.innerHTML = "Miercoles";

        const optionJueves = document.createElement("option");
        optionJueves.value = "Jueves";
        optionJueves.innerHTML = "Jueves";

        const optionViernes = document.createElement("option");
        optionViernes.value = "Viernes";
        optionViernes.innerHTML = "Viernes";

        const optionSabado = document.createElement("option");
        optionSabado.value = "Sabado";
        optionSabado.innerHTML = "Sabado";

        const optionDomingo = document.createElement("option");
        optionDomingo.value = "Domingo";
        optionDomingo.innerHTML = "Domingo";

        selectDia.appendChild(optionLunes);
        selectDia.appendChild(optionMartes);
        selectDia.appendChild(optionMiercoles);
        selectDia.appendChild(optionJueves);
        selectDia.appendChild(optionViernes);
        selectDia.appendChild(optionSabado);
        selectDia.appendChild(optionDomingo);

        switch (element.dia) {
          case "Lunes":
            optionLunes.setAttribute("selected", "selected");
            break;
          case "Martes":
            optionMartes.setAttribute("selected", "selected");
            break;
          case "Miercoles":
            optionMiercoles.setAttribute("selected", "selected");
            break;
          case "Jueves":
            optionJueves.setAttribute("selected", "selected");
            break;
          case "Viernes":
            optionViernes.setAttribute("selected", "selected");
            break;
          case "Sabado":
            optionSabado.setAttribute("selected", "selected");
            break;
          case "Domingo":
            optionDomingo.setAttribute("selected", "selected");
            break;
        }

        cellDia.appendChild(selectDia);

        const inputHoraInicio = document.createElement("input");
        inputHoraInicio.setAttribute("type", "time");
        inputHoraInicio.setAttribute("class", "form-control");
        inputHoraInicio.setAttribute("name", "hora_inicial[]");
        inputHoraInicio.setAttribute("value", element.hora_inicio);

        cellHoraInicio.appendChild(inputHoraInicio);

        const inputHoraFin = document.createElement("input");
        inputHoraFin.setAttribute("type", "time");
        inputHoraFin.setAttribute("class", "form-control");
        inputHoraFin.setAttribute("name", "hora_final[]");
        inputHoraFin.setAttribute("value", element.hora_fin);

        cellHoraFin.appendChild(inputHoraFin);

        const buttonDelete = document.createElement("button");
        buttonDelete.setAttribute("class", "btn btn-danger btn-xs");
        buttonDelete.setAttribute("type", "button");

        const i = document.createElement("i");
        i.setAttribute("class", "fas fa-trash-alt");

        buttonDelete.appendChild(i);
        buttonDelete.onclick = function () {
          Swal.fire({
            title: "¿Está seguro?",
            text: "¡No podrá revertir esto!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Si, ¡eliminar!",
          }).then((result) => {
            if (result.isConfirmed) {
              fetch(
                "../../controller/jornada.php?op=deleteJornada&id=" +
                  element.jdetalledbk,
                {
                  method: "GET",
                }
              )
                .then((response) => response.json())
                .then((data) => {
                  if (data.status == "success") {
                    Swal.fire({
                      title: "Eliminado",
                      text: data.message,
                      icon: "success",
                      confirmButtonText: "Aceptar",
                    });
                  } else {
                    Swal.fire({
                      title: "Error",
                      text: data.message,
                      icon: "error",
                      confirmButtonText: "Aceptar",
                    });
                  }
                })
                .catch((error) => {
                  console.log(error);
                });

              row.remove();
            }
          });
        };

        cellActions.appendChild(buttonDelete);
      });
    });
};

const eliminar = (id) => {
  Swal.fire({
    title: "¿Está seguro?",
    text: "¡No podrás revertir esto!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "Si, eliminarlo!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../controller/jornada.php?op=delete",
        type: "POST",
        data: { id: id },
        dataType: "json",
        success: function (data) {
          if (data.status == "success") {
            $("#data-jornada").DataTable().ajax.reload();

            Swal.fire({
              title: "Eliminado",
              text: data.message,
              icon: "success",
              confirmButtonText: "Aceptar",
            });
          } else {
            Swal.fire({
              title: "Error",
              text: data.message,
              icon: "error",
              confirmButtonText: "Aceptar",
            });
          }
        },
        error: function (data) {
          Swal.fire({
            title: "Error",
            text: data.message,
            icon: "error",
            confirmButtonText: "Aceptar",
          });
        },
      });
    }
  });
};

$("#save_register").click(function () {
  $("#register_form").submit();
});

$("#register_form").submit(function (e) {
  e.preventDefault();
  let form = $(this);
  let url = "../../controller/jornada.php?op=create";
  let data = form.serialize();

  $.ajax({
    url: url,
    type: "POST",
    data: data,
    dataType: "json",
    success: function (data) {
      if (data.status == "success") {
        Swal.fire({
          title: "Registro exitoso",
          text: data.message + " - Configure su jornada",
          icon: "success",
          confirmButtonText: "Aceptar",
        });

        configureJornada(data.id);
      } else {
        Swal.fire({
          title: "Error",
          text: data.message,
          icon: "error",
          confirmButtonText: "Aceptar",
        });
      }
    },
    error: function (data) {
      Swal.fire({
        title: "Error",
        text: data.message,
        icon: "error",
        confirmButtonText: "Aceptar",
      });
    },
  });
});

$("#addJornada").click(function () {
  addRow("table_update_jornada");
});

$("#update_register").click(function () {
  const form = document.getElementById("update_form");

  const data = new FormData(form);

  fetch("../../controller/jornada.php?op=updateJornada", {
    method: "POST",
    body: data,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status == "success") {
        Swal.fire({
          title: "Registro exitoso",
          text: data.message,
          icon: "success",
          confirmButtonText: "Aceptar",
        });
      } else {
        Swal.fire({
          title: "Error",
          text: data.message,
          icon: "error",
          confirmButtonText: "Aceptar",
        });

        console.log(data);
      }
    });
});

$("#update_jornada").click(function () {
  const form = document.getElementById("updateJornada");

  const data = new FormData(form);

  fetch("../../controller/jornada.php?op=updateJornadas", {
    method: "POST",
    body: data,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status == "success") {
        Swal.fire({
          title: "Registro exitoso",
          text: data.message,
          icon: "success",
          confirmButtonText: "Aceptar",
        });
      } else {
        Swal.fire({
          title: "Error",
          text: data.message,
          icon: "error",
          confirmButtonText: "Aceptar",
        });

        console.log(data);
      }
    });
});

const configureJornada = (id) => {
  const container = document.getElementById("button_container");
  container.innerHTML = "";

  const button = document.createElement("button");
  button.setAttribute("class", "btn btn-primary btn-block");
  button.type = "button";
  button.onclick = () => {
    addJornada(id);
  };

  const i = document.createElement("i");
  i.setAttribute("class", "fas fa-cog mr-2");

  const text = document.createTextNode("Configurar Jornada");

  button.appendChild(i);
  button.appendChild(text);

  container.appendChild(button);
};

const addJornada = (id) => {
  const container = document.getElementById("jornada_container");
  container.innerHTML = "";

  const container_body = document.createElement("div");
  container_body.setAttribute("class", "mt-2 border p-3");

  container.appendChild(container_body);

  const form = document.createElement("form");
  form.setAttribute("id", "jornada_form");

  const inputID = document.createElement("input");
  inputID.type = "hidden";
  inputID.name = "jornadadbk";
  inputID.value = id;

  form.appendChild(inputID);

  container_body.appendChild(form);

  const row = document.createElement("div");
  row.setAttribute("class", "row");

  const col_md_8 = document.createElement("div");
  col_md_8.setAttribute("class", "col-md-8");

  const h5 = document.createElement("h5");
  const text = document.createTextNode("Configurar Jornada");

  h5.appendChild(text);
  col_md_8.appendChild(h5);

  const col_md_4 = document.createElement("div");
  col_md_4.setAttribute("class", "col-md-4");

  const button = document.createElement("button");
  button.setAttribute("class", "btn btn-xs btn-success float-right");
  button.type = "button";
  button.onclick = () => {
    addRow("table_jornada");
  };

  const i = document.createElement("i");
  i.setAttribute("class", "fas fa-plus");

  button.appendChild(i);
  col_md_4.appendChild(button);

  row.appendChild(col_md_8);
  row.appendChild(col_md_4);

  form.appendChild(row);

  const table = document.createElement("table");
  table.setAttribute("class", "table table-bordered");
  table.id = "table_jornada";

  const thead = document.createElement("thead");
  const tr = document.createElement("tr");

  const th = document.createElement("th");
  const text_th = document.createTextNode("Dia");

  th.appendChild(text_th);
  tr.appendChild(th);

  const th2 = document.createElement("th");
  const text_th2 = document.createTextNode("Hora Inicial");

  th2.appendChild(text_th2);
  tr.appendChild(th2);

  const th3 = document.createElement("th");
  const text_th3 = document.createTextNode("Hora Final");

  th3.appendChild(text_th3);
  tr.appendChild(th3);

  const th4 = document.createElement("th");
  const text_th4 = document.createTextNode("Acciones");

  th4.appendChild(text_th4);
  tr.appendChild(th4);

  thead.appendChild(tr);
  table.appendChild(thead);

  form.appendChild(table);

  const buttonSave = document.createElement("button");
  buttonSave.setAttribute("class", "btn btn-block btn-warning");
  buttonSave.type = "button";
  buttonSave.onclick = () => {
    createJornada();
  };

  const iSave = document.createElement("i");
  iSave.setAttribute("class", "fas fa-save");

  buttonSave.appendChild(iSave);

  form.appendChild(buttonSave);
};

const addRow = (id) => {
  const table = document.getElementById(id);
  const tbody = document.createElement("tbody");

  const tr = document.createElement("tr");
  const td = document.createElement("td");

  const select = document.createElement("select");
  select.setAttribute("class", "form-control");
  select.name = "dia[]";

  const option = document.createElement("option");
  option.value = "Lunes";
  const text = document.createTextNode("Lunes");

  option.appendChild(text);
  select.appendChild(option);

  const option2 = document.createElement("option");
  option2.value = "Martes";
  const text2 = document.createTextNode("Martes");

  option2.appendChild(text2);
  select.appendChild(option2);

  const option3 = document.createElement("option");
  option3.value = "Miercoles";
  const text3 = document.createTextNode("Miercoles");

  option3.appendChild(text3);
  select.appendChild(option3);

  const option4 = document.createElement("option");
  option4.value = "Jueves";
  const text4 = document.createTextNode("Jueves");

  option4.appendChild(text4);
  select.appendChild(option4);

  const option5 = document.createElement("option");
  option5.value = "Viernes";
  const text5 = document.createTextNode("Viernes");

  option5.appendChild(text5);
  select.appendChild(option5);

  const option6 = document.createElement("option");
  option6.value = "Sabado";
  const text6 = document.createTextNode("Sabado");

  option6.appendChild(text6);
  select.appendChild(option6);

  const option7 = document.createElement("option");
  option7.value = "Domingo";
  const text7 = document.createTextNode("Domingo");

  option7.appendChild(text7);
  select.appendChild(option7);

  td.appendChild(select);
  tr.appendChild(td);

  const td2 = document.createElement("td");
  const input = document.createElement("input");
  input.setAttribute("class", "form-control");
  input.type = "time";
  input.name = "hora_inicial[]";

  td2.appendChild(input);
  tr.appendChild(td2);

  const td3 = document.createElement("td");
  const input2 = document.createElement("input");
  input2.setAttribute("class", "form-control");
  input2.type = "time";
  input2.name = "hora_final[]";

  td3.appendChild(input2);
  tr.appendChild(td3);

  const td4 = document.createElement("td");
  const button = document.createElement("button");

  button.setAttribute("class", "btn btn-xs btn-danger");
  button.type = "button";
  button.onclick = () => {
    tr.remove();
  };

  const i = document.createElement("i");
  i.setAttribute("class", "fas fa-trash");

  button.appendChild(i);

  const input3 = document.createElement("input");
  input3.type = "hidden";
  input3.name = "id_jornada[]";
  input3.value = "";

  td4.appendChild(input3);

  td4.appendChild(button);
  tr.appendChild(td4);

  tbody.appendChild(tr);
  table.appendChild(tbody);
};

const createJornada = () => {
  const form = document.getElementById("jornada_form");
  const data = new FormData(form);

  fetch("../../controller/jornada.php?op=configure", {
    method: "POST",
    body: data,
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status == "error") {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: data.message,
        });
      } else {
        Swal.fire({
          icon: "success",
          title: "Correcto",
          text: data.message,
        });
      }
    });
};
