// Open the modal for adding a new file
function openModal() {
    document.getElementById("modalTitle").innerText = "Add New File";
    document.getElementById("documentForm").reset(); // Reset the form
    document.getElementById("documentId").value = ""; // Ensure no documentId is set (for new files)
    document.getElementById("existingFileSection").style.display = "none"; // Hide the existing file section
    document.getElementById("documentModal").style.display = "block"; // Show the modal
}

// Open the modal for editing an existing file
function openEditModal(documentId, fileName, author, description, fileSize, resolution, filePath) {
    document.getElementById("modalTitle").innerText = "Edit File";
    document.getElementById("documentId").value = documentId; // Set document ID
    document.getElementById("fileName").value = fileName; // Pre-fill file name
    document.getElementById("fileAuthor").value = author; // Pre-fill author
    document.getElementById("fileDescription").value = description; // Pre-fill description

    // Show existing file information
    document.getElementById("existingFileSection").style.display = "block";
    document.getElementById("existingFileLink").href = filePath; // Link to the current file
    document.getElementById("existingFileLink").innerText = fileName + ' (' + fileSize + ' bytes, ' + resolution + ')';

    document.getElementById("documentModal").style.display = "block"; // Show the modal
}

// Wrapper closeModal that delegates to a global implementation if available.
// Accepts optional modalId for consistency with other scripts.
function closeModal(modalId) {
    if (typeof window.closeModal === 'function' && window.closeModal !== closeModal) {
        // delegate to the global implementation
        window.closeModal(modalId);
        return;
    }

    // fallback: close the document modal
    const doc = document.getElementById('documentModal');
    if (doc) doc.style.display = 'none';
}

// Function to remove existing file
function removeExistingFile() {
    document.getElementById("existingFileSection").style.display = "none"; // Hide the existing file section
    // Optionally, you could set a flag in your form to mark the file for deletion server-side
}
// Function to close the file preview modal
function closeFileModal() {
    document.getElementById('fileModal').style.display = "none";
}

// Function to confirm file deletion
function confirmDelete(documentId) {
    if (confirm('Are you sure you want to delete this file?')) {
        window.location.href = 'admin.php?delete_id=' + documentId; // Redirect to delete action
    }
}

// Function to handle removing the existing file (for editing)
function removeExistingFile() {
    document.getElementById("existingFileSection").style.display = "none"; // Hide the existing file section
    // Optionally, set a hidden field to mark the file for deletion server-side (not shown here)
}
