document.addEventListener('DOMContentLoaded', function () {
    // Get the left panel element
    var leftPanel = document.getElementById('left-panel');

    // Make sure the left panel exists before modifying it
    if (leftPanel) {
        // Create the left panel content
        leftPanel.innerHTML = `
        <h1>Admin Panel</h1>
        <span class="left-panel-close-button" onclick="showHideLeftPanel()">X</span>
        
        <!-- Correct HTML -->
        <div class="user-profile">
            <img id="user-profile-img" src="media/settings/default-profile.png" alt="User Profile">
            <h3 id="user-profile-name">Company Name</h3> <!-- This ID must be 'user-profile-name' -->
        </div>
        <div><i class="fas fa-user"></i> : <span id="user-name-show">User</span></div>
        
        <ul id="nav-links" class="nav-links">
            <!-- Dashboard Menu -->
            <li class="active"><a href="index.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
        
        
            <!-- Webhook Menu with Submenu Below -->
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <i class="fas fa-plug"></i> Webhook 
                    <i class="fas fa-chevron-down submenu-arrow"></i>
                </a>
                <ul class="submenu">
                    <li><a href="webhook-logs.php"><i class="fas fa-history"></i> Webhook Logs</a></li>
                    <li><a href="webhook-status.php"><i class="fas fa-check-circle"></i> Webhook Status</a></li>
                    <!-- You can add more submenus here as needed -->
                </ul>
            </li>

        
            <!-- WhatsApp Menu with Submenu Below -->
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <i class="fab fa-whatsapp"></i> WhatsApp 
                    <i class="fas fa-chevron-down submenu-arrow"></i>
                </a>
                <ul class="submenu">
                    <li><a href="whatsapp-webhook-config.php"><i class="fas fa-plug"></i> Webhook Configuration</a></li>
                    <li><a href="whatsapp-notifications.php"><i class="fas fa-bell"></i> Notifications</a></li>
                </ul>
            </li>
            

            <!-- Users Menu with Submenu Below -->
            <li class="menu-item">
                <a href="javascript:void(0)"><i class="fas fa-users"></i> Users <i class="fas fa-chevron-down submenu-arrow"></i></a>
                <ul class="submenu">
                    <li><a href="manage-user.php"><i class="fas fa-users"></i> Manage User</a></li>
                    <li><a href="manage-roles.php"><i class="fas fa-user-tag"></i> Manage Roles & Permissions</a></li>  <!-- New -->
                    <li><a href="manage-admin-pages.php"><i class="far fa-clone"></i> Manage Admin Pages</a></li>  <!-- New -->
                    <li><a href="manage-sessions.php"><i class="fas fa-user-clock"></i> Manage Sessions</a></li>
                </ul>
            </li>

            
            <!-- Settings Menu with Submenu Below -->
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <i class="fas fa-cogs"></i> Settings 
                    <i class="fas fa-chevron-down submenu-arrow"></i>
                </a>
                <ul class="submenu">
                    <li><a href="general-settings.php"><i class="fas fa-cogs"></i> General Settings</a></li>
                </ul>
            </li>

        </ul>
        `;
    }
});




document.addEventListener("DOMContentLoaded", function () {
    // Get sessionName and sessionRole from localStorage
    const sessionName = localStorage.getItem("sessionName");
    const sessionRole = localStorage.getItem("sessionRole");
    const nameSpan = document.getElementById("user-name-show");

    if (nameSpan) {
        if (sessionName && sessionName.trim() !== "") {
            nameSpan.textContent = sessionName;
        } else if (sessionRole && sessionRole.trim() !== "") {
            nameSpan.textContent = sessionRole;
        } else {
            nameSpan.textContent = "";
        }
    }

    // Fetch and set profile image + company name
    fetch("php/settings/fetch_profile_data.php")
        .then(response => response.json())
        .then(data => {
            // Set company logo
            const profileImg = document.getElementById("user-profile-img");
            if (profileImg && data.companyLogo && data.companyLogo.trim() !== "") {
                profileImg.src = data.companyLogo;
            }

            // Set company name
            const profileName = document.getElementById("user-profile-name");
            if (profileName && data.companyName && data.companyName.trim() !== "") {
                profileName.textContent = data.companyName;
            }
        })
        .catch(error => {
            console.error("Error fetching company profile:", error);
        });
});




document.addEventListener('DOMContentLoaded', function () {
    // This function will run when the document is fully loaded
    
    // Select all menu items and iterate over them
    const menuItems = document.querySelectorAll('.menu-item');

    menuItems.forEach(item => {
        // Add click event listener to each menu item
        item.querySelector('a').addEventListener('click', function () {
            // Get the submenu and arrow elements within the current menu item
            const submenu = item.querySelector('.submenu');
            const arrow = item.querySelector('.submenu-arrow');

            // Check if the submenu is already visible based on the max-height
            const isVisible = submenu.style.maxHeight && submenu.style.maxHeight !== '0px';

            // Toggle submenu visibility with sliding effect
            if (isVisible) {
                submenu.style.maxHeight = '0';  // Collapse the submenu
            } else {
                submenu.style.maxHeight = `${submenu.scrollHeight}px`;  // Expand the submenu to its full height
            }

            // Toggle the sub-open class for the arrow and item background
            item.classList.toggle('sub-open');
        });
    });
});



document.addEventListener('DOMContentLoaded', function () {
    // Create the header element
    var header = document.createElement('header');
    header.classList.add('header'); // Add a class to the header for styling

    // Create the header content as HTML
    var headerInnerHTML = `
        <div class="navbar">
            <div class="hamburger-container">
                <!-- Hamburger Icon -->
                <div class="hamburger-menu">
                    <i class="fas fa-bars" onclick="showHideLeftPanel()"></i>
                </div>

                <!-- Search Bar (next to the Hamburger Icon) -->
                <input type="text" id="search-input" placeholder="Search...">
            </div>

            <!-- Right Aligned Profile, Notifications, Logout -->
            <div class="nav-icons-container">
                <a href="profile.php"><i class="fas fa-user"></i></a>
                <a href="#notifications"><i class="fas fa-bell"></i></a>
                <a href="javascript:void(0)" onclick="logout()"><i class="fas fa-sign-out-alt"></i></a>
            </div>
        </div>
    `;

    // Set the inner HTML for the header
    header.innerHTML = headerInnerHTML;

    // Get the main content element by its ID (ensure this ID exists in your HTML)
    var mainContent = document.getElementById('main-content');

    // If main content exists, append the header to it
    if (mainContent) {
        // Append the header as the first child of the main content
        mainContent.prepend(header);
    }
});


// Function to toggle the left panel visibility and save state
function showHideLeftPanel() {
  const leftPanel = document.querySelector('.left-panel');
  const mainContent = document.querySelector('.main-content');

  const isHidden = leftPanel.classList.contains('left-panel-hidden');

  if (isHidden) {
    // Show the panel
    leftPanel.classList.remove('left-panel-hidden');
    leftPanel.classList.add('left-panel-show');

    mainContent.classList.remove('main-content-expand');
    mainContent.classList.add('main-content-normal');

    localStorage.setItem('leftPanelVisible', 'true');
  } else {
    // Hide the panel
    leftPanel.classList.remove('left-panel-show');
    leftPanel.classList.add('left-panel-hidden');

    mainContent.classList.remove('main-content-normal');
    mainContent.classList.add('main-content-expand');

    localStorage.setItem('leftPanelVisible', 'false');
  }
}

// Function to apply the saved state on page load
function applyLeftPanelState() {
  const leftPanel = document.querySelector('.left-panel');
  const mainContent = document.querySelector('.main-content');
  const savedState = localStorage.getItem('leftPanelVisible');

  if (savedState === 'false') {
    leftPanel.classList.remove('left-panel-show');
    leftPanel.classList.add('left-panel-hidden');

    mainContent.classList.remove('main-content-normal');
    mainContent.classList.add('main-content-expand');
  } else {
    // Default or saved true state: show panel
    leftPanel.classList.remove('left-panel-hidden');
    leftPanel.classList.add('left-panel-show');

    mainContent.classList.remove('main-content-expand');
    mainContent.classList.add('main-content-normal');
  }
}

// Apply state when DOM is ready
document.addEventListener('DOMContentLoaded', applyLeftPanelState);

    
    
    
// Function to toggle the header visibility
function toggleHeaderVisibility() {
    var header = document.querySelector('.header');

    if (!header) return; // Guard clause in case the header is not found

    // Toggle the 'hidden' class
    if (header.classList.contains('hidden')) {
        header.classList.remove('hidden');
    } else {
        header.classList.add('hidden');
    }
}

    
    
    
    // Function to check the session status every second
    function checkSession() {
        // Get sessionChecked and sessionKey from localStorage
        const sessionChecked = localStorage.getItem('sessionChecked');
        const sessionKey = localStorage.getItem('sessionKey');
        
        // Check if sessionChecked is "yes" and sessionKey is available and not empty
        if (sessionChecked === 'yes' && sessionKey && sessionKey.trim() !== '') {
            return; // Do nothing, session is valid and checked
        }
    
        // If session key exists and sessionChecked is not set, mark it as checked
        if (sessionKey && sessionKey.trim() !== '') {
            localStorage.setItem('sessionChecked', 'yes');
            window.location.href = 'index.php'; // Redirect to index.php
        } else {
            // If no session key or sessionKey is blank, redirect to login.php
            window.location.href = 'login.php';
        }
    }
    
    // Run checkSession every 1 second (1000 milliseconds)
    setInterval(checkSession, 1000);



    // Function to logout by clearing session data
    function logout() {
        // Remove session data from localStorage
        localStorage.removeItem('sessionKey');
        localStorage.removeItem('sessionChecked');
        
        // Optionally, redirect the user to the login page after logout
        window.location.href = 'login.php';
    }
    
    
async function applyRoleBasedMenu() {
    // Inject overlay with spinner if not present
    if (!document.getElementById('menu-loading-overlay')) {
        const overlay = document.createElement('div');
        overlay.id = 'menu-loading-overlay';
        overlay.style.position = 'fixed';
        overlay.style.top = '0';
        overlay.style.left = '0';
        overlay.style.width = '100%';
        overlay.style.height = '100%';
        overlay.style.background = 'rgba(0, 0, 0, 0.95)';  // Black translucent
        overlay.style.zIndex = '9999';
        overlay.style.display = 'flex';
        overlay.style.flexDirection = 'column';
        overlay.style.alignItems = 'center';
        overlay.style.justifyContent = 'center';
        overlay.style.color = '#fff';
        overlay.style.fontWeight = 'bold';
        overlay.style.fontSize = '20px';

        // Create spinner element
        const spinner = document.createElement('div');
        spinner.id = 'loading-spinner';
        spinner.style.border = '8px solid rgba(255, 255, 255, 0.3)';
        spinner.style.borderTop = '8px solid #fff';
        spinner.style.borderRadius = '50%';
        spinner.style.width = '60px';
        spinner.style.height = '60px';
        spinner.style.animation = 'spin 1s linear infinite';
        spinner.style.marginBottom = '15px';

        // Text
        const text = document.createElement('div');
        text.innerText = 'Loading menu...';

        overlay.appendChild(spinner);
        overlay.appendChild(text);
        document.body.appendChild(overlay);

        // Inject spinner keyframes CSS
        const styleTag = document.createElement('style');
        styleTag.type = 'text/css';
        styleTag.innerHTML = `
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(styleTag);
    }

    const overlay = document.getElementById('menu-loading-overlay');
    overlay.style.display = 'flex';

    const sessionRole = localStorage.getItem('sessionRole');

    if (!sessionRole || sessionRole.trim() === '') {
        window.location.href = 'login.php';
        return;
    }

    try {
        const response = await fetch('../php/fetch_roles.php');
        if (!response.ok) throw new Error('Failed to fetch roles');

        const rolesData = await response.json();
        const roleObject = rolesData.find(role => role.role === sessionRole);
        if (!roleObject || !Array.isArray(roleObject.pages)) return;

        const allowedPages = roleObject.pages.map(p => p.trim());

        const nav = document.getElementById('nav-links');
        if (!nav) return;

        const links = nav.querySelectorAll('a[href]');

        links.forEach(link => {
            const href = link.getAttribute('href');
            if (!href || href.startsWith('javascript')) return;

            const filename = href.split('/').pop().trim();
            if (!allowedPages.includes(filename)) {
                const li = link.closest('li');
                if (li) li.style.display = 'none';
            }
        });

        const menuItems = nav.querySelectorAll('.menu-item');
        menuItems.forEach(menuItem => {
            const submenuItems = menuItem.querySelectorAll('ul.submenu li');
            const visibleItems = Array.from(submenuItems).filter(li => li.style.display !== 'none');
            if (submenuItems.length > 0 && visibleItems.length === 0) {
                menuItem.style.display = 'none';
            }
        });

    } catch (error) {
        console.error('Error processing role-based menu:', error);
    } finally {
        overlay.style.display = 'none';
    }
}

document.addEventListener('DOMContentLoaded', applyRoleBasedMenu);



    
    
    
function loadExternalResources(callback) {
    // Define the URLs for the external resources (CSS and JS)
    const externalLinks = [
        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css',
        'https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap',
        'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css',
        'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css'
    ];

    const externalScripts = [
        'https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js',
        'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.1/xlsx.full.min.js',
        'https://cdn.jsdelivr.net/npm/lazysizes@5.3.0/lazysizes.min.js',
        'https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js',
        'https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js'
        
    ];

    // Load all CSS resources
    const loadCss = (href) => {
        return new Promise((resolve, reject) => {
            const link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = href;
            link.onload = resolve;
            link.onerror = () => reject(new Error(`Failed to load CSS: ${href}`));
            document.head.appendChild(link);
        });
    };

    // Load all JS resources (with defer attribute)
    const loadScript = (src, defer = false) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            if (defer) {
                script.defer = true; // Add defer attribute to the script tag
            }
            script.onload = resolve;
            script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
            document.head.appendChild(script);
        });
    };

    // Load all CSS links
    const cssPromises = externalLinks.map(loadCss);
    
    // Load all JS scripts (with defer for SweetAlert2)
    const scriptPromises = externalScripts.map(script => loadScript(script, true));  // Use defer for SweetAlert2

    // Wait for all CSS and JS resources to load
    Promise.all([...cssPromises, ...scriptPromises])
        .then(() => {
            if (callback) {
                callback(); // Callback after resources are loaded
            }
        })
        .catch((error) => {
            console.error('Error loading resources:', error);
        });
}

    
// Wait for the DOM to be fully loaded, then call the loadNavbar function
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM fully loaded and parsed');
    loadExternalResources();  // Call the function to load external resources
    applyRoleBasedMenu();
});
 
    
    
    
    
    
    
    
document.addEventListener("DOMContentLoaded", function () {
    // Wait 2 seconds before continuing
    setTimeout(() => {
        // Check if the peerId exists in localStorage
        let peerId = localStorage.getItem("peerId");

        if (!peerId) {
            // If no peerId is found, generate a new one
            peerId = generateRandomPeerId();
            localStorage.setItem("peerId", peerId);
            console.log("📡 New Peer ID generated and saved:", peerId);
        } else {
            console.log("📡 Existing Peer ID found:", peerId);
        }

        // Send the peerId to the backend immediately
        sendPeerIdToBackend(peerId);

        // Send peerId to the backend every 10 seconds
        setInterval(() => {
            sendPeerIdToBackend(peerId);
        }, 10000); // 10 seconds interval

    }, 2000); // <-- 2-second delay
});

// Function to generate a random 10-digit peer ID
function generateRandomPeerId() {
    let peerId = '';
    for (let i = 0; i < 10; i++) {
        peerId += Math.floor(Math.random() * 10); // Random digit between 0 and 9
    }
    return peerId;
}

// Function to send peerId to the backend
function sendPeerIdToBackend(peerId) {
    const sessionData = {
        peerId: peerId,
        sessionEmail: localStorage.getItem("sessionEmail") || "",
        sessionName: localStorage.getItem("sessionName") || "",
        sessionRole: localStorage.getItem("sessionRole") || "",
        sessionTime: new Date().toISOString(),
        sessionKey: localStorage.getItem("sessionKey") || ""
    };

    fetch("php/login/save_session_data.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(sessionData)
    })
    .then(response => response.json())
    .then(data => {
        console.log("✅ Session data sent:", data);
    })
    .catch(err => {
        console.error("❌ Error sending session data:", err);
    });
}












    
    // Function to show a modeless processing message with custom message
    function showProcessingMessage(message, timerOn = true, showCloseButton = false, buttonLabel = "X") {
        Swal.fire({
          icon: 'info',                   // Info icon for processing
          title: message,                 // Custom message
          showConfirmButton: showCloseButton,   // Set whether to show the close button
          confirmButtonText: buttonLabel, // Set the close button label (default is "X")
          timer: timerOn ? 3000 : null,   // If timerOn is true, set the timer to 3000ms, else don't set timer
          timerProgressBar: true,         // Show the progress bar
          toast: true,                    // Make it a toast message
          position: 'top',                // Position at the top
          background: '#fff',            // Set background color
          customClass: {
            title: 'sweetalert-title',    // Add custom class for title styling
          },
        });
      }
  
  
  // Function to show a modeless success message
  function showSuccessMessage(message, timerOn = true, showCloseButton = false, buttonLabel = "X") {
    Swal.fire({
      icon: 'success',                // Success icon
      title: message,                 // Success message
      showConfirmButton: showCloseButton,  // Set whether to show the close button
      confirmButtonText: buttonLabel,     // Set the close button label (default is "X")
      timer: timerOn ? 3000 : null,      // If timerOn is true, set the timer to 3000ms, else don't set timer
      timerProgressBar: true,         // Show the progress bar
      toast: true,                    // Make it a toast message
      position: 'top',                // Position at the top
      background: '#fff',            // Set background color
      customClass: {
        title: 'sweetalert-title',    // Add custom class for title styling
      },
    });
  }
  
  // Function to show a modeless error message
  function showErrorMessage(message, timerOn = true, showCloseButton = false, buttonLabel = "X") {
    Swal.fire({
      icon: 'error',                  // Error icon
      title: message,                 // Error message
      showConfirmButton: showCloseButton,  // Set whether to show the close button
      confirmButtonText: buttonLabel,     // Set the close button label (default is "X")
      timer: timerOn ? 3000 : null,      // If timerOn is true, set the timer to 3000ms, else don't set timer
      timerProgressBar: true,         // Show the progress bar
      toast: true,                    // Make it a toast message
      position: 'top',                // Position at the top
      background: '#fff',            // Set background color
      customClass: {
        title: 'sweetalert-title',    // Add custom class for title styling
      },
    });
  }
  




  // Function to show a confirmation message with custom button labels and timer option
function showConfirmationMessage(message, onConfirm, onCancel, confirmLabel = 'Yes', cancelLabel = 'No', timerOn = true, timerDuration = 5000) {
    Swal.fire({
        icon: 'question',              // Question icon
        title: message,                // Custom message
        showCancelButton: true,        // Show the "Cancel" button
        confirmButtonText: confirmLabel,      // Custom label for the confirm button (default is "Yes")
        cancelButtonText: cancelLabel,        // Custom label for the cancel button (default is "No")
        background: '#fff',           // Set background color
        customClass: {
            title: 'sweetalert-title', // Add custom class for title styling
        },
        timer: timerOn ? timerDuration : null, // Set the timer if timerOn is true (default 5000ms)
        timerProgressBar: true,       // Show a progress bar for the timer
        willClose: () => {            // Callback for when the dialog closes automatically
            if (timerOn && typeof onCancel === 'function') {
                onCancel();  // Execute onCancel if timer runs out
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            // Execute the action if confirmed
            if (typeof onConfirm === 'function') {
                onConfirm();  // Call the onConfirm callback
            }
        } else if (result.isDismissed) {
            // Execute the action if dismissed (either through Cancel or timer)
            if (typeof onCancel === 'function') {
                onCancel();  // Call the onCancel callback
            }
        }
    });
}


function closeSwal() {
  Swal.close();
}
