const updateCalendar = () => {
  const table = document.getElementById("table-calendar");
  const thead = document.createElement("thead");
  const tr = document.createElement("tr");
  const date_text = document.getElementById("date-text");

  const date = document.getElementById("month").value;
  const year = date.split("-")[0];
  const month = date.split("-")[1];

  const monthName = upperCaseFirstLetter(
    new Date(year, month - 1).toLocaleString("default", { month: "long" })
  );

  const daysInMonth = new Date(year, month, 0).getDate();

  table.innerHTML = "";

  const fun = document.createElement("th");
  fun.innerHTML = "Funcionario";
  tr.appendChild(fun);

  for (let i = 0; i < daysInMonth; i++) {
    const th = document.createElement("th");
    th.innerHTML = i + 1;
    th.id = `${year}-${month}-${i + 1}`;
    tr.appendChild(th);
  }

  date_text.innerHTML = `${monthName} - ${year}`;

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

  const tbody = document.createElement("tbody");

  fetch("../../controller/biometrico.php?op=report_fetch&date=" + date)
    .then((response) => response.json())
    .catch((error) => {
      console.log(error);
    })
    .then((data) => {
      for (const [key, value] of Object.entries(data)) {
        const tr = document.createElement("tr");
        const td = document.createElement("td");
        td.innerHTML = "";
        td.rowSpan = 5;
        td.id = cleanSpaces(key) + "-td";

        tr.id = cleanSpaces(key) + "-tr";
        tr.appendChild(td);

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

        for (let i = 0; i < 4; i++) {
          const tr = document.createElement("tr");
          tr.id = cleanSpaces(key) + "-" + i;

          for (let j = 0; j < daysInMonth; j++) {
            const td = document.createElement("td");
            td.innerHTML = "";
            td.id = cleanSpaces(key) + "-td-" + (j + 1) + "-" + (i + 1);
            tr.appendChild(td);
          }
          tbody.appendChild(tr);
        }

        for (const [key1, value1] of Object.entries(value)) {
          const day = value1.fecha.split("-")[2];

          switch (value1.tipo) {
            case "ENTRADA_INICIAL":
              const row = getRowIndex(cleanSpaces(key) + "-0");
              const cell = getCellIndex(cleanSpaces(key) + "-td-" + day + "-1");

              table.rows[row].cells[cell].appendChild(states(value1.estado));
              break;

            case "SALIDA_ALMUERZO":
              const row1 = getRowIndex(cleanSpaces(key) + "-1");
              const cell1 = getCellIndex(
                cleanSpaces(key) + "-td-" + day + "-2"
              );

              table.rows[row1].cells[cell1].appendChild(states(value1.estado));
              break;

            case "ENTRADA_ALMUERZO":
              const row2 = getRowIndex(cleanSpaces(key) + "-2");
              const cell2 = getCellIndex(
                cleanSpaces(key) + "-td-" + day + "-3"
              );

              table.rows[row2].cells[cell2].appendChild(states(value1.estado));
              break;

            case "SALIDA_FINAL":
              const row3 = getRowIndex(cleanSpaces(key) + "-3");
              const cell3 = getCellIndex(
                cleanSpaces(key) + "-td-" + day + "-4"
              );

              table.rows[row3].cells[cell3].appendChild(states(value1.estado));
              break;
          }

          const button = document.createElement("button");
          button.className = "btn btn-primary btn-sm mt-2";
          button.innerHTML = "Detalles";
          button.setAttribute("data-toggle", "modal");
          button.setAttribute("data-target", "#modal-details");
          button.id = value1.usuario + "-" + cleanSpaces(value1.nombre);

          button.onclick = function () {
            showDetails(value1.usuario);
          };

          const row = getRowIndex(cleanSpaces(key) + "-tr");
          const cell = getCellIndex(cleanSpaces(key) + "-td");

          const div = document.createElement("div");
          const text = document.createTextNode(key);

          div.appendChild(text);
          div.appendChild(button);

          table.rows[row].cells[cell].innerHTML == ""
            ? table.rows[row].cells[cell].appendChild(div)
            : "";
        }
      }
    });
};

const states = (state) => {
  const na_icon = document.createElement("i");
  na_icon.innerHTML = "N/A";

  const regular_icon = document.createElement("i");
  regular_icon.className = "fas fa-check";

  const tardanza_icon = document.createElement("i");
  tardanza_icon.className = "fas fa-times";

  const salida_anticipada_icon = document.createElement("i");
  salida_anticipada_icon.className = "fas fa-grip-lines";

  const regular = document.createElement("span");
  regular.className = "badge badge-success";
  regular.appendChild(regular_icon);

  const tardanza = document.createElement("span");
  tardanza.className = "badge badge-warning";
  tardanza.appendChild(tardanza_icon);

  const salida_anticipada = document.createElement("span");
  salida_anticipada.className = "badge badge-info";
  salida_anticipada.appendChild(salida_anticipada_icon);

  switch (state) {
    case "REGULAR":
      return regular;

    case "TARDANZA":
      return tardanza;

    case "SALIDA ANTICIPADA":
      return salida_anticipada;

    case "NA":
      return na_icon;
  }
};

const getRowIndex = (id) => {
  const rowEl = document.getElementById(id);

  return rowEl.rowIndex;
};

const getCellIndex = (id) => {
  const cellEl = document.getElementById(id);

  return cellEl.cellIndex;
};

const showDetails = (id) => {
  const table = document.getElementById("table-details");
  const date_text = document.getElementById("date-details");

  const date = document.getElementById("month").value;
  const year = date.split("-")[0];
  const month = date.split("-")[1];

  table.innerHTML = "";

  const monthName = upperCaseFirstLetter(
    new Date(year, month - 1).toLocaleString("default", { month: "long" })
  );

  date_text.innerHTML = `${monthName} - ${year}`;

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

  const day = document.createElement("th");
  day.innerHTML = "Dia";
  tr.appendChild(day);

  const ti = document.createElement("th");
  ti.innerHTML = "EI";
  ti.id = `ti-${id}`;
  tr.appendChild(ti);

  const tsa = document.createElement("th");
  tsa.innerHTML = "SA";
  tsa.id = `tsa-${id}`;
  tr.appendChild(tsa);

  const tea = document.createElement("th");
  tea.innerHTML = "EA";
  tea.id = `tea-${id}`;
  tr.appendChild(tea);

  const ts = document.createElement("th");
  ts.innerHTML = "SF";
  ts.id = `ts-${id}`;
  tr.appendChild(ts);

  const observation = document.createElement("th");
  observation.innerHTML = "Observacion";
  observation.id = `obs-${id}`;
  tr.appendChild(observation);

  const total = document.createElement("th");
  total.innerHTML = "Total";
  tr.appendChild(total);

  const tbody = document.createElement("tbody");

  for (let i = 0; i < new Date(year, month, 0).getDate(); i++) {
    const tr = document.createElement("tr");
    const day = document.createElement("td");

    day.innerHTML = i + 1;
    day.id = `${date}-${i + 1}-${id}`;
    tr.appendChild(day);

    const ti = document.createElement("td");
    ti.innerHTML = "";
    ti.id = `${date}-${i + 1}-ti-${id}`;
    tr.appendChild(ti);

    const tsa = document.createElement("td");
    tsa.innerHTML = "";
    tsa.id = `${date}-${i + 1}-tsa-${id}`;
    tr.appendChild(tsa);

    const tea = document.createElement("td");
    tea.innerHTML = "";
    tea.id = `${date}-${i + 1}-tea-${id}`;
    tr.appendChild(tea);

    const ts = document.createElement("td");
    ts.innerHTML = "";
    ts.id = `${date}-${i + 1}-ts-${id}`;
    tr.appendChild(ts);

    const observation = document.createElement("td");
    observation.innerHTML = "";
    observation.id = `${date}-${i + 1}-obs-${id}`;
    tr.appendChild(observation);

    const total = document.createElement("td");
    total.innerHTML = "";
    total.id = `${date}-${i + 1}-total-${id}`;
    tr.appendChild(total);

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

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

  fetch(
    "../../controller/biometrico.php?op=report_details&date=" +
      date +
      "&user=" +
      id
  )
    .then((response) => response.json())
    .catch((error) => {
      console.log(error);
    })
    .then((data) => {
      let total_late = 0;
      let total_early = 0;
      let hours_total = "00:00:00";

      for (const [key, value] of Object.entries(data)) {
        for (const [key1, value1] of Object.entries(value)) {
          const name = clenaSpacesAndReturnArray(value1.nombre);

          const nameEl = document.getElementById("name");
          nameEl.innerHTML = name[0] + " " + name[1];

          const lastnameEl = document.getElementById("lastname");
          lastnameEl.innerHTML = name[2] + " " + name[3];

          const dateEL = document.getElementById("date");

          const date = new Date();
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();

          dateEL.innerHTML = `${day}/${month}/${year}`;

          const rowEl = document.getElementById(`${key}-${id}`);

          switch (value1.estado) {
            case "TARDANZA":
              total_late++;
              break;

            case "SALIDA ANTICIPADA":
              total_early++;
              break;
          }

          console.log(value1);

          if (rowEl) {
            const row = rowEl.parentNode.rowIndex;

            switch (value1.tipo) {
              case "ENTRADA_INICIAL":
                const cellEl = document.getElementById(`ti-${id}`);
                const cell = cellEl.cellIndex;

                table.rows[row].cells[cell].innerHTML =
                  value1.hora + " - " + normalizeText(value1.tipo);
                break;

              case "SALIDA_ALMUERZO":
                const cellEl1 = document.getElementById(`tsa-${id}`);
                const cell1 = cellEl1.cellIndex;

                table.rows[row].cells[cell1].innerHTML =
                  value1.hora + " - " + normalizeText(value1.tipo);
                break;

              case "ENTRADA_ALMUERZO":
                const cellEl2 = document.getElementById(`tea-${id}`);
                const cell2 = cellEl2.cellIndex;

                table.rows[row].cells[cell2].innerHTML =
                  value1.hora + " - " + normalizeText(value1.tipo);
                break;
              case "SALIDA_FINAL":
                const cellEl3 = document.getElementById(`ts-${id}`);
                const cell3 = cellEl3.cellIndex;

                table.rows[row].cells[cell3].innerHTML =
                  value1.hora + " - " + normalizeText(value1.tipo);
                break;
            }

            const observationCell = document.getElementById(`obs-${id}`);
            const observationCellIndex = observationCell.cellIndex;

            table.rows[row].cells[observationCellIndex].innerHTML =
              value1.observacion ? value1.observacion : "Sin Observacion";

            const cellEl4 = document.getElementById(`${key}-total-${id}`);
            const cell4 = cellEl4.cellIndex;

            const ti = table.rows[row].cells[1].innerHTML;
            const tsa = table.rows[row].cells[2].innerHTML;
            const tea = table.rows[row].cells[3].innerHTML;
            const ts = table.rows[row].cells[4].innerHTML;

            if (ti && tsa && tea && ts) {
              const total = calcularHoras(ti, tsa, tea, ts);
              hours_total = sumarHoras(hours_total, total);

              table.rows[row].cells[cell4].innerHTML = total;
            }
          }
        }
      }

      const total_late_el = document.getElementById("total-late");
      total_late_el.innerHTML = total_late;

      const total_early_el = document.getElementById("total-early");
      total_early_el.innerHTML = total_early;

      const total_hours = document.getElementById("total-hours");
      total_hours.innerHTML = hours_total;
    });
};

const calcularHoras = (ti, tsa, tea, ts) => {
  const total = sumarHoras(
    restarHoras(restarHoras(ts, ti), restarHoras(tea, tsa)),
    "00:00"
  );

  return total;
};

const diferenciaHoras = (h1, h2) => {
  const [h1h, h1m] = h1.split(":");
  const [h2h, h2m] = h2.split(":");
  const h = parseInt(h1h) - parseInt(h2h);
  const m = parseInt(h1m) - parseInt(h2m);
  return `${h}:${m}`;
};

const sumarHoras = (h1, h2) => {
  const [h1h, h1m] = h1.split(":");
  const [h2h, h2m] = h2.split(":");
  const h = parseInt(h1h) + parseInt(h2h);
  const m = parseInt(h1m) + parseInt(h2m);
  return `${h}:${m}`;
};

const restarHoras = (h1, h2) => {
  const [h1h, h1m] = h1.split(":");
  const [h2h, h2m] = h2.split(":");
  const h = parseInt(h1h) - parseInt(h2h);
  const m = parseInt(h1m) - parseInt(h2m);
  return `${h}:${m}`;
};

const upperCaseFirstLetter = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

const uppercaseFirtsLetterOfEachWord = (string) => {
  return string
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
};

const cleanSpaces = (string) => {
  return string.replace(/\s/g, "-");
};

const clenaSpacesAndReturnArray = (string) => {
  return string.split(" ");
};

const normalizeText = (text) => {
  const converted = text.replace(/_/g, " ").toLowerCase();

  return uppercaseFirtsLetterOfEachWord(converted);
};

$("#month").on("change", function (e) {
  updateCalendar();
});

$("#download-pdf").on("click", function () {
  const doc = new jspdf.jsPDF();

  const date = document.getElementById("month").value;
  const month = date.split("-")[1];
  const year = date.split("-")[0];

  const monthName = upperCaseFirstLetter(
    new Date(year, month - 1).toLocaleString("default", { month: "long" })
  );

  doc.setFontSize(20);
  doc.text("Reporte de Asistencia", 14, 15);
  doc.text(`${monthName} - ${year}`, 14, 25);

  doc.autoTable({
    html: "#table-user",
    theme: "grid",
    margin: { top: 30 },
  });

  doc.autoTable({
    html: "#instructions",
    theme: "grid",
  });

  doc.autoTable({
    html: "#table-details",
    theme: "grid",
  });

  doc.autoTable({
    html: "#table-hours",
    theme: "grid",
  });
  doc.save(`reporte_${monthName}_${year}.pdf`);
});
