document.addEventListener('DOMContentLoaded', function() {
    // Immediately Invoked Function Expression (IIFE) to avoid polluting the global scope
    (function() {
        const ordersTable = document.getElementById('orders-table');

        if (ordersTable) {
            // Check if we need to disable inputs based on the data attribute
            const hasUnconfirmedClearance = ordersTable.dataset.hasUnconfirmedClearance === 'true';

            if (hasUnconfirmedClearance) {
                disableOrderInputs();

                // Disable the finalize-deal button
                const finalizeDealBtn = document.getElementById('finalize-deal-btn');
                if (finalizeDealBtn) {
                    finalizeDealBtn.disabled = true;
                }

                // Gray out the orders table
                ordersTable.style.opacity = '0.5';
            }

            // Event listener for sell and return buttons
            ordersTable.addEventListener('click', function(event) {
                if (hasUnconfirmedClearance) return; // Prevent interaction if inputs are disabled

                const target = event.target;
                const row = target.closest('tr');
                if (!row) return;
                const itemId = row.getAttribute('data-item-id');

                if (target.classList.contains('sell-item-btn')) {
                    const input = row.querySelector('.sell-quantity-input');
                    const quantityToSell = input.value;
                    if (quantityToSell) {
                        sellItem(itemId, quantityToSell);
                    }
                } else if (target.classList.contains('return-item-btn')) {
                    const input = row.querySelector('.return-quantity-input');
                    const quantityToReturn = input.value;
                    if (quantityToReturn) {
                        returnItem(itemId, quantityToReturn);
                    }
                }
            });

            // Event handler for finalize-deal button
            const finalizeDealBtn = document.getElementById('finalize-deal-btn');
            if (finalizeDealBtn && !hasUnconfirmedClearance) {
                finalizeDealBtn.addEventListener('click', finalizeDeal);
            }

            // Event handler for reset-orders button
            const resetOrdersBtn = document.getElementById('reset-orders-btn');
            if (resetOrdersBtn && !hasUnconfirmedClearance) {
                resetOrdersBtn.addEventListener('click', resetOrders);
            }
        }

        function sellItem(itemId, quantityToSell) {
            fetch('index.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'sell', itemId: itemId, quantityToSell: quantityToSell })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const row = document.querySelector('tr[data-item-id="' + itemId + '"]');
                    if (row) {
                        row.querySelector('.sold').textContent = data.updatedSold;
                        row.querySelector('.stock').textContent = data.updatedStock;
                        row.querySelector('.sell-quantity-input').value = '';
                    }
                } else {
                    alert('销售商品出错: ' + data.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('销售商品出错');
            });
        }

        function returnItem(itemId, quantityToReturn) {
            fetch('index.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'return', itemId: itemId, quantityToReturn: quantityToReturn })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const row = document.querySelector('tr[data-item-id="' + itemId + '"]');
                    if (row) {
                        row.querySelector('.returned').textContent = data.updatedReturn;
                        row.querySelector('.stock').textContent = data.updatedStock;
                        row.querySelector('.return-quantity-input').value = '';
                    }
                } else {
                    alert('退返商品出错: ' + data.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('退返商品出错.');
            });
        }

        function resetOrders() {
            if (confirm('请确认重置')) {
                fetch('index.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'reset_orders' })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('重置成功.');
                        // Update the frontend accordingly
                        const orderRows = document.querySelectorAll('#orders-table tbody tr');
                        orderRows.forEach(row => {
                            row.querySelector('.sold').textContent = '0';
                            row.querySelector('.returned').textContent = '0';
                            const quantity = parseInt(row.querySelector('td:nth-child(3)').textContent, 10);
                            row.querySelector('.stock').textContent = quantity.toString();
                            // Re-enable inputs and buttons after reset
                            enableOrderInputs();
                            // Reset the table opacity
                            ordersTable.style.opacity = '1';
                            // Re-enable finalize-deal button
                            const finalizeDealBtn = document.getElementById('finalize-deal-btn');
                            if (finalizeDealBtn) {
                                finalizeDealBtn.disabled = false;
                            }
                        });
                    } else {
                        alert('重置失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('重置失败.');
                });
            }
        }

        function finalizeDeal() {
            const orderRows = Array.from(document.querySelectorAll('#orders-table tbody tr'));
            const hasSoldOrReturnedItems = orderRows.some(row =>
                parseInt(row.querySelector('.sold').textContent, 10) > 0 ||
                parseInt(row.querySelector('.returned').textContent, 10) > 0
            );

            if (!hasSoldOrReturnedItems) {
                alert('你没有销售或退返商品，不能申请结算.');
                return;
            }

            const itemIds = orderRows.map(row => row.dataset.itemId);
            fetch('index.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'finalize_deal', itemIds: itemIds })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('申请结算成功!');
                    const resetButton = document.getElementById('reset-orders-btn');
                    if (resetButton) {
                        resetButton.style.display = 'none';
                    }

                    // Disable inputs and buttons
                    disableOrderInputs();

                    // Disable finalize-deal-btn
                    const finalizeDealBtn = document.getElementById('finalize-deal-btn');
                    if (finalizeDealBtn) {
                        finalizeDealBtn.disabled = true;
                    }

                    // Gray out the orders table
                    if (ordersTable) {
                        ordersTable.style.opacity = '0.5';
                    }
                } else {
                    alert('申请结算出错: ' + data.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
                alert('申请结算出错.');
            });
        }

        function disableOrderInputs() {
            const sellInputs = document.querySelectorAll('.sell-quantity-input');
            const returnInputs = document.querySelectorAll('.return-quantity-input');
            const sellButtons = document.querySelectorAll('.sell-item-btn');
            const returnButtons = document.querySelectorAll('.return-item-btn');

            sellInputs.forEach(input => input.disabled = true);
            returnInputs.forEach(input => input.disabled = true);
            sellButtons.forEach(button => button.disabled = true);
            returnButtons.forEach(button => button.disabled = true);
        }

        function enableOrderInputs() {
            const sellInputs = document.querySelectorAll('.sell-quantity-input');
            const returnInputs = document.querySelectorAll('.return-quantity-input');
            const sellButtons = document.querySelectorAll('.sell-item-btn');
            const returnButtons = document.querySelectorAll('.return-item-btn');

            sellInputs.forEach(input => input.disabled = false);
            returnInputs.forEach(input => input.disabled = false);
            sellButtons.forEach(button => button.disabled = false);
            returnButtons.forEach(button => button.disabled = false);
        }
    })();
});