// Store the install prompt event
let deferredPrompt;
console.log("app is running");

// Function to send install data to the database
function sendInstallData() {
  // Check if the user has successfully installed the app
  if (
    window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone === true
  ) {
    // Send install data to the database
    fetch("page/sendInstallData.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify({
        choiceResult: "accepted", 
        deviceType: getDeviceType(),
      }),
    })
      .then((response) => {
        if (response.ok) {
          console.log("Install data sent to the database");
        } else {
          console.log("Failed to send install data to the database");
        }
      })
      .catch((error) => {
        console.log("Error sending install data:", error);
      });
  }
}

// Function to get the device type
function getDeviceType() {
  const userAgent = navigator.userAgent.toLowerCase();
  if (/android/.test(userAgent)) return "Android";
  if (/iphone|ipad|ipod/.test(userAgent)) return "iOS";
  if (/windows/.test(userAgent)) return "Windows";
  if (/mac/.test(userAgent)) return "Mac";
  return "Unknown";
}

// Function to handle install button click
function handleInstallButtonClick() {
  deferredPrompt.prompt();
  deferredPrompt.userChoice.then((choiceResult) => {
    const outcome = choiceResult.outcome;
    console.log(
      outcome === "accepted"
        ? "You have installed Restou App"
        : "User declined to install Restou App"
    );

    // Check if the user accepted the installation
    if (outcome === "accepted") {
      // Send install data to the database
      sendInstallData();
    }

    // Clear the deferredPrompt variable
    deferredPrompt = null;
  });
}

// Listen for the beforeinstallprompt event
window.addEventListener("beforeinstallprompt", (event) => {
  // Prevent the default install prompt
  event.preventDefault();

  // Store the event for later use
  deferredPrompt = event;

  // Show/hide the install button based on PWA installation status
  const installButton = document.getElementById("install-button");
  installButton.style.display =
    window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone === true
      ? "none"
      : "block";

  // Add click event listener to the install button
  installButton.addEventListener("click", handleInstallButtonClick);
});

// Listen for the appinstalled event
window.addEventListener("appinstalled", () => {
  console.log("App has been successfully installed");
});
