const createTable = () => {
  const table = document.getElementById("applicationsTable");
  const tbody = table.querySelector("tbody");

  // Очищаем таблицу
  tbody.innerHTML = "";

  applications.forEach((application) => {
    const row = document.createElement("tr");
    row.setAttribute("onclick", `openApplication(${application.id});`);

    // Добавляем ячейки с данными
    const id = document.createElement("td");
    id.textContent = application.id;
    row.appendChild(id);
    const status = document.createElement("td");
    status.textContent = application.status;
    row.appendChild(status);
    const type = document.createElement("td");
    type.textContent = application.type;
    row.appendChild(type);
    const worker = document.createElement("td");
    worker.innerHTML = application.worker;
    row.appendChild(worker);
    const legal = document.createElement("td");
    legal.innerHTML = application.legal;
    row.appendChild(legal);
    const date = document.createElement("td");
    const rawDate = new Date(application.date);
    const formattedDate = `${rawDate.getDate().toString().padStart(2, "0")}/${(
      rawDate.getMonth() + 1
    )
      .toString()
      .padStart(2, "0")}/${rawDate.getFullYear()}`;
    date.textContent = formattedDate;
    row.appendChild(date);

    const finaldate = document.createElement("td");
    if (application.finaldate) {
      const rawFinalDate = new Date(application.finaldate);
      const formattedfinalDate = `${rawFinalDate
        .getDate()
        .toString()
        .padStart(2, "0")}/${(rawFinalDate.getMonth() + 1)
        .toString()
        .padStart(2, "0")}/${rawFinalDate.getFullYear()}`;
      finaldate.textContent = formattedfinalDate;
    } else {
      finaldate.textContent = "";
    }
    row.appendChild(finaldate);
    const car = document.createElement("td");
    if (application.car) {
      let carText = application.car.replace(/&quot;/g, '"');
      carText = JSON.parse(carText).join(", ");
      car.textContent = carText;
    }
    row.appendChild(car);

    tbody.appendChild(row);
  });
};

document.addEventListener("DOMContentLoaded", function () {
  createTable();
});

function getCookie(name) {
  var cookies = document.cookie.split(";");
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i].trim();
    if (cookie.startsWith(name + "=")) {
      return cookie.substring(name.length + 1);
    }
  }
  return null;
}

function requestUpdate() {
  document.getElementById("applicationsTable").style.filter =
    "brightness(0.85)";

  const formData = new FormData();
  formData.append(
    "page",
    parseInt(document.getElementById("page-number").textContent)
  );

  const requestOptions = {
    method: "POST",
    headers: {
      Authorization: getCookie("token"),
    },
    body: formData,
  };

  fetch(API_SERVER + "/forms/getmyapplications", requestOptions)
    .then((response) => {
      document.getElementById("applicationsTable").style.filter =
        "brightness(1)";
      if (response.ok) {
        return response.json();
      } else {
        console.error("Ошибка при отправке POST запроса.");
        return "Ошибка при отправке запроса.";
      }
    })
    .then((data) => {
      applications.splice(0, applications.length);

      applications.push(
        ...data.applications.map((item) => ({
          id: item.id,
          status: item.Статус,
          type: item.Вид_заявки,
          worker: item.Работник,
          date: item.Дата_заявки,
          finaldate: item.Дата_решения,
          legal: item.Организация,
          car: item.Авто_гос_номер,
        }))
      );

      createTable();

      totalMax = Math.ceil(data.totalCount / 15);

      if (totalMax === 0) {
        totalMax = 1;
      }

      var currentPage = parseInt(pageNumberInput.textContent, 10);
      if (currentPage > totalMax) {
        pageNumberInput.textContent = totalMax;
        requestUpdate();
      }
    })
    .catch((error) => {
      console.error("Ошибка при отправке запроса:", error);
    });
}
