document.querySelectorAll('.menu-item').forEach(item => {
    item.addEventListener('click', function(event) {
        event.preventDefault(); // Prevent default anchor behavior
        const contentUrl = this.getAttribute('data-content');
        loadContent(contentUrl);
    });
});

function loadContent(url) {
    const dynamicContent = document.getElementById('dynamicContent');
    const xhr = new XMLHttpRequest();
    
    xhr.open('GET', url, true);
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            dynamicContent.innerHTML = xhr.responseText;
            // Update the URL in the address bar
            const pageName = url.split('/').pop(); // Get the filename from the URL
            history.pushState(null, '', `home.php?page=${pageName}`);
        } else {
            dynamicContent.innerHTML = '<p>Error loading content. Please try again.</p>';
        }
    };
    
    xhr.onerror = function() {
        dynamicContent.innerHTML = '<p>Error loading content. Please check your connection.</p>';
    };
    
    xhr.send();
}
window.onload = function() {
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('page');

    if (page) {
        loadContent(page); // Load the content specified in the URL
    } else {
        loadContent('pupils.php'); // Load default content if no page parameter
    }
};
window.onpopstate = function(event) {
    // Optionally, you can load the content based on the URL when navigating back/forward
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('page');
    if (page) {
        loadContent(page);
    } else {
        loadContent('pupils.php'); // Default content
    }
};