<?php include_once "../config/siteconfig.php";?>
<script>
  var appUrl = "quiz";
  var url = 'ibix://' + appUrl;w

  var webUrl = '<?php echo WEBURL; ?>';

  var appStoreURL = '<?php echo PLAYSTOREURL; ?>';
  var playStoreURL = '<?php echo PLAYSTOREURL; ?>';

  function getMobileOperatingSystem() {
      var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      if (/android/i.test(userAgent)) {
          return "Android";
      } else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
          return "iOS";
      } else {
          return "unknown";
      }
  }

  function openInAppOrWeb() {
      // Ask the user whether they want to open in the app or web version
      var userChoice = confirm("Do you want to open this in the app? Click OK for the app, or Cancel to visit the web version.");

      if (userChoice) {
          // Try to open the app
          var os = getMobileOperatingSystem();
          var timeout = setTimeout(function () {
              // If the app is not installed, redirect to the appropriate store
              if (os === "Android") {
                  window.location.href = playStoreURL;
              } else {
                  alert("Your device is not supported.");
              }
          }, 2000); // Wait 2 seconds for the deep link to resolve

          // Attempt to open the app
          window.location = url;

          // Clear the timeout if the user returns to the page, indicating the app opened successfully
          window.addEventListener('focus', function () {
              clearTimeout(timeout);
          });
      } else {
          // Redirect to the web version
          window.location.href = webUrl;
      }
  }

  // Trigger the function
  openInAppOrWeb();
</script>
