// Global function for number spinner
function incrementQuantity() {
    var input = document.getElementById('doc-quantity');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        input.value = currentValue + 1;
        input.dispatchEvent(new Event('input', { bubbles: true }));
    }
}

function decrementQuantity() {
    var input = document.getElementById('doc-quantity');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        var minValue = parseInt(input.getAttribute('min')) || 0;
        if (currentValue > minValue) {
            input.value = currentValue - 1;
            input.dispatchEvent(new Event('input', { bubbles: true }));
        }
    }
}

function incrementExportQuantity() {
    var input = document.getElementById('export-quantity');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        input.value = currentValue + 1;
        input.dispatchEvent(new Event('input', { bubbles: true }));
    }
}

function decrementExportQuantity() {
    var input = document.getElementById('export-quantity');
    if (input) {
        var currentValue = parseInt(input.value) || 0;
        var minValue = parseInt(input.getAttribute('min')) || 1;
        if (currentValue > minValue) {
            input.value = currentValue - 1;
            input.dispatchEvent(new Event('input', { bubbles: true }));
        }
    }
}

// Helper function to safely reload page without white box flash
function safeReload() {
    document.body.classList.add('reloading');
    var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
    elementsToHide.forEach(function(el) {
        el.style.display = 'none';
        el.style.visibility = 'hidden';
        el.style.opacity = '0';
        el.classList.remove('show');
    });
    // Add critical CSS to prevent flash
    var style = document.createElement('style');
    style.id = 'reload-prevent-flash';
    style.textContent = '* { transition: none !important; animation: none !important; } .page-loader, .modal-backdrop, .modal-overlay { display: none !important; visibility: hidden !important; opacity: 0 !important; }';
    document.head.appendChild(style);
    void document.body.offsetHeight;
    requestAnimationFrame(function() {
        requestAnimationFrame(function() {
            location.reload();
        });
    });
}

document.addEventListener('DOMContentLoaded', function () {
    var modal = document.getElementById('incoming-modal');
    if (!modal) { return; }

    // Fix mobile date input issues
    function fixMobileDateInputs() {
        var dateInputs = document.querySelectorAll('input[type="date"]');
        dateInputs.forEach(function(input) {
            // Ensure proper date format for mobile browsers
            input.addEventListener('focus', function() {
                // Allow selecting past dates: remove any previously set minimum
                input.removeAttribute('min');
            });
            
            // Handle mobile date input blur to ensure proper formatting
            input.addEventListener('blur', function() {
                if (input.value) {
                    // Validate and format the date
                    var date = new Date(input.value);
                    if (!isNaN(date.getTime())) {
                        var year = date.getFullYear();
                        var month = String(date.getMonth() + 1).padStart(2, '0');
                        var day = String(date.getDate()).padStart(2, '0');
                        input.value = year + '-' + month + '-' + day;
                    }
                }
            });
        });
    }
    
    // Apply mobile date fixes
    fixMobileDateInputs();
    
    // Fix quantity input validation
    function fixQuantityInput() {
        var quantityInput = document.getElementById('doc-quantity');
        if (quantityInput) {
            // Prevent non-numeric input
            quantityInput.addEventListener('input', function(e) {
                // Remove any non-numeric characters
                this.value = this.value.replace(/[^0-9]/g, '');
            });
            
            // Prevent paste of non-numeric content
            quantityInput.addEventListener('paste', function(e) {
                e.preventDefault();
                var paste = (e.clipboardData || window.clipboardData).getData('text');
                var numericOnly = paste.replace(/[^0-9]/g, '');
                this.value = numericOnly;
            });
            
            // Prevent keypress of non-numeric characters
            quantityInput.addEventListener('keypress', function(e) {
                // Allow: backspace, delete, tab, escape, enter
                if ([8, 9, 27, 13, 46].indexOf(e.keyCode) !== -1 ||
                    // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X
                    (e.keyCode === 65 && e.ctrlKey === true) ||
                    (e.keyCode === 67 && e.ctrlKey === true) ||
                    (e.keyCode === 86 && e.ctrlKey === true) ||
                    (e.keyCode === 88 && e.ctrlKey === true)) {
                    return;
                }
                // Ensure that it is a number and stop the keypress
                if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
            });
        }
    }
    
    // Apply quantity input fixes
    fixQuantityInput();
    
    // Add click handlers for date icons and inputs
    function setupDateIconHandlers() {
        // Handle date icons
        var dateIcons = document.querySelectorAll('.date-icon');
        dateIcons.forEach(function(icon) {
            icon.addEventListener('click', function() {
                var targetId = this.getAttribute('data-target');
                var targetInput = document.getElementById(targetId);
                if (targetInput) {
                    try {
                        targetInput.focus();
                        targetInput.showPicker();
                    } catch (e) {
                        // Fallback for browsers without showPicker()
                        targetInput.click();
                    }
                }
            });
        });
        
        // Handle clicking anywhere on date inputs
        var dateInputs = document.querySelectorAll('input[type="date"]');
        dateInputs.forEach(function(input) {
            input.addEventListener('click', function(e) {
                try {
                    this.focus();
                    this.showPicker();
                } catch (err) {
                    // Fallback for browsers without showPicker()
                    // The native click will handle it
                }
            });
            
            // Also handle focus event
            input.addEventListener('focus', function(e) {
                try {
                    // Small delay to ensure focus is complete
                    setTimeout(function() {
                        input.showPicker();
                    }, 100);
                } catch (err) {
                    // Fallback - do nothing, native behavior will work
                }
            });
        });
    }
    
    // Setup date icon handlers
    setupDateIconHandlers();

    var actionInput = document.getElementById('incoming-action');
    var idInput = document.getElementById('incoming-id');
    var submitBtn = document.getElementById('incoming-submit');
    var titleEl = document.getElementById('incoming-modal-title');
    var lastFocused = null;

    function openModal(){
        lastFocused = document.activeElement;
        modal.classList.add('show');
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-hidden','false');
        modal.style.display = 'flex';
        modal.style.zIndex = '100000';
        
        // Ensure upload button is in default state when modal opens
        setTimeout(function() {
            resetUploadButton();
            toggleViewButton();
        }, 100);
        
        var first = document.getElementById('doc-symbol');
        if (first) { try { first.focus(); } catch(_) {} }
        
        // Re-apply mobile date fixes and quantity validation when modal opens
        setTimeout(function() {
            fixMobileDateInputs();
            fixQuantityInput();
        }, 100);
    }
    function closeModal(){
        var active = document.activeElement;
        if (active && modal.contains(active)) { try { active.blur(); } catch(_) {} }
        // Hide modal immediately to prevent white box flash
        modal.style.display = 'none';
        modal.style.visibility = 'hidden';
        modal.style.opacity = '0';
        modal.classList.remove('show');
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-hidden','true');
        // Force reflow to ensure styles are applied
        void modal.offsetHeight;
        if (lastFocused && document.contains(lastFocused)) { try { lastFocused.focus(); } catch(_) {} }
        lastFocused = null;
        
        // Reset upload button when modal closes
        resetUploadButton();
    }


    function setCreate(){
        if (actionInput) actionInput.value = 'create';
        if (idInput) idInput.value = '0';
        var form = document.getElementById('incoming-form');
        if (form) form.reset();
        if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-create') || 'Lưu');
        if (titleEl) titleEl.textContent = (titleEl.getAttribute('data-label-create') || 'THÊM CÔNG VĂN ĐẾN');
        
        // Reset doc-code field to next document ID and sync hidden upload id
        var docCodeField = document.getElementById('doc-code');
        if (docCodeField) {
            var nextId = docCodeField.getAttribute('data-next-id') || '1';
            docCodeField.value = nextId;
            docCodeField.setAttribute('readonly', 'readonly');
            var hiddenUploadId = document.getElementById('document-id');
            if (hiddenUploadId) { hiddenUploadId.value = String(nextId); }
        }
        // Clear any edit-mode getter
        try { if (window.getCurrentDocumentId) { delete window.getCurrentDocumentId; } } catch(_) {}
        // Reset custom select label/hidden input for company field
        try {
            var custom = document.getElementById('company-custom-select');
            if (custom) {
                var btn = custom.querySelector('.custom-select-toggle');
                var hidden = document.getElementById('doc-company-id');
                if (btn) {
                    var ph = btn.getAttribute('data-placeholder') || '--';
                    btn.textContent = ph;
                }
                if (hidden) { hidden.value = ''; }
                custom.classList.remove('open');
            }
        } catch(_) {}
        // Reset custom select label/hidden input for category field
        try {
            var custom = document.getElementById('category-custom-select');
            if (custom) {
                var btn = custom.querySelector('.custom-select-toggle');
                var hidden = document.getElementById('doc-category-id');
                if (btn) {
                    var ph = btn.getAttribute('data-placeholder') || '--';
                    btn.textContent = ph;
                }
                if (hidden) { hidden.value = ''; }
                custom.classList.remove('open');
            }
        } catch(_) {}
        // Reset custom select label/hidden input for doctype field
        try {
            var custom = document.getElementById('doctype-custom-select');
            if (custom) {
                var btn = custom.querySelector('.custom-select-toggle');
                var hidden = document.getElementById('doc-type-id');
                if (btn) {
                    var ph = btn.getAttribute('data-placeholder') || '--';
                    btn.textContent = ph;
                }
                if (hidden) { hidden.value = ''; }
                custom.classList.remove('open');
            }
        } catch(_) {}
        // Reset custom select label/hidden input for docpagetype field
        try {
            var custom = document.getElementById('docpagetype-custom-select');
            if (custom) {
                var btn = custom.querySelector('.custom-select-toggle');
                var hidden = document.getElementById('doc-typedoc-id');
                if (btn) {
                    var ph = btn.getAttribute('data-placeholder') || '--';
                    btn.textContent = ph;
                }
                if (hidden) { hidden.value = ''; }
                custom.classList.remove('open');
            }
        } catch(_) {}
        
        // Reset upload state
        tempFileName = null;
        resetUploadButton();
        
        // Hide view button when resetting
        var viewBtn = document.getElementById('view-pdf-btn');
        if (viewBtn) {
            viewBtn.style.display = 'none';
        }
        
        // Toggle view button based on file URL
        toggleViewButton();
        
        // Fix modal state
        var modal = document.getElementById('incoming-modal');
        if (modal) {
            modal.removeAttribute('aria-hidden');
            modal.setAttribute('aria-hidden', 'false');
            modal.removeAttribute('aria-hidden');
        }
        
        var first = document.getElementById('doc-symbol');
        if (first) { try { first.focus(); } catch(_) {} }
    }

    function setUpdate(docId){
        if (actionInput) actionInput.value = 'update';
        if (idInput) idInput.value = docId;
        if (submitBtn) submitBtn.textContent = (submitBtn.getAttribute('data-label-update') || 'Cập nhật');
        if (titleEl) titleEl.textContent = (titleEl.getAttribute('data-label-update') || 'CẬP NHẬT CÔNG VĂN ĐẾN');
        
        // Ensure doc-code field is readonly in update mode
        var docCodeField = document.getElementById('doc-code');
        if (docCodeField) {
            docCodeField.setAttribute('readonly', true);
            docCodeField.style.color = '#7adcc9';
            docCodeField.style.fontWeight = 'bold';
        }
        
        // Fix modal state
        var modal = document.getElementById('incoming-modal');
        if (modal) {
            modal.removeAttribute('aria-hidden');
            modal.setAttribute('aria-hidden', 'false');
            modal.removeAttribute('aria-hidden');
        }
    }

    document.addEventListener('click', function(e){
        
        var addBtn = e.target.closest('[data-incoming-open="create"]');
        if(addBtn){ setCreate(); openModal(); return; }

        var viewBtn = e.target.closest('[data-incoming-view]');
        if(viewBtn){ 
            var docId = viewBtn.getAttribute('data-incoming-view');
            viewDocument(docId);
            return; 
        }

        var editBtn = e.target.closest('[data-incoming-edit]');
        if(editBtn){ 
            var docId = editBtn.getAttribute('data-incoming-edit');
            editDocument(docId);
            return; 
        }

        var deleteBtn = e.target.closest('[data-incoming-delete]');
        if(deleteBtn){ 
            var docId = deleteBtn.getAttribute('data-incoming-delete');
            deleteDocument(docId);
            return; 
        }

        var exportBtn = e.target.closest('[data-incoming-export]');
        if(exportBtn){ 
            var docId = exportBtn.getAttribute('data-incoming-export');
            exportDocument(docId);
            return; 
        }

        // View PDF button in form
        var viewPdfBtn = e.target.closest('#view-pdf-btn');
        if(viewPdfBtn){ 
            var fileInput = document.getElementById('doc-file');
            if (fileInput && fileInput.value.trim()) {
                viewDocumentFromFile(fileInput.value);
            } else {
            }
            return; 
        }

        // Ignore close actions coming from inside the PDF viewer modal
        var isInsidePdfModal = !!e.target.closest('#pdf-viewer-modal');
        if(!isInsidePdfModal && e.target.closest('[data-modal-close]')){ 
            // Check if it's export modal close
            var isExportModal = !!e.target.closest('#export-modal');
            if (isExportModal) {
                closeExportModal();
            } else {
                closeModal(); 
            }
        }
    });

    document.addEventListener('keydown', function(e){ 
        if(e.key === 'Escape'){ 
            var exportModal = document.getElementById('export-modal');
            if (exportModal && exportModal.style.display === 'flex') {
                closeExportModal();
            } else {
                closeModal(); 
            }
        }
    });

    // Export form submission
    document.addEventListener('submit', function(e) {
        if (e.target && e.target.id === 'export-form') {
            e.preventDefault();
            
            var docId = document.getElementById('export-doc-id').value;
            var quantity = document.getElementById('export-quantity').value;
            var recipient = document.getElementById('export-recipient-id').value;
            var reason = document.getElementById('export-reason').value;
            var quantityField = document.getElementById('export-quantity');
            var maxQuantity = quantityField ? parseInt(quantityField.max) : null;
            
            var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
            
            if (!docId || !quantity || !recipient || !reason) {
                var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['export_validation_missing_data']) ? window.__MESSAGES__['export_validation_missing_data'] : 'Vui lòng điền đầy đủ thông tin';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                if (window.showToast) {
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(errorMsg);
                }
                return;
            }
            
            // Validate quantity against max
            if (maxQuantity && parseInt(quantity) > maxQuantity) {
                var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['export_validation_exceed_quantity']) ? window.__MESSAGES__['export_validation_exceed_quantity'] : 'Số lượng xuất không được vượt quá số lượng hiện có';
                errorMsg += ' (' + maxQuantity + ')';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                if (window.showToast) {
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(errorMsg);
                }
                return;
            }
            
            // Validate quantity is positive
            if (parseInt(quantity) <= 0) {
                var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['export_validation_positive_quantity']) ? window.__MESSAGES__['export_validation_positive_quantity'] : 'Số lượng xuất phải lớn hơn 0';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                if (window.showToast) {
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(errorMsg);
                }
                return;
            }
            
            // Process export
            processExport(docId, parseInt(quantity), recipient, reason);
        }
    });
    
    // Function to process export
    function processExport(docId, quantity, recipient, reason) {
        // Send AJAX request to server
        var formData = new FormData();
        formData.append('action', 'export');
        formData.append('document_id', docId);
        formData.append('export_quantity', quantity);
        formData.append('export_recipient', recipient);
        formData.append('export_reason', reason);
        
        // Add license (required for validation)
        var licEl = document.getElementById('incoming-license');
        formData.append('license', (licEl && licEl.value) ? licEl.value : '');
        
        fetch('modules/incoming_service.php', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'fetch',
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (data.ok) {
                // Close modal on success
                closeExportModal();
                
                // Show success toast
                if (window.showToast) {
                    var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                    var successWithHeader = '<div class="success-header">' + successTitle + '</div>' + data.message;
                    window.showToast('success', successWithHeader);
                }
                
                // Reload page to update quantity
                setTimeout(function() {
                    // Hide all elements before reload
                    document.body.classList.add('reloading');
                    var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
                    elementsToHide.forEach(function(el) {
                        el.style.display = 'none';
                        el.style.visibility = 'hidden';
                        el.style.opacity = '0';
                        el.classList.remove('show');
                    });
                    void document.body.offsetHeight;
                    safeReload();
                }, 1500);
            } else {
                // Keep modal open on error, only show error toast
                if (window.showToast) {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'LỖI';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + data.message;
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(data.message);
                }
            }
        })
        .catch(function(error) {
            console.error('Export error:', error);
            // Keep modal open on error
            if (window.showToast) {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'LỖI';
                var errorMsg = 'Có lỗi xảy ra khi xuất file';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                window.showToast('error', errorWithHeader);
            } else {
                alert('Có lỗi xảy ra khi xuất file');
            }
        });
    }

    // Add event listener for file input changes
    document.addEventListener('input', function(e) {
        if (e.target && e.target.id === 'doc-file') {
            toggleViewButton();
        }
    });

    // Add event listener for file input changes (for programmatic changes)
    document.addEventListener('change', function(e) {
        if (e.target && e.target.id === 'doc-file') {
            toggleViewButton();
        }
    });

    // Function to export document
    function exportDocument(docId) {
        if (!docId) {
            return;
        }
        
        // Find the document data from the table
        var exportButton = document.querySelector('[data-incoming-export="' + docId + '"]');
        if (!exportButton) {
            return;
        }
        
        var row = exportButton.closest('tr');
        if (!row) {
            return;
        }
        
        // Get document data from data attributes
        var rowData = row.getAttribute('data-document');
        var docData = rowData ? JSON.parse(rowData) : {};
        
        // Open export modal
        openExportModal(docId, docData);
    }
    
    // Function to open export modal
    function openExportModal(docId, docData) {
        var modal = document.getElementById('export-modal');
        if (!modal) {
            console.error('Export modal not found');
            return;
        }
        
        // Set document ID
        var docIdField = document.getElementById('export-doc-id');
        if (docIdField) {
            docIdField.value = docId;
        }
        
        // Set max quantity based on available quantity
        var quantityField = document.getElementById('export-quantity');
        if (quantityField && docData.quantity) {
            quantityField.max = docData.quantity;
            var placeholderText = (window.__MESSAGES__ && window.__MESSAGES__['export_quantity_placeholder']) ? window.__MESSAGES__['export_quantity_placeholder'] : 'Nhập số lượng xuất';
            var maxLabel = (window.__MESSAGES__ && window.__MESSAGES__['export_quantity_max_label']) ? window.__MESSAGES__['export_quantity_max_label'] : 'Tối đa';
            quantityField.placeholder = placeholderText + ' (' + maxLabel + ': ' + docData.quantity + ')';
        }
        
        // Clear form
        var form = document.getElementById('export-form');
        if (form) {
            form.reset();
        }
        
        // Reset custom select for recipient
        try {
            var recipientCustom = document.getElementById('export-recipient-custom-select');
            if (recipientCustom) {
                var recipientBtn = recipientCustom.querySelector('.custom-select-toggle');
                var recipientHidden = document.getElementById('export-recipient-id');
                if (recipientBtn) {
                    var ph = recipientBtn.getAttribute('data-placeholder') || 'Chọn người nhận';
                    recipientBtn.textContent = ph;
                }
                if (recipientHidden) { recipientHidden.value = ''; }
                recipientCustom.classList.remove('open');
            }
        } catch(_) {}
        
        // Show modal with same style as incoming modal
        modal.classList.add('show');
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-hidden', 'false');
        modal.style.display = 'flex';
        modal.style.zIndex = '100000';
        
        // Focus first input
        setTimeout(function() {
            if (quantityField) {
                quantityField.focus();
            }
        }, 100);
    }
    
    // Function to close export modal
    function closeExportModal() {
        var modal = document.getElementById('export-modal');
        if (modal) {
            // Blur any focused element inside modal to prevent aria-hidden warning
            var activeElement = document.activeElement;
            if (activeElement && modal.contains(activeElement)) {
                try { activeElement.blur(); } catch(_) {}
            }
            
            // Close modal immediately
            modal.classList.remove('show');
            modal.setAttribute('aria-hidden', 'true');
            modal.style.display = 'none';
        }
    }

    // Function to view document from file path
    function viewDocumentFromFile(filePath) {
        if (!filePath || !filePath.trim()) {
            return;
        }
        
        // Check if main modal is visible
        var mainModal = document.querySelector('.modal.show');
        // Open PDF viewer with file path
        openPdfModal(filePath);
    }

    // Function to toggle view button visibility
    function toggleViewButton() {
        var fileInput = document.getElementById('doc-file');
        var viewBtn = document.getElementById('view-pdf-btn');
        
        if (fileInput && viewBtn) {
            if (fileInput.value && fileInput.value.trim()) {
                viewBtn.style.display = 'flex';
            } else {
                viewBtn.style.display = 'none';
            }
        }
    }

    // Function to reset upload button to default state
    function resetUploadButton() {
        var uploadBtn = document.getElementById('upload-pdf-btn');
        if (uploadBtn) {
            uploadBtn.innerHTML = '<svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: currentColor;"><path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/><path d="M12,15L15,12H13V8H11V12H9L12,15Z"/></svg>';
            uploadBtn.style.background = '';
            uploadBtn.style.transform = '';
            uploadBtn.style.color = '';
            uploadBtn.style.width = '32px';
            uploadBtn.style.height = '32px';
            uploadBtn.disabled = false;
            uploadBtn.classList.remove('success', 'error');
        }
    }

    // Function to set upload button loading state
    function setUploadButtonLoading() {
        var uploadBtn = document.getElementById('upload-pdf-btn');
        if (uploadBtn) {
            uploadBtn.innerHTML = '<svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #ffffff;"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>';
            uploadBtn.disabled = true;
            uploadBtn.classList.remove('success', 'error');
        }
    }

    // Function to set upload button success state
    function setUploadButtonSuccess() {
        var uploadBtn = document.getElementById('upload-pdf-btn');
        if (uploadBtn) {
            uploadBtn.innerHTML = '<svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #ffffff;"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>';
            uploadBtn.classList.add('success');
            uploadBtn.classList.remove('error');
            uploadBtn.disabled = false;
        }
    }

    // Function to set upload button error state
    function setUploadButtonError() {
        var uploadBtn = document.getElementById('upload-pdf-btn');
        if (uploadBtn) {
            uploadBtn.innerHTML = '<svg viewBox="0 0 24 24" style="width: 20px; height: 20px; fill: #ffffff;"><path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/><path d="M12,15L15,12H13V8H11V12H9L12,15Z"/></svg>';
            uploadBtn.classList.add('error');
            uploadBtn.classList.remove('success');
            uploadBtn.disabled = false;
        }
    }

    // Test function to manually show view button
    function testViewButton() {
        var fileInput = document.getElementById('doc-file');
        var viewBtn = document.getElementById('view-pdf-btn');
        
        if (fileInput && viewBtn) {
            fileInput.value = 'data\\File\\Document\\test.pdf';
            viewBtn.style.display = 'flex';
        }
    }

    // Make test function available globally
    window.testViewButton = testViewButton;

    // Function to edit document
    function editDocument(docId) {
        if (!docId) {
            return;
        }
        
        // Find the document data from the table
        var editButton = document.querySelector('[data-incoming-edit="' + docId + '"]');
        if (!editButton) {
            return;
        }
        
        var row = editButton.closest('tr');
        if (!row) {
            return;
        }
        
        var cells = row.querySelectorAll('td');
        if (cells.length < 5) {
            return;
        }
        
        // Extract data from table row
        var symbol = cells[1].textContent.trim();
        var title = cells[2].textContent.trim();
        var issuer = cells[3].textContent.trim();
        var effectiveDate = cells[4].textContent.trim();
        
        // Get additional data from data attributes
        var rowData = row.getAttribute('data-document');
        var docData = rowData ? JSON.parse(rowData) : {};
        
        
        // Convert date from dd/mm/yyyy to yyyy-mm-dd
        var dateParts = effectiveDate.split('/');
        var formattedDate = '';
        if (dateParts.length === 3) {
            formattedDate = dateParts[2] + '-' + dateParts[1].padStart(2, '0') + '-' + dateParts[0].padStart(2, '0');
        }
        
        // Set update mode
        setUpdate(docId);
        
        // Set form data
        var docIdField = document.getElementById('doc-id');
        var docSymbolField = document.getElementById('doc-symbol');
        var docTitleField = document.getElementById('doc-title');
        var docIssuerField = document.getElementById('doc-issuer');
        var docDateField = document.getElementById('doc-effective');
        var docCodeField = document.getElementById('doc-code');
        var docSummaryField = document.getElementById('doc-summary');
        var docCategoryField = document.getElementById('doc-category-id');
        var docTypeField = document.getElementById('doc-type-id');
        var docPageTypeField = document.getElementById('doc-typedoc-id');
        var docQuantityField = document.getElementById('doc-quantity');
        var docExpirationField = document.getElementById('doc-expiry');
        var docCompanyField = document.getElementById('doc-company-id');
        var docStorageField = document.getElementById('file-storage');
        var docNotesField = document.getElementById('doc-notes');
        var docFileField = document.getElementById('doc-file');
        // Ensure hidden document-id (used for upload naming) reflects current editing ID
        try {
            var hiddenUploadId = document.getElementById('document-id');
            if (hiddenUploadId) { hiddenUploadId.value = String(docId); }
            // Provide a getter for other parts if needed
            window.getCurrentDocumentId = function(){ return String(docId); };
        } catch(_) {}
        
        console.log('Form fields found:', {
            docId: !!docIdField,
            symbol: !!docSymbolField,
            title: !!docTitleField,
            issuer: !!docIssuerField,
            date: !!docDateField,
            code: !!docCodeField,
            summary: !!docSummaryField,
            category: !!docCategoryField,
            type: !!docTypeField,
            pageType: !!docPageTypeField,
            quantity: !!docQuantityField,
            expiration: !!docExpirationField,
            company: !!docCompanyField,
            storage: !!docStorageField,
            notes: !!docNotesField,
            fileUrl: !!docFileField
        });
        
        if (docIdField) docIdField.value = docId;
        if (docSymbolField) docSymbolField.value = symbol;
        if (docTitleField) docTitleField.value = title;
        if (docIssuerField) docIssuerField.value = issuer;
        if (docDateField) docDateField.value = formattedDate;
        if (docCodeField) {
            docCodeField.value = docId; // Set current document ID
            docCodeField.setAttribute('readonly', true); // Keep readonly to prevent editing
            docCodeField.style.color = '#7adcc9';
            docCodeField.style.fontWeight = 'bold';
        }
        
        // Set additional fields from docData
        if (docSummaryField) docSummaryField.value = docData.summary || '';
        if (docQuantityField) docQuantityField.value = docData.quantity || '';
        if (docStorageField) docStorageField.value = docData.storage_location || '';
        if (docNotesField) docNotesField.value = docData.notes || '';
        if (docFileField) docFileField.value = docData.file_url || '';
        
        // Toggle view button based on file URL
        toggleViewButton();
        
        // Force show view button if file URL exists
        var fileInput = document.getElementById('doc-file');
        var viewBtn = document.getElementById('view-pdf-btn');
        if (fileInput && viewBtn && fileInput.value && fileInput.value.trim()) {
            viewBtn.style.display = 'flex';
        }
        
        // Set expiration date
        if (docExpirationField && docData.expiration_date) {
            var expDateParts = docData.expiration_date.split('/');
            if (expDateParts.length === 3) {
                var expFormattedDate = expDateParts[2] + '-' + expDateParts[1].padStart(2, '0') + '-' + expDateParts[0].padStart(2, '0');
                docExpirationField.value = expFormattedDate;
            }
        }
        
        // Set dropdowns (custom select)
        if (docCategoryField && docData.id_category) {
            docCategoryField.value = docData.id_category;
            // Update custom select display
            var categorySelect = document.getElementById('category-custom-select');
            if (categorySelect) {
                var option = categorySelect.querySelector(`[data-value="${docData.id_category}"]`);
                if (option) {
                    var toggle = categorySelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        if (docTypeField && docData.doctype) {
            docTypeField.value = docData.doctype;
            // Update custom select display
            var typeSelect = document.getElementById('doctype-custom-select');
            if (typeSelect) {
                var option = typeSelect.querySelector(`[data-value="${docData.doctype}"]`);
                if (option) {
                    var toggle = typeSelect.querySelector('.custom-select-toggle');
                    if (toggle) {
                        toggle.textContent = option.textContent;
                    }
                }
            }
        }
        if (docPageTypeField && docData.typedoc) {
            docPageTypeField.value = docData.typedoc;
            // Update custom select display
            var pageTypeSelect = document.getElementById('docpagetype-custom-select');
            if (pageTypeSelect) {
                var option = pageTypeSelect.querySelector(`[data-value="${docData.typedoc}"]`);
                if (option) {
                    var toggle = pageTypeSelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        if (docCompanyField && docData.id_company) {
            docCompanyField.value = docData.id_company;
            // Update custom select display
            var companySelect = document.getElementById('company-custom-select');
            if (companySelect) {
                var option = companySelect.querySelector(`[data-value="${docData.id_company}"]`);
                if (option) {
                    var toggle = companySelect.querySelector('.custom-select-toggle');
                    if (toggle) toggle.textContent = option.textContent;
                }
            }
        }
        
        // Reset upload button to default state
        resetUploadButton();
        
        // Toggle view button based on file URL
        toggleViewButton();
        
        // Fix modal state before opening
        var modal = document.getElementById('incoming-modal');
        if (modal) {
            modal.removeAttribute('aria-hidden');
            modal.setAttribute('aria-hidden', 'false');
            modal.removeAttribute('aria-hidden');
            modal.classList.add('show');
            modal.style.display = 'flex';
            modal.style.zIndex = '100000';
        }
        
        // Open modal
        openModal();
    }

    // Function to delete document
    function deleteDocument(docId) {
        if (!docId) return;
        
        // Find the document data from the table
        var row = document.querySelector('[data-incoming-delete="' + docId + '"]').closest('tr');
        if (!row) return;
        
        var cells = row.querySelectorAll('td');
        if (cells.length < 2) return;
        
        var title = cells[2].textContent.trim();
        
        // Show confirmation dialog
        var confirmMessage = 'Bạn có chắc chắn muốn xóa công văn "' + title + '" không?';
        if (!confirm(confirmMessage)) return;
        
        // Send delete request
        fetch('modules/incoming_service.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'fetch'
            },
            body: 'action=delete&id=' + encodeURIComponent(docId)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Remove row from table
                row.remove();
                
                // Show success message
                var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                var successWithHeader = '<div class="success-header">' + successTitle + '</div>' + (data.message || 'Xóa công văn thành công');
                if (window.showToast) { window.showToast('success', successWithHeader); }
                
                // Reload page to refresh pagination
                setTimeout(function() {
                    safeReload();
                }, 1000);
            } else {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + (data.message || 'Không thể xóa công văn');
                if (window.showToast) { window.showToast('error', errorWithHeader); }
            }
        })
        .catch(error => {
            var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
            var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + 'Lỗi khi xóa công văn';
            if (window.showToast) { window.showToast('error', errorWithHeader); }
        });
    }

    // Function to view document
    function viewDocument(docId) {
        if (!docId) return;
        
        // Get file URL from server
        fetch('modules/incoming_service.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-Requested-With': 'fetch'
            },
            body: 'action=get_file_url&id=' + encodeURIComponent(docId)
        })
        .then(response => response.json())
        .then(data => {
            if ((data.success || data.ok) && data.file_url) {
                // Stream PDF inline through server endpoint to avoid download prompts
                // Append dummy query to avoid IDM caching/intercepting
                // Pass RAW file path to modal; modal will request base64 via pdf_data.php
                openPdfModal(data.file_url);
            } else {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + (data.message || 'Không thể mở file');
                if (window.showToast) { window.showToast('error', errorWithHeader); }
            }
        })
        .catch(error => {
            var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
            var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + 'Lỗi khi tải file';
            if (window.showToast) { window.showToast('error', errorWithHeader); }
        });
    }

    // Function to open PDF modal
    function openPdfModal(fileUrl) {
        // Check if mobile first
        var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth <= 768;
        
        // On mobile, directly open PDF in new tab - no modal needed
        if (isMobile) {
            var pdfUrl = 'modules/pdf_viewer.php?file=' + encodeURIComponent(fileUrl) + '#toolbar=1&navpanes=1&scrollbar=1';
            window.open(pdfUrl, '_blank');
            return; // Exit early, no modal needed
        }
        
        // Desktop only: Create modal for PDF preview
        // Save current modal state before opening PDF modal
        var currentModal = document.querySelector('.modal.show');
        if (currentModal) {
            window.currentModalState = {
                element: currentModal,
                display: currentModal.style.display,
                zIndex: currentModal.style.zIndex,
                classList: currentModal.classList.toString()
            };
        }
        
        // Create modal if it doesn't exist
        var existingModal = document.getElementById('pdf-viewer-modal');
        if (existingModal) {
            existingModal.remove();
        }

        var modal = document.createElement('div');
        modal.id = 'pdf-viewer-modal';
        modal.className = 'modal-overlay';
        
        // Desktop only - show PDF in iframe
        modal.innerHTML = `
            <div class="modal-content pdf-modal">
                <button type="button" class="modal-close" data-modal-close title="${window.getTooltipText ? window.getTooltipText('close') : 'Đóng'}">×</button>
                <div class="modal-body pdf-container" style="padding:0;height:100%;overflow:hidden;background:#3C3C3C;position:relative;">
                    <iframe id="pdf-iframe" src="" type="application/pdf" style="width:100%;height:100%;border:none;background:#3C3C3C;"></iframe>
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        var contentEl = modal.querySelector('.modal-content');
        
        // Ensure modal is visible
        modal.style.display = 'flex';

        // Add event listeners for close buttons
        var closeButtons = modal.querySelectorAll('[data-modal-close]');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                closePdfModal();
            });
        });

        // Close modal when clicking outside
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closePdfModal();
            }
        });
        
        // Close modal with Escape key
        var escapeHandler = function(e) {
            if (e.key === 'Escape') {
                closePdfModal();
                document.removeEventListener('keydown', escapeHandler);
            }
        };
        document.addEventListener('keydown', escapeHandler);
        
        // Function to close PDF modal properly
        function closePdfModal() {
            // Remove PDF modal
            modal.remove();

            // Only restore a previously open modal if there actually was one
            var saved = window.currentModalState;
            if (saved && saved.element) {
                try {
                    var el = saved.element;
                    el.style.display = saved.display || 'flex';
                    el.style.zIndex = saved.zIndex || '100000';
                    el.classList.add('show');
                    el.removeAttribute('aria-hidden');
                    el.setAttribute('aria-hidden', 'false');
                    // Re-attach listeners if it's the incoming modal
                    if (el.id === 'incoming-modal') {
                        reattachModalEventListeners(el);
                    }
                } catch (_) {}
            }

            // Clear saved state
            window.currentModalState = null;
        }
        
        // Function to re-attach event listeners for modal
        function reattachModalEventListeners(modalElement) {
            if (!modalElement) return;

            
            // Fix modal state
            modalElement.style.display = 'flex';
            modalElement.style.zIndex = '100000';
            modalElement.classList.add('show');
            modalElement.removeAttribute('aria-hidden');
            modalElement.setAttribute('aria-hidden', 'false');
            modalElement.removeAttribute('aria-hidden');
            
            // Re-attach close button listeners
            var closeButtons = modalElement.querySelectorAll('[data-modal-close]');
            closeButtons.forEach(btn => {
                // Remove existing listeners first
                btn.replaceWith(btn.cloneNode(true));
                // Add new listener
                btn.addEventListener('click', function() {
                    closeModal();
                });
            });
            
            // Re-attach cancel button listeners
            var cancelButtons = modalElement.querySelectorAll('button[type="button"]');
            cancelButtons.forEach(btn => {
                if (btn.textContent.includes('Hủy') || btn.textContent.includes('Cancel')) {
                    // Remove existing listeners first
                    btn.replaceWith(btn.cloneNode(true));
                    // Add new listener
                    btn.addEventListener('click', function() {
                        closeModal();
                    });
                }
            });
            
            // Re-attach form submit listener
            var form = modalElement.querySelector('form');
            if (form) {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    // Let the existing form handler take care of it
                });
            }
            
            // Re-attach input change listeners
            var fileInput = modalElement.querySelector('#doc-file');
            if (fileInput) {
                fileInput.addEventListener('input', function() {
                    toggleViewButton();
                });
                fileInput.addEventListener('change', function() {
                    toggleViewButton();
                });
            }
            
            // Re-attach upload button listeners
            var uploadBtn = modalElement.querySelector('#upload-pdf-btn');
            if (uploadBtn) {
                uploadBtn.addEventListener('click', function() {
                    var fileInput = modalElement.querySelector('#pdf-file-input');
                    if (fileInput) {
                        fileInput.click();
                    }
                });
            }
            
            // Re-attach view button listeners
            var viewBtn = modalElement.querySelector('#view-pdf-btn');
            if (viewBtn) {
                viewBtn.addEventListener('click', function() {
                    var fileInput = modalElement.querySelector('#doc-file');
                    if (fileInput && fileInput.value.trim()) {
                        viewDocumentFromFile(fileInput.value);
                    }
                });
            }
            
        }
        
        // Function to re-initialize modal functionality
        function reinitializeModalFunctionality() {
            // Find and fix the main modal
            var mainModal = document.querySelector('#incoming-modal');
            if (mainModal) {
                mainModal.style.display = 'flex';
                mainModal.style.zIndex = '100000';
                mainModal.classList.add('show');
                mainModal.removeAttribute('aria-hidden');
                mainModal.setAttribute('aria-hidden', 'false');
                mainModal.removeAttribute('aria-hidden');
                
                // Re-attach event listeners
                reattachModalEventListeners(mainModal);
            }
        }

        // Load PDF in iframe (Desktop only)
        try {
            // Construct full URL for PDF with toolbar enabled
            var pdfUrl = 'modules/pdf_viewer.php?file=' + encodeURIComponent(fileUrl) + '#toolbar=1&navpanes=1&scrollbar=1';
            
            var iframeEl = modal.querySelector('#pdf-iframe');
            if (iframeEl) {
                // Set source - browser will handle PDF rendering with toolbar
                iframeEl.src = pdfUrl;
                
                // Handle load error
                iframeEl.onerror = function() {
                    alert('Không thể tải PDF. Vui lòng thử lại.');
                    closePdfModal();
                };
            }
        } catch (error) {
            console.error('Error loading PDF:', error);
            alert('Không thể tải PDF');
        }
    }

    var form = document.getElementById('incoming-form');
    if (!form) return;

    // Custom select (company) - portal to body
    (function(){
        var custom = document.getElementById('company-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('doc-company-id') || document.getElementById('doc-company-select') || document.getElementById('doc-company-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Custom select (category) - portal to body
    (function(){
        var custom = document.getElementById('category-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('doc-category-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Custom select (doctype) - portal to body
    (function(){
        var custom = document.getElementById('doctype-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('doc-type-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Custom select (docpagetype) - portal to body
    (function(){
        var custom = document.getElementById('docpagetype-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('doc-typedoc-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || '--';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Custom select (export recipient) - portal to body (same pattern as docpagetype)
    (function(){
        var custom = document.getElementById('export-recipient-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('export-recipient-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || 'Chọn người nhận';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Custom select (import sender) - portal to body (same pattern as export recipient)
    (function(){
        var custom = document.getElementById('import-sender-custom-select');
        if (!custom) return;
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('import-sender-id');
        if (!toggle || !menu) return;
        var placeholder = toggle.getAttribute('data-placeholder') || 'Chọn người gửi';
        var closeOnScroll = null; var closeOnResize = null;

        var anchorParent = null; var anchorNext = null; var isPortaled = false;
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { anchorParent.insertBefore(menu, anchorNext); }
                else { anchorParent.appendChild(menu); }
            }
            isPortaled = false;
        }
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var maxH = 260;
            var left = Math.round(r.left);
            var width = Math.round(r.width);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + width + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - width - pad);
            }
            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.top = Math.round(r.bottom + 6) + 'px';
            menu.style.width = width + 'px';
            menu.style.minWidth = width + 'px';
            menu.style.maxWidth = width + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
        }
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { window.removeEventListener('scroll', closeOnScroll, true); closeOnScroll = null; }
            if (closeOnResize) { window.removeEventListener('resize', closeOnResize); closeOnResize = null; }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                closeOnScroll = function(ev){ if (menu.contains(ev.target)) return; closeAll(); };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var id = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            if (hidden) hidden.value = id;
            toggle.textContent = label || placeholder;
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ it.classList.toggle('is-selected', it === opt); });
            closeAll();
        });
        document.addEventListener('click', closeAll);
    })();

    // Handle PDF upload
    var uploadBtn = document.getElementById('upload-pdf-btn');
    var fileInput = document.getElementById('pdf-file-input');
    var tempFileName = null;

    if (uploadBtn && fileInput) {
        uploadBtn.addEventListener('click', function() {
            fileInput.click();
        });

        fileInput.addEventListener('change', function(e) {
            var file = e.target.files[0];
            if (!file) return;

            // Validate file type
            if (file.type !== 'application/pdf') {
                var msgOnlyPdf = (window.__MESSAGES__ && window.__MESSAGES__['incoming_form_upload_pdf']) ? window.__MESSAGES__['incoming_form_upload_pdf'] : 'Chỉ cho phép tệp PDF';
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var msgWithHeader = '<div class="error-header">' + errorTitle + '</div>' + msgOnlyPdf;
                if (window.showToast) { window.showToast('error', msgWithHeader); } else { alert(msgOnlyPdf); }
                return;
            }

            // Validate file size (50MB max)
            if (file.size > 50 * 1024 * 1024) {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var limitText = (window.__MESSAGES__ && window.__MESSAGES__['incoming_max_size']) ? window.__MESSAGES__['incoming_max_size'] : 'Kích thước file quá lớn. Tối đa 50MB';
                var msg = '<div class="error-header">' + errorTitle + '</div>' + limitText;
                if (window.showToast) { window.showToast('error', msg); } else { alert('Kích thước file quá lớn. Tối đa 50MB'); }
                return;
            }

            // Get document ID for file naming
            var documentIdInput = document.getElementById('document-id');
            var documentId = (documentIdInput && documentIdInput.value) ? documentIdInput.value : '';
            if (!documentId && typeof getCurrentDocumentId === 'function') {
                try { documentId = String(getCurrentDocumentId()); } catch(_) {}
            }
            if (!documentId) { documentId = '1'; }
            var finalFileName = documentId + '.pdf';

            // Upload file with new naming
            var formData = new FormData();
            formData.append('pdf_file', file);
            formData.append('document_id', documentId);
            formData.append('final_name', finalFileName);

            setUploadButtonLoading();

            fetch('modules/incoming/upload_standalone.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                // Check if response is JSON
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    return response.text().then(text => {
                        throw new Error('Server returned non-JSON response: ' + text);
                    });
                }
                
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    tempFileName = data.temp_file;
                    setUploadButtonSuccess();
                    
                    // Update file URL field with final path from server
                    var fileUrlField = document.getElementById('doc-file');
                    if (fileUrlField) {
                        var finalPath = data.final_path || ('data\\File\\Document\\' + finalFileName);
                        fileUrlField.value = finalPath.replace(/\\\\/g,'/');
                    }
                    
                    // Toggle view button after successful upload
                    toggleViewButton();
                } else {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorMsg = '<div class="error-header">' + errorTitle + '</div>Upload thất bại: ' + (data.message || '');
                    if (window.showToast) { window.showToast('error', errorMsg); } else { alert('Upload thất bại: ' + (data.message || '')); }
                    setUploadButtonError();
                }
            })
            .catch(error => {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorMsg = '<div class="error-header">' + errorTitle + '</div>Lỗi upload file';
                if (window.showToast) { window.showToast('error', errorMsg); } else { alert('Lỗi upload file'); }
                setUploadButtonError();
            });
        });
    }

    form.addEventListener('submit', function(e){
        e.preventDefault();
        var submitBtnEl = document.getElementById('incoming-submit');
        if (submitBtnEl) { submitBtnEl.disabled = true; }

        try {
            var licInput = document.getElementById('incoming-license');
            if (licInput && licInput.value) { /* ok */ } else if (licInput) { licInput.value = licInput.value || ''; }
        } catch(_) {}

        var data = new FormData(form);
        if (!data.has('license')) {
            var licEl = document.getElementById('incoming-license');
            data.append('license', (licEl && licEl.value) ? licEl.value : '');
        }
        
        // Add temp file if uploaded
        if (tempFileName) {
            data.append('temp_file', tempFileName);
        }
        var postUrl = form.getAttribute('action') || form.action;
        fetch(postUrl, { method: 'POST', headers: { 'X-Requested-With': 'fetch', 'Accept': 'application/json' }, body: data })
            .then(function(r){ return r.text(); })
            .then(function(text){
                var json = null;
                try { json = text ? JSON.parse(text) : null; } catch(_) {}
                if (!json) {
                    if (window.showToast) { 
                        const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                        window.showToast('error', '<div class="error-header">' + errorTitle + '</div>Network error'); 
                    }
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                    return;
                }
                if (json && json.ok) {
                    closeModal();
                    // Mark body as reloading and hide all elements immediately
                    document.body.classList.add('reloading');
                    var elementsToHide = document.querySelectorAll('.modal-backdrop, .modal-overlay, .user-actions-dropdown, .page-loader');
                    elementsToHide.forEach(function(el) {
                        el.style.display = 'none';
                        el.style.visibility = 'hidden';
                        el.style.opacity = '0';
                        el.classList.remove('show');
                    });
                    // Force reflow to ensure styles are applied
                    void document.body.offsetHeight;
                    // Add critical CSS to prevent flash
                    var style = document.createElement('style');
                    style.id = 'reload-prevent-flash';
                    style.textContent = '* { transition: none !important; animation: none !important; } .page-loader, .modal-backdrop, .modal-overlay { display: none !important; visibility: hidden !important; opacity: 0 !important; }';
                    document.head.appendChild(style);
                    // Use requestAnimationFrame to ensure DOM is updated before reload
                    var msg = encodeURIComponent(json.message || '');
                    requestAnimationFrame(function() {
                        requestAnimationFrame(function() {
                            location.href = 'index.php?incoming=1&success=' + msg;
                        });
                    });
                } else {
                    var err = (json && json.message) ? String(json.message) : 'Error';
                    err = err.replace(/\n/g, '<br>');
                    
                    // Add error header
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + err;
                    
                    if (window.showToast) { window.showToast('error', errorWithHeader); }
                    if (submitBtnEl) { submitBtnEl.disabled = false; }
                }
            })
            .catch(function(){ 
                if (window.showToast) { 
                    const errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    window.showToast('error', '<div class="error-header">' + errorTitle + '</div>Network error'); 
                } 
                if (submitBtnEl) { submitBtnEl.disabled = false; } 
            });
    });
    
    // ============ IMPORT FUNCTIONS ============
    
    // Function to increment import quantity
    window.incrementImportQuantity = function() {
        var input = document.getElementById('import-quantity');
        if (input) {
            var currentValue = parseInt(input.value) || 0;
            input.value = currentValue + 1;
            input.dispatchEvent(new Event('input', { bubbles: true }));
        }
    };
    
    // Function to decrement import quantity
    window.decrementImportQuantity = function() {
        var input = document.getElementById('import-quantity');
        if (input) {
            var currentValue = parseInt(input.value) || 0;
            var minValue = parseInt(input.getAttribute('min')) || 1;
            if (currentValue > minValue) {
                input.value = currentValue - 1;
                input.dispatchEvent(new Event('input', { bubbles: true }));
            }
        }
    };
    
    // Function to open import modal
    function importDocument(docId) {
        if (!docId) {
            return;
        }
        
        // Find the document data from the table
        var importButton = document.querySelector('[data-incoming-import="' + docId + '"]');
        if (!importButton) {
            return;
        }
        
        var row = importButton.closest('tr');
        if (!row) {
            return;
        }
        
        // Get document data from data attributes
        var rowData = row.getAttribute('data-document');
        var docData = rowData ? JSON.parse(rowData) : {};
        
        // Open import modal
        openImportModal(docId, docData);
    }
    
    // Function to open import modal
    function openImportModal(docId, docData) {
        var modal = document.getElementById('import-modal');
        if (!modal) {
            console.error('Import modal not found');
            return;
        }
        
        // Set document ID
        var docIdField = document.getElementById('import-doc-id');
        if (docIdField) {
            docIdField.value = docId;
        }
        
        // Clear form
        var form = document.getElementById('import-form');
        if (form) {
            form.reset();
        }
        
        // Reset custom select for sender
        try {
            var senderCustom = document.getElementById('import-sender-custom-select');
            if (senderCustom) {
                var senderBtn = senderCustom.querySelector('.custom-select-toggle');
                var senderHidden = document.getElementById('import-sender-id');
                if (senderBtn) {
                    var ph = senderBtn.getAttribute('data-placeholder') || 'Chọn người gửi';
                    senderBtn.textContent = ph;
                }
                if (senderHidden) { senderHidden.value = ''; }
                senderCustom.classList.remove('open');
            }
        } catch(_) {}
        
        // Show modal
        modal.classList.add('show');
        modal.removeAttribute('aria-hidden');
        modal.setAttribute('aria-hidden', 'false');
        modal.style.display = 'flex';
        modal.style.zIndex = '100000';
        
        // Focus first input
        var quantityField = document.getElementById('import-quantity');
        setTimeout(function() {
            if (quantityField) {
                quantityField.focus();
            }
        }, 100);
    }
    
    // Function to close import modal
    function closeImportModal() {
        var modal = document.getElementById('import-modal');
        if (modal) {
            // Blur any focused element inside modal
            var activeElement = document.activeElement;
            if (activeElement && modal.contains(activeElement)) {
                try { activeElement.blur(); } catch(_) {}
            }
            
            // Close modal immediately
            modal.classList.remove('show');
            modal.setAttribute('aria-hidden', 'true');
            modal.style.display = 'none';
        }
    }
    
    // Handle import button click
    document.addEventListener('click', function(e) {
        var importBtn = e.target.closest('[data-incoming-import]');
        if (importBtn) {
            var docId = importBtn.getAttribute('data-incoming-import');
            importDocument(docId);
            return;
        }
        
        // Handle import modal close
        var isImportModal = !!e.target.closest('#import-modal');
        if (isImportModal && e.target.closest('[data-modal-close]')) {
            closeImportModal();
        }
    });
    
    // Handle import form submission
    document.addEventListener('submit', function(e) {
        if (e.target && e.target.id === 'import-form') {
            e.preventDefault();
            
            var docId = document.getElementById('import-doc-id').value;
            var quantity = document.getElementById('import-quantity').value;
            var sender = document.getElementById('import-sender-id').value;
            var reason = document.getElementById('import-reason').value;
            
            var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
            
            if (!docId || !quantity || !sender || !reason) {
                var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['import_validation_missing_data']) ? window.__MESSAGES__['import_validation_missing_data'] : 'Vui lòng điền đầy đủ thông tin';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                if (window.showToast) {
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(errorMsg);
                }
                return;
            }
            
            // Process import
            processImport(docId, quantity, sender, reason);
        }
    });
    
    // Function to process import
    function processImport(docId, quantity, sender, reason) {
        var formData = new FormData();
        formData.append('action', 'import');
        formData.append('document_id', docId);
        formData.append('import_quantity', quantity);
        formData.append('import_sender', sender);
        formData.append('import_reason', reason);
        
        // Get license from import modal
        var licenseField = document.getElementById('import-license');
        if (licenseField) {
            formData.append('license', licenseField.value);
        }
        
        fetch('modules/incoming_service.php', {
            method: 'POST',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            body: formData
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('HTTP error ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            if (data.ok) {
                // Close modal
                closeImportModal();
                
                // Show success message
                if (window.showToast) {
                    var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÀNH CÔNG';
                    var successWithHeader = '<div class="success-header">' + successTitle + '</div>' + data.message;
                    window.showToast('success', successWithHeader);
                } else {
                    alert(data.message);
                }
                
                // Reload page after short delay
                setTimeout(function() {
                    safeReload();
                }, 1500);
            } else {
                // Keep modal open, show error
                if (window.showToast) {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'LỖI';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + data.message;
                    window.showToast('error', errorWithHeader);
                } else {
                    alert(data.message);
                }
            }
        })
        .catch(function(error) {
            // Keep modal open on error
            if (window.showToast) {
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'LỖI';
                var errorMsg = 'Có lỗi xảy ra khi nhập file';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                window.showToast('error', errorWithHeader);
            } else {
                alert('Có lỗi xảy ra khi nhập file');
            }
        });
    }
    
    // Handle ESC key for import modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            var importModal = document.getElementById('import-modal');
            if (importModal && importModal.style.display === 'flex') {
                closeImportModal();
            }
        }
    });
});


