function openFileModal(title, author, type, uploaded, updated, filePath, documentId, description, fileSize, resolution, divisionId, refNo) {
    // Update modal metadatas
    document.getElementById('fileTitle').textContent = title;
    // Helper: set element text or value depending on element type
    function setElTextOrValue(el, text) {
        if (!el) return;
        const tag = (el.tagName || '').toLowerCase();
        if (tag === 'input' || tag === 'textarea') {
            el.value = text || '';
        } else {
            el.textContent = text || 'N/A';
        }
    }

    // write to preview-only author element to avoid colliding with add/edit form fields
    const previewAuthorEl = document.getElementById('preview_fileAuthor');
    const fileAuthorEl = document.getElementById('fileAuthor');
    setElTextOrValue(previewAuthorEl, author);
    setElTextOrValue(fileAuthorEl, author);
    document.getElementById('file_type').textContent = type;
    document.getElementById('uploadDate').textContent = uploaded;
    document.getElementById('lastUpdated').textContent = updated;
    // write description to both preview span and form textarea if present
    const previewDescriptionEl = document.getElementById('preview_fileDescription');
    const fileDescriptionEl = document.getElementById('fileDescription');
    setElTextOrValue(previewDescriptionEl, description || "N/A");
    setElTextOrValue(fileDescriptionEl, description || "");
    document.getElementById('fileSize').textContent = fileSize ? formatFileSize(fileSize) : "N/A";
    document.getElementById('fileResolution').textContent = resolution || "N/A";

    // Set download button action
    document.getElementById('modalDownloadBtn').setAttribute('onclick', `window.location.href='download.php?id=${documentId}&division_id=${divisionId}'`);

    // Set preview based on file type and division
    const previewArea = document.getElementById('previewArea');
    previewArea.innerHTML = ""; // Clear previous content
    // make type matching case-insensitive
    if (type.match(/(jpg|jpeg|png|gif|svg)$/i)) {
        previewArea.innerHTML = `<img src="view.php?id=${documentId}&division_id=${divisionId}" alt="Preview Image">`;
    } else if (type.match(/(mp4|mpeg|avi|mov|wmv)$/)) {
        previewArea.innerHTML = `<video controls><source src="view.php?id=${documentId}&division_id=${divisionId}" type="video/${type}">Your browser does not support the video tag.</video>`;
    } else if (type.match(/(mp3|aac|wav|aiff|pcm)$/)) {
        previewArea.innerHTML = `<audio controls><source src="view.php?id=${documentId}&division_id=${divisionId}" type="audio/${type}">Your browser does not support the audio tag.</audio>`;
    } else if (type.match(/(pdf)$/)) {
        previewArea.innerHTML = `<iframe src="view.php?id=${documentId}&division_id=${divisionId}" style="width: 100%; height: 100%;" frameborder="0"></iframe>`;
    } else if (type.match(/(doc|docx|xls|xlsx|ppt|pptx|js|html|py|php|sql|css)$/)) {
        if (type.match(/(ppt|pptx|xls|xlsx)$/)) {
            previewArea.innerHTML = `<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(window.location.origin + '/view.php?id=' + documentId + '&division_id=' + divisionId)}" style="width: 100%; height: 100%;" frameborder="0"></iframe>`;
        } else {
            previewArea.innerHTML = `<p>Preview not available for ${type} files. Download to view.</p>`;
        }
    } else {
        previewArea.innerHTML = `<p>Unsupported file type.</p>`;
    }

    // Display the modal
    document.getElementById('fileModal').style.display = "block";

    // populate reference number if element exists
    const refEl = document.getElementById('ref_no');
    if (refEl) refEl.textContent = refNo || 'N/A';

    // set globals for other actions (download/email)
    window.currentDocumentId = documentId;
    window.currentFileName = title;
}

// Helper function to format file size
function formatFileSize(bytes) {
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes === 0) return '0 Byte';
    const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

// Function to update the current division name
function updateCurrentDivisionName() {
    const divisionDropdown = document.getElementById("divisionDropdown");
    const currentDivisionName = divisionDropdown.options[divisionDropdown.selectedIndex].text;
    document.getElementById("currentDivisionName").innerText = currentDivisionName;
}

// Function to update file statistics
function updateFileStatistics() {
    const divisionId = document.getElementById("divisionDropdown").value;
    fetch(`piechart.php?division_id=${divisionId}`)
        .then(response => response.text())
        .then(data => {
            document.querySelector('.file-summary').innerHTML = data;
            create_pie_chart(); // Recreate the pie chart with new data
        });
}

// Call the functions on page load and when the division changes
document.addEventListener('DOMContentLoaded', () => {
    updateCurrentDivisionName();
    updateFileStatistics();
});