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

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

  passes.forEach((pass) => {
    const row = document.createElement("tr");
    row.setAttribute("onclick", `openPass(${pass.id});`);

    // Добавляем ячейки с данными
    const id = document.createElement("td");
    id.textContent = pass.id;
    row.appendChild(id);
    const status = document.createElement("td");
    status.textContent = pass.status;
    row.appendChild(status);
    const date = document.createElement("td");
    const rawDate = new Date(pass.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 type = document.createElement("td");
    type.textContent = pass.type;
    row.appendChild(type);
    const worker = document.createElement("td");
    worker.textContent = pass.name;
    row.appendChild(worker);
    const legal = document.createElement("td");
    legal.innerHTML = pass.legal;
    row.appendChild(legal);
    const finaldate = document.createElement("td");
    if (pass.finaldate) {
      const rawFinalDate = new Date(pass.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 address = document.createElement("td");
    address.textContent = pass.address;
    row.appendChild(address);
    const car = document.createElement("td");
    if (pass.car) {
      let carText = pass.car.replace(/"/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("passesTable").style.filter = "brightness(0.85)";

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

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

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

      passes.push(
        ...data.passes.map((item) => ({
          id: item.id,
          status: item.Состояние,
          date: item.Дата_выдачи,
          finaldate: item.Действие_до,
          type: item.Вид_пропуска,
          name: item.Работник,
          legal: item.Организация,
          address: item.Зона_доступа,
          car: item.Авто_гос_номер,
          tmcname: 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);
    });
}