document.addEventListener("DOMContentLoaded", function() {
    setupViewModal();
});

function setupViewModal() {
    // Get the modal
    const modalView = document.getElementById("documentViewModal");

    // Get all links that should open in the modal
    const links = document.querySelectorAll(".edocmanplayerbtn");
    const links1 = document.querySelectorAll(".pdfviewer");

    // Get the iframe inside the modal
    const modalIframeView = document.getElementById("modalIframe");

    // Get the close button
    const closeBtn = document.querySelector(".close-btn");

    // Loop through each link and add a click event listener
    links.forEach(link => {
        link.addEventListener("click", function(event) {
            event.preventDefault(); // Prevent default link behavior
            var url = this.href; // Get the link URL
            modalIframeView.src = url; // Load the URL inside the iframe
            modalView.style.display = "flex"; // Show the modal
        });
    });

    links1.forEach(link => {
        link.addEventListener("click", function(event) {
            event.preventDefault(); // Prevent default link behavior
            var url = this.href; // Get the link URL
            modalIframeView.src = url; // Load the URL inside the iframe
            modalView.style.display = "flex"; // Show the modal
        });
    });

    // Close the modal when clicking the close button
    closeBtn.onclick = function() {
        modalView.style.display = "none";
        modalIframeView.src = ""; // Reset iframe to stop loading content
    };

    const modalContent = document.getElementById('modalViewContent');
    const toggleFullscreenButton = document.getElementById('fullscreenBtn');
    toggleFullscreenButton.onclick = function() {
        modalContent.classList.toggle('fullscreen');
        if (modalContent.classList.contains('fullscreen')) {
            toggleFullscreenButton.innerHTML = '<i class="fas fa-compress"></i>';
        } else {
            toggleFullscreenButton.innerHTML = '<i class="fas fa-expand"></i>'; 
        }
    };

    const modals = document.querySelectorAll('.edmd'); 
    window.onclick = function(event) {
        modals.forEach(modal => {
            if (event.target === modal) {
                modal.style.display = "none";
                const iframe = modal.querySelector('iframe'); 
                if (iframe) {
                    iframe.src = "";
                }
            }
        });
    };
}
