<!DOCTYPE html> 
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Cyber Stock</title> <!-- Dynamic title -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500&display=swap" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet">
  <link rel="stylesheet" href="/css/gg.css">
  <link rel="manifest" href="/manifest.json">
</head>
<body>

  <%- include('topnav') %>
  <%- include('sidebar') %> 

  <div id="parent-container" class="parent-container">
    <!-- Dynamic content will be loaded here -->
  </div>

  <p>Click "Install App" to add this as a PWA.</p>

  <button id="installPWA" style="display: none;">Install App</button>
  <script>
  
  
  let deferredPrompt;
      let wakeLock = null;
      let registration;


console.log("🚀 Checking if navigator is supported...");
console.log("navigator:", navigator);

if ('serviceWorker' in navigator) {
  console.log("✅ Service Worker is supported!");
} else {
  console.error("❌ Service Worker is NOT supported.");
}




      if ('serviceWorker' in navigator) {
        
          navigator.serviceWorker.register('/service-worker.js').then(reg => {
              console.log("✅ Service Worker Registered");
              registration = reg;
          }).catch(error => console.error("❌ Service Worker Registration Failed:", error));
      }

      // ✅ Handle PWA Install Prompt
      window.addEventListener("beforeinstallprompt", (event) => {
          console.log("✅ beforeinstallprompt fired!");
          event.preventDefault();
          deferredPrompt = event;
          document.getElementById("installPWA").style.display = "block";

          document.getElementById("installPWA").addEventListener("click", () => {
              deferredPrompt.prompt();
              deferredPrompt.userChoice.then(choice => {
                  console.log(choice.outcome === "accepted" ? "✅ PWA Installed" : "❌ Install dismissed");
                  deferredPrompt = null;
              });
          });
      });


    const loadedjs={}
   // Mapping of pages to their corresponding initialization functions
const pageInitFunctions = {
  '/new-transaction': 'initializeNewTransaction',
  '/transaction': 'initializeTransactionList',
  '/transfer': 'initializeTransfer',
  '/daily-sale': 'initializeDailySale',
  '/expense': 'initializeExpense',
  '/expense-group': 'initializeExpenseGroup',

  '/financial-summary': 'initializeFinancialSummary',
  '/monthly-expense': 'initializeMonthlyExpense',
  '/profit': 'initializeProfit',
  '/summary': 'initializeSummary',
  '/total-summary-all': 'initializeTotalSummaryAll',
  '/total-summary-daily': 'initializeTotalSummaryDaily',
  '/report': 'initializeReport',
  '/transaction-report': 'initializeTransactionReport',
  '/transaction-detail': 'initializeTransactionDetail',
  '/bank-account': 'initializeBankAccount',
  '/bank-transaction': 'initializeBankTransaction',
  '/branch': 'initializeBranchPage',
  '/branch-group': 'initializeBranchGroup',
  '/branch-inventory': 'initializeBranchInventory',
  '/company': 'initializeCompany',
  '/customer': 'initializeCustomer',
  '/user': 'initializeUser',
  '/register': 'initializeRegister',
  '/setting': 'initializeSetting',
  '/general': 'initializeGeneral',
  '/item': 'initializeItem',
  '/merged-data': 'initializeMergedData'
};
    // Main function to load page content dynamically
    async function loadContent(page) {
      try {
        const response = await fetch(page);
        const html = await response.text();
        const contentElement = document.getElementById('parent-container');
        contentElement.innerHTML = html;
console.log("the page being caliing is",page)
        // Find all script tags with a src attribute in the fetched content
        const scriptTags = Array.from(contentElement.querySelectorAll("script[src]"));
        
        // Load each script sequentially
        await loadScriptsSequentially(scriptTags);
        console.log('All scripts loaded and executed successfully');

        // Call the specific initialization function based on the page
        afterScriptsLoaded(page);

        // Set active class on the clicked sidebar link
        setActiveLink(page);
      } catch (error) {
        console.error('Error loading page:', error);
        document.getElementById('content').innerHTML = '<p>Error loading content.</p>';
      }
    }

    // Function that runs after all scripts are loaded
    function afterScriptsLoaded(page) {
      console.log("Scripts are fully loaded. Executing post-load functions.");

      // Get the function name for the current page from the mapping
      const initFunctionName = pageInitFunctions[page];
      console.log("the function is:",initFunctionName)
      if (initFunctionName && typeof window[initFunctionName] === 'function') {
        // Call the initialization function if it's defined
        console.log("the function is:",initFunctionName)
       window[initFunctionName]();
      } else {
        // Log a warning if the initialization function is not found
        console.warn(`Initialization function ${initFunctionName} is not defined in loaded scripts.`);
      }
    }

    // Helper function to load each script sequentially using async/await
    async function loadScriptsSequentially(scriptTags) {
      for (const scriptTag of scriptTags) {
        const scriptSrc = scriptTag.getAttribute("src");

        // Only load if the script has not been loaded previously
      //  if (!isScriptLoaded(scriptSrc)) {

            console.log(".. loading...")
          await loadScript(scriptSrc);
    
    
          // }
      }
    }

    // Helper function to dynamically load a script by its path
    function loadScript(src) {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script');
     



if(loadedjs[src]!=1)
{

      script.src = src;
        script.async = false; // Ensures sequential loading
       
       
      script.onload = () => {
      
        loadedjs[src]=1;
      
          console.log(`Loaded script: ${src}`);
          resolve();
        };


        script.onerror = () => {
          console.error(`Failed to load script: ${src}`);
          reject(new Error(`Failed to load script: ${src}`));
        };
        document.body.appendChild(script);

      }

      else
      {
        console.log("file is already loaded")

    //    removeAllScriptsFromFolder('/js/');

// Example usage
removeScript('/js/new-transaction.js');




      }
    



   

       

      });
    }




    function removeScript(scriptUrl) {
  const scripts = document.querySelectorAll(`script[src="${scriptUrl}"]`);
  scripts.forEach(script => script.parentNode.removeChild(script));
}




    function removeAllScriptsFromFolder(folderPath) {
  const scripts = document.querySelectorAll('script');
  scripts.forEach(script => {
    if (script.src.includes(folderPath)) {
      script.parentNode.removeChild(script);
    }
  });
}

// Example usage




    // Helper function to check if a script with the specified src is already loaded
 // Helper function to check if a script from the specified src is already loaded
function isScriptLoaded(src) {
  const scripts = Array.from(document.getElementsByTagName('script'));

  // Check if any script has an exact match for the src or an absolute URL that matches the expected path
  return scripts.some(script => {
    const scriptSrc = script.src;
    
    // Check for exact match with relative path or matching absolute URL
    const scriptPath = `.${new URL(script.src, window.location.origin).pathname}`;
   
    const scriptPath1 = new URL(script.src, window.location.origin).pathname;
    const normalizedSrc = new URL(src, window.location.origin).pathname;
    
    console.log("Path one (loaded):", scriptPath1);
    console.log("Path two (new):", normalizedSrc);
    
    //   console.log( "path one :",scriptPath),
    //   console.log("path two:",src)

      if (scriptPath1 === normalizedSrc)
      {

        console.log("this is alread loadedddddddddddddd")
      }


    return scriptSrc === src || scriptSrc.endsWith(src) || scriptSrc.includes(src);
  });
}

    // Helper function to set active class on the clicked sidebar link
    function setActiveLink(page) {
      const links = document.querySelectorAll('.sidebar a');
      links.forEach(link => link.classList.remove('active'));

      const activeLink = document.querySelector(`.sidebar a[href="#"][onclick*="${page}"]`);
      if (activeLink) {
        activeLink.classList.add('active');
      }
    }

    // Define initialization functions for each page
    function initializePage1() {
      console.log("Initializing Page 1");
      // Add code specific to Page 1 setup
    }

    function initializeBranchPage() {
      console.log("Initializing Branch Page");
      // Add code specific to Branch Page setup
    }

    function initializeInventoryPage() {
      console.log("Initializing Inventory Page");
      // Add code specific to Inventory Page setup
    }

    function initializeReportsPage() {
      console.log("Initializing Reports Page");
      // Add code specific to Reports Page setup
    }

    function initializeTransactionPage() {
      console.log("Initializing Transaction Page");
      // Add code specific to Transaction Page setup
    }

    function initializeBankTransactionPage() {
      console.log("Initializing Bank Transaction Page");
      // Add code specific to Bank Transaction Page setup
    }

    function initializeFinancialSummaryPage() {
      console.log("Initializing Financial Summary Page");
      // Add code specific to Financial Summary Page setup
    }

    // Example function for toggling sections in the sidebar
    function toggleSection(sectionId) {
      const section = document.getElementById(sectionId);
      if (section) {
        section.style.display = section.style.display === 'none' ? 'block' : 'none';
      }
    }

    // Initialize sidebar sections to be collapsed by default
    document.addEventListener('DOMContentLoaded', () => {
      const sections = document.querySelectorAll('.section-content');
      sections.forEach(section => (section.style.display = 'none'));
    });
  </script>


<script>
  // if ('serviceWorker' in navigator) {
  //   navigator.serviceWorker.register('/service-worker.js')
  //     .then(registration => {
  //       console.log('Service Worker registered with scope:', registration.scope);
  //     })
  //     .catch(error => {
  //       console.error('Service Worker registration failed:', error);
  //     });
  // }







  document.addEventListener('DOMContentLoaded', () => {
    const toggleButton = document.querySelector('.toggle-sidebar-btn');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.querySelector('.parent-container');

    toggleButton.addEventListener('click', () => {
    if (sidebar.classList.contains('collapsed')) {
        sidebar.classList.remove('collapsed'); // Show the sidebar
        mainContent.classList.remove('collapsed'); // Adjust main-content layout
    } else {
        sidebar.classList.add('collapsed'); // Hide the sidebar
        mainContent.classList.add('collapsed'); // Adjust main-content layout
    }
});




   
let touchStartX = 0;
let touchEndX = 0;

// Detect the start of a touch
document.addEventListener('touchstart', (e) => {
    touchStartX = e.touches[0].clientX;
});

// Detect movement during a touch
document.addEventListener('touchmove', (e) => {
    touchEndX = e.touches[0].clientX;
});

// Detect the end of a touch and determine if it was a swipe
document.addEventListener('touchend', () => {
    handleSwipe();
});
function handleSwipe() {
    if (touchStartX - touchEndX > 150) { // Swipe left detection (threshold = 50px)
        sidebar.classList.add('collapsed'); // Hide sidebar
        mainContent.classList.add('collapsed'); // Adds/removes the 'collapsed' class on main-content
 
    } else if (touchEndX - touchStartX > 150) { // Swipe right detection (to show sidebar)
        sidebar.classList.remove('collapsed'); // Show sidebar
        mainContent.classList.remove('collapsed'); // Adds/removes the 'collapsed' class on main-content
 
    }
}





});







</script>








</body>
</html>
