<!DOCTYPE html>
<html lang="vi">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quản lý bán hàng</title>
    <link rel="shortcut icon" href="1.png" type="image/x-icon">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.2/axios.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <style>
        input[type="number"]::-webkit-inner-spin-button,
        input[type="number"]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        @media print {
            body * {
                visibility: hidden;
            }

            #printArea,
            #printArea * {
                visibility: visible;
            }

            #printArea {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }

            .no-print {
                display: none !important;
            }
        }

        .select2-container {
            min-width: 200px !important;
        }

        .select2-dropdown {
            min-width: 300px !important;
            width: auto !important;
            max-width: 400px !important;
        }

        .select2-results__options {
            white-space: normal;
            word-wrap: break-word;
        }

        .select2-results__option {
            padding: 8px 12px !important;
            line-height: 1.4 !important;
        }

        .select2-container .select2-selection--single {
            height: 38px !important;
            border-color: rgb(209, 213, 219) !important;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 38px !important;
            font-size: 0.75rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 32px !important;
        }

        .select2-dropdown {
            border-color: rgb(209, 213, 219) !important;
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="fixed inset-0 z-50 hidden flex items-center justify-center bg-black bg-opacity-50">
        <div class="bg-white p-5 rounded-lg shadow-xl flex items-center space-x-4">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
            <span class="text-gray-700">Đang xử lý...</span>
        </div>
    </div>

    <!-- Main Container -->
    <div class="flex min-h-screen">
        <!-- Sidebar -->
        <div id="sidebar" class="w-96 bg-white shadow-lg flex flex-col h-screen sticky top-0">
            <!-- Sidebar Header -->
            <div class="p-4 border-b border-gray-200">
                <div class="flex justify-between items-center">
                    <h2 class="text-xl font-semibold flex items-center space-x-2">
                        <img src="1.png" width="30" alt="">
                        <span>Danh Mục Hàng Hóa</span>
                    </h2>
                    <button onclick="refreshProductList()"
                        class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                        <i class="fas fa-sync-alt mr-2"></i>Tải lại
                    </button>
                </div>
            </div>

            <!-- Search Box -->
            <div class="p-4 border-b border-gray-200">
                <div class="relative">
                    <input type="text" id="searchProduct"
                        class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="Tìm kiếm hàng hóa...">
                    <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
            </div>

            <!-- Filter Section -->
            <div class="p-4 border-b border-gray-200">
                <div id="productFilter" class="space-y-2">
                    <!-- Product filters will be loaded here -->
                </div>
            </div>

            <!-- Product List -->
            <div class="flex-1 overflow-y-auto p-4">
                <div id="productList" class="space-y-3">
                    <!-- Products will be loaded here -->
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-6">
            <!-- Header -->
            <div class="mb-6">
                <h1 class="text-2xl font-bold text-gray-800">Phiếu Bán Hàng</h1>
            </div>

            <!-- Form Section -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <form id="orderForm" class="space-y-4">
                    <!-- Order Info -->
                    <div class="grid grid-cols-3 gap-4">
                        <!-- Order ID and Date -->
                        <div class="space-y-2">
                            <div>
                                <label class="text-sm font-medium text-gray-700">Mã đơn hàng</label>
                                <input type="text" id="orderID" readonly
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                            </div>
                            <div>
                                <label class="text-sm font-medium text-gray-700">Ngày tạo</label>
                                <input type="datetime-local" id="orderDate" required
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                        </div>

                        <!-- Customer Info -->
                        <div class="space-y-2">
                            <div>
                                <label class="text-sm font-medium text-gray-700">Khách hàng</label>
                                <select id="customerSelect" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                    <option value="">Chọn khách hàng</option>
                                </select>
                            </div>
                            <div>
                                <label class="text-sm font-medium text-gray-700">Số điện thoại</label>
                                <input type="text" id="customerPhone" readonly
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                            </div>
                        </div>

                        <!-- Additional Info -->
                        <div class="space-y-2">
                            <div>
                                <label class="text-sm font-medium text-gray-700">Địa chỉ</label>
                                <input type="text" id="customerAddress"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg">
                            </div>
                            <div>
                                <label class="text-sm font-medium text-gray-700">Ghi chú</label>
                                <textarea id="orderNote" rows="1"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-lg resize-none"></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- Totals -->
                    <div class="grid grid-cols-4 gap-4 pt-4 border-t border-gray-200">
                        <div>
                            <label class="text-sm font-medium text-gray-700">Tổng tiền hàng</label>
                            <input type="text" id="subtotal" readonly
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">% Giảm giá</label>
                            <input type="number" id="discountPercent" value="0" min="0" max="100"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                                onchange="updateDiscountFromPercent()">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">Giảm giá</label>
                            <input type="text" id="discount" value="0"
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg"
                                onchange="handleDiscountChange(this)" oninput="formatDiscountInput(this)">
                        </div>
                        <div>
                            <label class="text-sm font-medium text-gray-700">Thành tiền</label>
                            <input type="text" id="total" readonly
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-gray-50">
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="flex justify-end space-x-2">
                        <button type="button" onclick="resetForm()"
                            class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">
                            <i class="fas fa-redo mr-2"></i>Làm mới
                        </button>
                        <button type="button" onclick="printOrder()"
                            class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600">
                            <i class="fas fa-print mr-2"></i>In đơn
                        </button>
                        <button type="button" onclick="printShippingReceipt()"
                            class="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600">
                            <i class="fas fa-shipping-fast mr-2"></i>In phiếu gửi
                        </button>
                        <button type="button" onclick="saveOrder()"
                            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
                            <i class="fas fa-save mr-2"></i>Lưu đơn
                        </button>
                    </div>
                </form>
            </div>

            <!-- Order Details -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold text-gray-800">Chi tiết đơn hàng</h2>
                    <div class="text-sm text-gray-500">
                        Số mặt hàng: <span id="itemCount" class="font-medium">0</span>
                    </div>
                </div>

                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th
                                    class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Sản phẩm</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Đơn vị</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Số lượng</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Đơn giá</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Thành tiền</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Ghi chú</th>
                                <th
                                    class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
                                    Thao tác</th>
                            </tr>
                        </thead>
                        <tbody id="orderDetails" class="bg-white divide-y divide-gray-200">
                            <!-- Order details will be loaded here -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script>
        // Configuration
        const API_CONFIG = {
            APP_ID: 'a3c21623-f7da-4dfd-bbe4-197bd67d7296',
            ACCESS_KEY: 'V2-5WcPS-sJgmv-8IXNy-QnfZ7-8sfxW-8XiP6-bZe4T-IaHdV',
            REGION: 'www',
            BASE_URL: 'https://www.appsheet.com/api/v2/apps'
        };
      
        // State Management
        let state = {
            currentOrderId: '',
            products: [],
            customers: [],
            selectedProducts: [],
            loading: false
        };
        function formatDiscountInput(input) {
            // Lấy giá trị hiện tại và xóa tất cả dấu phẩy
            let value = input.value.replace(/,/g, '');

            // Xóa tất cả ký tự không phải số
            value = value.replace(/[^\d]/g, '');

            // Format số với dấu phẩy
            if (value) {
                input.value = formatCurrency(value);
            }
        }
        function handleDiscountChange(input) {
            // Lấy giá trị số từ chuỗi đã format
            const numericValue = unformatCurrency(input.value);

            // Format lại giá trị hiển thị
            input.value = formatCurrency(numericValue);

            // Cập nhật phần trăm nếu element tồn tại
            const percentElement = document.getElementById('discountPercent');
            if (percentElement) {
                updatePercentFromDiscount();
            }

            // Cập nhật tổng
            updateTotals();
        }
        // API Service
        const apiService = {
            createAxiosInstance() {
                return axios.create({
                    baseURL: `${API_CONFIG.BASE_URL}/${API_CONFIG.APP_ID}/tables`,
                    headers: {
                        'ApplicationAccessKey': API_CONFIG.ACCESS_KEY,
                        'Content-Type': 'application/json'
                    }
                });
            },

            async request(tableName, action, data = {}, properties = {}) {
                try {
                    const api = this.createAxiosInstance();
                    const response = await api.post(`/${tableName}/Action`, {
                        Action: action,
                        Properties: properties,
                        ...data
                    });
                    return response.data;
                } catch (error) {
                    console.error('API request failed:', error);
                    throw error;
                }
            }
        };

        // Loading Management
        function showLoading() {
            document.getElementById('loadingOverlay').classList.remove('hidden');
            state.loading = true;
        }

        function hideLoading() {
            document.getElementById('loadingOverlay').classList.add('hidden');
            state.loading = false;
        }
        function updatePercentFromDiscount() {
            const percentElement = document.getElementById('discountPercent');
            if (!percentElement) return;

            const subtotal = unformatCurrency(document.getElementById('subtotal').value);
            const discountAmount = unformatCurrency(document.getElementById('discount').value) || 0;

            const discountPercent = subtotal > 0 ? Math.round((discountAmount / subtotal) * 100) : 0;
            percentElement.value = discountPercent;
        }

        function updateDiscountFromPercent() {
            const percentElement = document.getElementById('discountPercent');
            const discountElement = document.getElementById('discount');
            if (!percentElement || !discountElement) return;

            const subtotal = unformatCurrency(document.getElementById('subtotal').value);
            const discountPercent = parseFloat(percentElement.value) || 0;

            if (discountPercent < 0) percentElement.value = 0;
            if (discountPercent > 100) percentElement.value = 100;

            const discountAmount = Math.round(subtotal * (discountPercent / 100));
            discountElement.value = formatCurrency(discountAmount);

            updateTotals();
        }
        // Initialize Application
        async function initializeApp() {
            try {
                showLoading();

                // Generate new order ID
                state.currentOrderId = generateOrderId();
                document.getElementById('orderID').value = state.currentOrderId;

                // Set current date and time
                const now = new Date();
                now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
                document.getElementById('orderDate').value = now.toISOString().slice(0, 16);

                // Load initial data
                await Promise.all([
                    fetchCompanySettings(),
                    loadProducts(),
                    loadCustomers()
                ]);

                // Initialize event listeners
                setupEventListeners();

                hideLoading();
            } catch (error) {
                console.error('Error initializing app:', error);
                showToast('Lỗi khởi tạo ứng dụng', 'error');
                hideLoading();
            }
        }
        function setupEventListeners() {
            // Search product
            document.getElementById('searchProduct').addEventListener('input',
                debounce((e) => {
                    const searchTerm = e.target.value.toLowerCase();
                    const filteredProducts = state.products.filter(product =>
                        product.Tensp.toLowerCase().includes(searchTerm) ||
                        product.Masp.toLowerCase().includes(searchTerm)
                    );
                    renderProductList(filteredProducts);
                }, 300)
            );

            // Customer select change
            $('#customerSelect').on('change', function () {
                const customerId = $(this).val();
                if (customerId) {
                    const customer = state.customers.find(c => c.Makh === customerId);
                    if (customer) {
                        document.getElementById('customerPhone').value = customer.SDT || '';
                        document.getElementById('customerAddress').value = customer.Diachi || '';
                    }
                } else {
                    document.getElementById('customerPhone').value = '';
                    document.getElementById('customerAddress').value = '';
                }
            });
        }

        // Debounce function
        function debounce(func, wait) {
            let timeout;
            return function (...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, args), wait);
            };
        }
        function renderProductFilter() {
            const productFilter = document.getElementById('productFilter');
            const uniqueGroups = [...new Set(state.products.map(p => p.Nhomsp))];

            productFilter.innerHTML = `
        <label class="block text-sm font-medium text-gray-700">Lọc theo nhóm</label>
        <select id="groupFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
            <option value="">Tất cả nhóm</option>
            ${uniqueGroups.map(group => `
                <option value="${group}">${group}</option>
            `).join('')}
        </select>
    `;

            document.getElementById('groupFilter').addEventListener('change', (e) => {
                const selectedGroup = e.target.value;
                const filteredProducts = selectedGroup
                    ? state.products.filter(p => p.Nhomsp === selectedGroup)
                    : state.products;
                renderProductList(filteredProducts);
            });
        }
        function resetForm() {
            // Reset form fields
            document.getElementById('orderForm').reset();
            document.getElementById('orderDetails').innerHTML = '';
            document.getElementById('discountPercent').value = '0';
            // Generate new order ID
            state.currentOrderId = generateOrderId();
            document.getElementById('orderID').value = state.currentOrderId;
            document.getElementById('discount').value = formatCurrency(0);
            // Reset date
            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('orderDate').value = now.toISOString().slice(0, 16);

            // Reset totals
            document.getElementById('subtotal').value = formatCurrency(0);
            document.getElementById('total').value = formatCurrency(0);
            document.getElementById('itemCount').textContent = '0';

            // Reset customer select
            $('#customerSelect').val('').trigger('change');

            showToast('Đã làm mới đơn hàng', 'success');
        }
        // Load Products
        // Thêm điều kiện Selector cho API
        async function loadProducts() {
            try {
                const response = await apiService.request('DMHH', 'Find', {}, {
                    Selector: 'filter(DMHH, true)'
                });
                state.products = response;
                renderProductList(response);
                renderProductFilter();
            } catch (error) {
                console.error('Error loading products:', error);
                showToast('Lỗi tải danh sách sản phẩm', 'error');
            }
        }

        async function loadCustomers() {
            try {
                const response = await apiService.request('DSKH', 'Find', {}, {
                    Selector: 'filter(DSKH, true)'
                });
                // ... rest of the function
            } catch (error) {
                console.error('Error loading customers:', error);
                showToast('Lỗi tải danh sách khách hàng', 'error');
            }
        }

        // Load Customers
        async function loadCustomers() {
            try {
                const response = await apiService.request('DSKH', 'Find', {}, {
                    Selector: 'Filter(DSKH, true)'
                });

                state.customers = response;
                const customerSelect = $('#customerSelect');

                customerSelect.empty().append('<option value="">Chọn khách hàng</option>');

                response.forEach(customer => {
                    customerSelect.append(new Option(
                        `${customer.Tenkh} - ${customer.Makh}`,
                        customer.Makh,
                        false,
                        false,
                        {
                            customerData: customer
                        }
                    ));
                });

                // Initialize Select2
                customerSelect.select2({
                    placeholder: 'Chọn khách hàng',
                    allowClear: true,
                    width: '100%'
                });

            } catch (error) {
                console.error('Error loading customers:', error);
                throw error;
            }
        }

        // Render Product List
        function renderProductList(products) {
            const productList = document.getElementById('productList');
            productList.innerHTML = '';

            if (!products?.length) {
                productList.innerHTML = `
            <div class="flex flex-col items-center justify-center py-12">
                <i class="fas fa-box-open text-4xl text-gray-400 mb-4"></i>
                <p class="text-gray-500 text-lg">Không tìm thấy sản phẩm</p>
            </div>`;
                return;
            }

            products.forEach(product => {
                const productCard = document.createElement('div');
                productCard.className = 'flex items-center p-3 rounded-lg border hover:bg-gray-50 cursor-pointer';
                productCard.onclick = () => selectProduct(product);

                productCard.innerHTML = `
            <div class="w-12 h-12 rounded-lg bg-gray-100 flex-shrink-0">
                <img src="${product.Hinhanh || 'https://i.ibb.co/cYHCSgp/image.png'}" 
                     alt="${product.Tensp}" 
                     class="w-full h-full object-cover rounded-lg"
                     onerror="this.src='https://i.ibb.co/cYHCSgp/image.png'">
            </div>
            <div class="ml-3 flex-1">
                <div class="flex items-start justify-between">
                    <h3 class="font-medium text-gray-900 text-sm">${product.Tensp}</h3>
                    <span class="text-sm font-medium text-gray-500">${formatCurrency(product.Giaban)}</span>
                </div>
                <div class="mt-1 flex flex-col gap-1">
                    <div class="text-xs text-gray-500">
                        <span class="px-2 py-0.5 rounded-full bg-blue-100 text-blue-700">
                            ${product.Dvtinh}
                        </span>
                        ${product.Nhomsp}
                    </div>
                </div>
            </div>
        `;

                productList.appendChild(productCard);
            });
        }
      
      
        function printShippingReceipt() {
    if (!validateOrder()) {
        return;
    }
    const printWindow = window.open('', '', 'width=800,height=600');

    printWindow.document.write(`
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phiếu Gửi Hàng: ${document.getElementById('orderID').value}</title>
    <style>
        body {
            font-family: Verdana, sans-serif;
            font-size: 12px;
            line-height: 1.2;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            background-color: #f0f0f0;
        }

        #content {
            width: 148mm;
            background-color: white;
            padding: 5mm;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 3mm;
        }

        .company-name {
            font-size: 18px;
            font-weight: bold;
        }

        .invoice-details {
            font-size: 18px;
            margin-bottom: 2mm;
        }

        .footer {
            text-align: center;
            margin-top: 3mm;
            font-size: 14px;
        }

        .top-info {
            justify-content: space-between;
            font-size: 16px;
            margin-bottom: 2mm;
        }

        @media print {
            body {
                background-color: white;
            }
            #content {
                box-shadow: none;
                padding: 0;
            }
        }
    </style>
</head>
<body>
    <div id="content">
        <div class="header">
            <div class="company-name">
                <img src="${COMPANY_SETTINGS.Logo}" style="width: 40px; vertical-align: middle; margin-right: 5px;" alt="Logo">
                ${COMPANY_SETTINGS.companyName}
            </div>
            <div><strong>${COMPANY_SETTINGS.address}</strong></div>
            <div>SĐT: ${COMPANY_SETTINGS.phone}</div>
            <div class="top-info">
                <div style="text-align: center;">
                    <h2><strong>PHIẾU GỬI HÀNG</strong></h2>
                </div>
                <div style="text-align: left;">Người gửi: ${COMPANY_SETTINGS.companyName}</div>
                <div style="text-align: left;">ĐỊA CHỈ: ${COMPANY_SETTINGS.address}</div>
            </div>
        </div>

        <div class="invoice-details">
            <div>Người nhận: ${getSelectedCustomerName()}</div>
            <div>Số điện thoại: ${document.getElementById('customerPhone').value}</div>
            <div>Địa chỉ: ${document.getElementById('customerAddress').value}</div>
            <div>Thu hộ: ${document.getElementById('total').value}</div>
            <div>Ghi chú: ${document.getElementById('orderNote').value}</div>
        </div>

        <div class="footer">
            <hr>
            <i>Xin cảm ơn và hẹn gặp lại!</i><br>
            <i>Rất biết ơn khi tiếp nhận phản hồi của quý khách.</i>
        </div>
    </div>
</body>
</html>
    `);

    printWindow.document.close();
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}
      
      
        // Product Selection
        function selectProduct(product) {
            const orderDetails = document.getElementById('orderDetails');
            const existingRow = Array.from(orderDetails.children)
                .find(row => row.getAttribute('data-product-id') === product.Masp);

            if (existingRow) {
                const quantityInput = existingRow.querySelector('input[type="number"]');
                quantityInput.value = parseInt(quantityInput.value) + 1;
                updateRowTotal(existingRow);
            } else {
                const row = document.createElement('tr');
                row.setAttribute('data-product-id', product.Masp);

                row.innerHTML = `
            <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                    <div class="flex-shrink-0 h-10 w-10">
                        <img class="h-10 w-10 rounded-full" 
                             src="${product.Hinhanh || 'https://i.ibb.co/cYHCSgp/image.png'}" 
                             alt="${product.Tensp}">
                    </div>
                    <div class="ml-4">
                        <div class="text-sm font-medium text-gray-900">${product.Tensp}</div>
                        <div class="text-sm text-gray-500">${product.Masp}</div>
                    </div>
                </div>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">
                ${product.Dvtinh}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-center">
                <input type="number" min="1" value="1"
                    class="w-20 px-2 py-1 text-center border border-gray-300 rounded"
                    onchange="updateRowTotal(this.closest('tr'))">
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-center text-sm text-gray-500">
                ${formatCurrency(product.Giaban)}
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                ${formatCurrency(product.Giaban)}
            </td>
            <td class="px-6 py-4 whitespace-nowrap">
                <input type="text" class="w-full px-2 py-1 border border-gray-300 rounded text-sm">
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                <button onclick="removeRow(this.closest('tr'))"
                    class="text-red-600 hover:text-red-900">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;

                orderDetails.appendChild(row);
                updateItemCount();
            }

            updateTotals();
        }
        const formatNumberVN = (num) => {
            return num.toString().replace('.', ',');
        };
        // Update Calculations
        function updateRowTotal(row) {
            // Lấy số lượng trực tiếp từ input, không cần unformatCurrency vì input number trả về số
            const quantity = parseInt(row.querySelector('input[type="number"]').value) || 0;
            const productId = row.getAttribute('data-product-id');
            const product = state.products.find(p => p.Masp === productId);
            const price = product ? product.Giaban : 0;
            const total = quantity * price;

            row.children[4].textContent = formatCurrency(total);
            updateTotals();
        }

        // Sửa lại hàm updateTotals để xử lý giá trị đã format
        function updateTotals() {
            const rows = document.getElementById('orderDetails').getElementsByTagName('tr');
            let subtotal = 0;

            Array.from(rows).forEach(row => {
                const rowTotal = unformatCurrency(row.children[4].textContent);
                subtotal += rowTotal;
            });

            const discount = unformatCurrency(document.getElementById('discount').value) || 0;
            const total = subtotal - discount;

            document.getElementById('subtotal').value = formatCurrency(subtotal);
            document.getElementById('total').value = formatCurrency(total);
        }

        async function fetchCompanySettings() {
            try {
                const settingsResponse = await apiService.request("Thongtin", "Find", [{ "Id": "1" }],{} );

                if (!settingsResponse || settingsResponse.length === 0) {
                    throw new Error("Không tìm thấy thông tin cài đặt");
                }

                const settings = settingsResponse[0];

                // Update global settings object
                COMPANY_SETTINGS = {
                    companyName: settings['Tencty'] || '',
                    address: settings['Diachi'] || '',
                    phone: settings['Dienthoai'] || '',
                    taxCode: settings['MST'] || '',
                    accountName: settings['Hovaten'] || '',
                    accountNo: settings['Sotk'] || '',
                    bankId: settings['MaBinNganhang'] || '',
                    bankName: settings['Nganhang'] || '',
                    qrTemplate: settings['Template VietQR'] || 'compact2',
                    Logo: settings['Logo']
                };

              

            } catch (error) {
                console.error("Error fetching company settings:", error);
                alert(`Lỗi khi lấy thông tin cài đặt: ${error.message}`);
            }
        }
        function printOrder() {
    if (!validateOrder()) {
        return;
    }
    const printWindow = window.open('', '', 'width=800,height=600');

    printWindow.document.write(`
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <title>Phiếu Tính tiền: ${document.getElementById('orderID').value}</title>
    <style>
        body {
            font-family: Verdana, sans-serif;
            font-size: 12px;
            line-height: 1.2;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            background-color: white;
        }

        #content {
            width: 80mm;
            padding: 5mm;
        }

        .header {
            text-align: center;
            margin-bottom: 3mm;
        }

        .company-name {
            font-size: 16px;
            font-weight: bold;
        }

        .invoice-details {
            margin-bottom: 2mm;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 10px;
        }

        th, td {
            border-top: 0.5px solid #ddd;
            border-bottom: 0.5px solid #ddd;
            padding: 1mm;
            text-align: left;
            line-height: 1.2;
        }

        .total {
            font-weight: bold;
            text-align: right;
            margin-top: 2mm;
        }

        .footer {
            text-align: center;
            margin-top: 3mm;
            font-size: 10px;
        }

        @media print {
            @page {
                size: 80mm auto;
                margin: 0;
            }

            body {
                width: 80mm;
            }

            #content {
                padding: 0;
            }
        }
    </style>
</head>
<body>
    <div id="content">
        <div class="header">
            <div class="company-name">
                <img src="${COMPANY_SETTINGS.Logo}" style="width: 40px; vertical-align: middle; margin-right: 5px;" alt="Logo">
                ${COMPANY_SETTINGS.companyName}
            </div>
            <div>${COMPANY_SETTINGS.address}</div>
            <div>SĐT: ${COMPANY_SETTINGS.phone}</div>
        </div>

        <div style="text-align: center;">
            <h2><strong>Phiếu Tính tiền</strong></h2>
            <div><strong>Số: ${document.getElementById('orderID').value}</strong></div>
            <div><strong>Ngày: ${new Date().toLocaleDateString('vi-VN')}</strong></div>
        </div>

        <div class="invoice-details">
            <div>Khách hàng: ${getSelectedCustomerName()}</div>
            <div>Số điện thoại: ${document.getElementById('customerPhone').value}</div>
            <div>Địa chỉ: ${document.getElementById('customerAddress').value}</div>
        </div>

        <table>
            <thead>
                <tr>
                    <th>STT.</th>
                    <th>TÊN SP</th>
                    <th>ĐVT</th>
                    <th>SL</th>
                    <th>ĐƠN GIÁ</th>
                    <th>THÀNH TIỀN</th>
                </tr>
            </thead>
            <tbody>
                ${Array.from(document.getElementById('orderDetails').getElementsByTagName('tr')).map((row, index) => `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${row.querySelector('.text-sm.font-medium').textContent}</td>
                        <td>${row.children[1].textContent.trim()}</td>
                        <td>${row.querySelector('input[type="number"]').value}</td>
                        <td style="text-align: right;">${row.children[3].textContent}</td>
                        <td style="text-align: right;">${row.children[4].textContent}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>

        <div class="total">
            Tổng tiền: ${document.getElementById('subtotal').value}<br>
            Giảm giá: ${document.getElementById('discount').value}<br>
            Thành tiền: ${document.getElementById('total').value}
        </div>

        <i>Ghi chú: ${document.getElementById('orderNote').value}</i>

        <div class="footer">
            <img src="${generateVietQRUrl(
                unformatCurrency(document.getElementById('total').value),
                document.getElementById('orderID').value
            )}" width="200"><br>
            <i>Quý khách vui lòng giữ lại Phiếu Tính tiền.</i><br>
            <i>Xin cảm ơn và hẹn gặp lại!</i><br>
            <i>Rất biết ơn khi tiếp nhận phản hồi của quý khách.</i>
        </div>
    </div>
</body>
</html>
    `);

    printWindow.document.close();
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}

// Thêm hàm generateVietQRUrl
function generateVietQRUrl(amount, orderId) {
    const encodedName = encodeURIComponent(COMPANY_SETTINGS.accountName);
    const thongtin = encodeURIComponent("Thanh toan hoa don so " + orderId);
    return `https://img.vietqr.io/image/${COMPANY_SETTINGS.bankId}-${COMPANY_SETTINGS.accountNo}-${COMPANY_SETTINGS.qrTemplate}.png?amount=${amount}&addInfo=${thongtin}&accountName=${encodedName}`;
}


        async function refreshProductList() {
            try {
                showLoading();
                await loadProducts();
                showToast('Đã tải lại danh sách sản phẩm', 'success');
            } catch (error) {
                console.error('Error refreshing products:', error);
                showToast('Lỗi khi tải lại danh sách sản phẩm', 'error');
            } finally {
                hideLoading();
            }
        }

        // Handle Row Removal
        function removeRow(row) {
            row.remove();
            updateItemCount();
            updateTotals();
        }

        // Update Item Count
        function updateItemCount() {
            const count = document.getElementById('orderDetails').children.length;
            document.getElementById('itemCount').textContent = count;
        }

        // Save Order
        async function saveOrder() {
            try {
                if (!validateOrder()) {
                    return;
                }

                showLoading();

                const orderHeader = prepareOrderHeader();
                const orderDetails = prepareOrderDetails();

                // Save order header
                await apiService.request('BANHANG', 'Add', {
                    Rows: [orderHeader]
                },
                    {
                        Locale: "vi-VN",
                        Timezone: "Asia/Ho_Chi_Minh"
                    });

                // Save order details
                await apiService.request('BANHANGDE', 'Add', {
                    Rows: orderDetails
                },
                    {
                        Locale: "vi-VN",
                        Timezone: "Asia/Ho_Chi_Minh"
                    }
                );

                showToast('Đơn hàng đã được lưu thành công!', 'success');
                resetForm();
            } catch (error) {
                console.error('Error saving order:', error);
                showToast('Lỗi khi lưu đơn hàng: ' + error.message, 'error');
            } finally {
                hideLoading();
            }
        }

        function prepareOrderHeader() {
            // Lấy giá trị và chuyển đổi sang số
            const subtotal = formatNumberVN(unformatCurrency(document.getElementById('subtotal').value));
            const discount = formatNumberVN(unformatCurrency(document.getElementById('discount').value)) || 0;
            const total = formatNumberVN(unformatCurrency(document.getElementById('total').value));

            console.log(subtotal, discount, total);

            return {
                IDBANHANG: document.getElementById('orderID').value,
                "THỜI GIAN": document.getElementById('orderDate').value,
                Makh: document.getElementById('customerSelect').value,
                Tenkh: getSelectedCustomerName(),
                Diachi: document.getElementById('customerAddress').value,
                Sodt: document.getElementById('customerPhone').value,
                Tongtien: subtotal,
                Giamgia: discount,
                Thanhtien: total,
                Trangthaidonhang: 'Mới',
                Ghichu: document.getElementById('orderNote').value
            };
        }


        function prepareOrderDetails() {
            const rows = document.getElementById('orderDetails').getElementsByTagName('tr');
            const details = [];

            Array.from(rows).forEach(row => {
                const productId = row.getAttribute('data-product-id');
                const product = state.products.find(p => p.Masp === productId);
                const quantity = parseInt(row.querySelector('input[type="number"]').value) || 0;
                const total = unformatCurrency(row.children[4].textContent);

                details.push({
                    IDBANHANGDE: generateDetailId(),
                    IDBANHANG: document.getElementById('orderID').value,
                    Masp: productId,
                    Tensp: product.Tensp,
                    Mota: product.Mota,
                    Dvtinh: product.Dvtinh,
                    Giaban: product.Giaban,
                    Soluong: quantity,
                    Thanhtien: total,
                    Ghichu: row.querySelector('input[type="text"]').value
                });
            });

            return details;
        }

        // Utility Functions
        function generateOrderId() {
            return `DH${Date.now()}${Math.floor(Math.random() * 1000)}`;
        }

        function generateDetailId() {
            return `CT${Date.now()}${Math.floor(Math.random() * 1000)}`;
        }

        function formatCurrency(number) {
            if (!number) return "0";
            // Làm tròn số và format với dấu phẩy ngăn cách hàng nghìn
            return Math.round(number).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        }

        function unformatCurrency(str) {
            if (typeof str === 'string') {
                return parseFloat(str.replace(/,/g, '')) || 0;
            }
            return parseFloat(str) || 0;
        }

        function getSelectedCustomerName() {
            const select = document.getElementById('customerSelect');
            const option = select.options[select.selectedIndex];
            return option ? option.text.split(' - ')[0] : '';
        }

        function validateOrder() {
            // Kiểm tra khách hàng
            if (!document.getElementById('customerSelect').value) {
                showToast('Vui lòng chọn khách hàng', 'error');
                return false;
            }

            // Kiểm tra sản phẩm
            const orderDetails = document.getElementById('orderDetails');
            if (!orderDetails.children.length) {
                showToast('Vui lòng thêm ít nhất một sản phẩm', 'error');
                return false;
            }

            return true;
        }

        // Toast Notification
        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                style: {
                    background: type === 'success' ? "linear-gradient(to right, #00b09b, #96c93d)" :
                        "linear-gradient(to right, #ff5f6d, #ffc371)",
                }
            }).showToast();
        }

        // Initialize when document is ready
        document.addEventListener('DOMContentLoaded', initializeApp);
    </script>
</body>

</html>