document.addEventListener('DOMContentLoaded', function() {
    const cartTable = document.getElementById('cartItems-table');

    if (cartTable) {
        cartTable.addEventListener('click', function(event) {
            const target = event.target;
            const row = target.closest('tr');
            if (!row) return;
            const itemId = row.getAttribute('data-item-id');
            const quantitySpan = row.querySelector('.total_quantity');
            const unitPriceElement = row.querySelector('.unit-price');
            const totalPriceElement = row.querySelector('.total-price');

            let quantity = parseInt(quantitySpan.textContent, 10);
            const unitPrice = parseFloat(unitPriceElement.textContent);

            if (target.classList.contains('quantity-minus')) {
                if (quantity > 1) {
                    quantity--;
                    quantitySpan.textContent = quantity;
                    totalPriceElement.textContent = (unitPrice * quantity).toFixed(2);
                    updateCartItem(itemId, quantity);
                }
            } else if (target.classList.contains('quantity-plus')) {
                quantity++;
                quantitySpan.textContent = quantity;
                totalPriceElement.textContent = (unitPrice * quantity).toFixed(2);
                updateCartItem(itemId, quantity);
            } else if (target.classList.contains('delete-item')) {
                if (confirm('你确定删除此商品吗?')) {
                    // row.parentNode.removeChild(row);
                    deleteCartItem(itemId, row);
                }
            }
        });

        function updateCartItem(itemId, quantity) {
            const data = {
                action: 'update_order',
                itemId: itemId,
                quantity: quantity
            };

            fetch('index.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (!result.success) {
                    alert('更新数量失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
            });
        }

        function deleteCartItem(itemId, row) {
            const data = {
                action: 'delete_item',
                itemId: itemId
            };

            fetch('index.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    // Remove the row from the DOM after successful deletion
                    row.parentNode.removeChild(row);

                    // Optionally, check if the cart is empty and display a message
                    if (cartTable.querySelector('tbody').children.length === 0) {
                        cartTable.parentNode.innerHTML = '<p>没有采购商品.</p>';
                    }
                } else {
                    alert('删除商品失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('错误:', error);
            });
        }

        // Handle confirm order button
        const confirmOrderButton = document.getElementById('confirm-order-btn');
        if (confirmOrderButton) {
            confirmOrderButton.addEventListener('click', function() {
                const data = {
                    action: 'confirm_order'
                };

                fetch('index.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        alert('已确认订单');
                        window.location.href = 'index.php?view=order';
                    } else {
                        alert('确认订单失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                });
            });
        }
    }
});