//Autore: Ruslana Kapicka; JS datne, kurā notiek viss funkcionāls;
//Veidots:2024. gadā, Jaunākā versija

document.addEventListener("DOMContentLoaded", function () {
  console.log("DOM fully loaded and parsed");
  initialize();
});

  // Helper function to make POST requests
  async function postData(url = "", data = {}) {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams(data),
    });
    return response.text();
  }

  // Password change handler
  function setupChangePasswordHandler() {
    const form = document.getElementById("changePasswordForm");
    if (form) {
      form.addEventListener("submit", async function (event) {
        event.preventDefault();
        const currentPassword = document
          .getElementById("currentPasswordInput")
          .value.trim();
        const newPassword = document.getElementById("newPassword").value.trim();

        if (!currentPassword || !newPassword) {
          alert("Please fill in all fields");
          return;
        }

        const data = await postData("php/change_password.php", {
          currentPassword,
          newPassword,
        });
        alert(data);
      });
    }
  }

  // User registration handler
  function setupRegistrationHandler() {
    const button = document.getElementById("registerButton");
    if (button) {
      button.addEventListener("click", async function () {
        const regUsername = document.getElementById("regUsername").value.trim();
        const regEmail = document.getElementById("regEmail").value.trim();
        const regPassword = document.getElementById("regPassword").value.trim();

        if (!regUsername || !regEmail || !regPassword) {
          alert("Please fill in all fields");
          return;
        }

        const data = await postData("php/register.php", {
          regUsername,
          regEmail,
          regPassword,
        });
        console.log(data);
        if (data.toLowerCase().replaceAll("\n","") == "registation successful") {
          window.location.href = "login.html";
        }
      });
    }
  }

  // User login handler
  function setupLoginHandler() {
    const button = document.getElementById("loginButton");
    if (button) {
      button.addEventListener("click", async function () {
        const login = document.getElementById("login").value.trim();
        const password = document.getElementById("password").value.trim();

        if (!login || !password) {
          alert("Please fill in all fields");
          return;
        }

        const data = await postData("php/login.php", { login, password });
	if(data == 1){
  		alert("Login successful");
                window.location.href = "index.html";
        }else if(data == 0){
		alert("Incorrect password");
	}

      });
    }
  }

  // Fetch and display user data
  function fetchUserData() {
    fetch("php/get_user_info.php")
      .then((response) => response.json())
      .then((data) => {
        document.getElementById("currentUsername").textContent = data.username;
        document.getElementById("currentPassword").textContent = "*".repeat(
          data.password_hash.length
        );
      })
      .catch((error) => console.error("Error fetching user data:", error));
  }

  // Sort table by column
  function sortTableByColumn(columnName) {
    const table = document.querySelector("table");
    const tbody = table.querySelector("tbody");
    const rows = Array.from(tbody.querySelectorAll("tr"));

    const columnIndex = {
      name: 0,
      price: 1,
      "price change-24h": 2,
    }[columnName];

    rows.sort((a, b) => {
      const aValue =
        columnName === "name"
          ? a.cells[columnIndex].textContent.toLowerCase()
          : parseFloat(a.cells[columnIndex].textContent);
      const bValue =
        columnName === "name"
          ? b.cells[columnIndex].textContent.toLowerCase()
          : parseFloat(b.cells[columnIndex].textContent);

      if (columnName === "name") {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      }
      return columnName === "price"
        ? bValue - aValue
        : (aValue >= 0 && bValue >= 0) || (aValue < 0 && bValue < 0)
        ? bValue - aValue
        : aValue >= 0
        ? -1
        : 1;
    });

    rows.forEach((row) => tbody.appendChild(row));
  }

  // Fetch and display last database update time
  function fetchLastUpdateTime() {
    fetch("php/get_last_update.php")
      .then((response) => response.text())
      .then((data) => {
        const lastUpdateElement = document.getElementById("lastUpdate");
        if (lastUpdateElement) {
          lastUpdateElement.textContent = data;
        } else {
          console.error('Element with ID "lastUpdate" not found');
        }
      })
      .catch((error) =>
        console.error("Error fetching last update data:", error)
      );
  }

  // Fade out animation
  function setupFadeOutLinks() {
    const mainContainer = document.querySelector(".main-container");
    function fadeOut(link) {
      mainContainer.classList.add("page-fade-out");
      setTimeout(() => (window.location.href = link), 300);
    }

    document.querySelectorAll(".navbar ul li a").forEach((link) => {
      link.addEventListener("click", function (event) {
        event.preventDefault();
        fadeOut(this.getAttribute("href"));
      });
    });

    document.querySelector(".logo img").addEventListener("click", function () {
      fadeOut("CryptoWebLapa.html");
    });
  }

  // Initialize all functionalities
  function initialize() {
    setupChangePasswordHandler();
    setupRegistrationHandler();
    setupLoginHandler();
    //fetchUserData();
    //fetchCryptoData();
    //setupCryptoSearchHandler();
    //fetchLastUpdateTime();
    //setupFadeOutLinks();
  }


