<?php
require_once __DIR__ . '/../../core/init.php';
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>POS Mobile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f6f9; padding-bottom: 80px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
        .bottom-nav { position: fixed; bottom: 0; left: 0; width: 100%; background: #fff; box-shadow: 0 -2px 10px rgba(0,0,0,0.05); display: flex; justify-content: space-around; padding: 8px 0; z-index: 1000; }
        .nav-item { text-decoration: none; color: #959ca6; text-align: center; font-size: 10px; display: flex; flex-direction: column; align-items: center; width: 25%; }
        .nav-item i { font-size: 20px; margin-bottom: 4px; }
        .nav-item.active { color: #0d6efd; font-weight: 600; }
        .cart-item { background: #fff; border-radius: 10px; margin-bottom: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); border: 1px solid #f0f0f0; overflow: hidden; }
        .product-name { color: #0d6efd; font-weight: 800; font-size: 1rem; text-transform: uppercase; margin-bottom: 4px; line-height: 1.3; }
        .product-meta { font-size: 0.85rem; color: #6c757d; margin-bottom: 6px; display: flex; align-items: center; }
        .inventory-badge { background-color: #fff3cd; color: #664d03; font-weight: 700; padding: 1px 6px; border-radius: 4px; margin-left: 5px; font-size: 0.8rem; }
        .product-price { color: #0d6efd; font-weight: 800; font-size: 1.1rem; }
        .custom-input { border-radius: 20px !important; border: 1px solid #dee2e6; text-align: center; font-weight: 600; height: 36px; font-size: 1rem; }
        .custom-input:focus { border-color: #0d6efd; box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.1); }
        #footer-controls { background: #fff; border-top: 1px solid #e9ecef; box-shadow: 0 -4px 20px rgba(0,0,0,0.05); padding: 15px; border-radius: 15px 15px 0 0; z-index: 999; }
        .total-label { font-size: 1.1rem; font-weight: 600; color: #555; }
        .total-amount { font-size: 1.8rem; font-weight: 900; color: #dc3545; }
        .modal-fullscreen .modal-header { padding: 10px; background: #fff; border-bottom: 1px solid #eee; }
        .modal-fullscreen .modal-body { background: #f8f9fa; padding: 0; }
        .product-select-item { background: white; padding: 12px; border-bottom: 1px solid #f0f0f0; display: flex; justify-content: space-between; align-items: center; }
        .product-select-item:active { background-color: #e9ecef; }
        .product-select-item .prod-name { color: #0d6efd; font-weight: 800; text-transform: uppercase; font-size: 1rem; line-height: 1.2; margin-bottom: 4px; }
        .product-select-item .prod-meta { font-size: 0.9rem; color: #555; }
        .product-select-item .prod-price { color: #0d6efd; font-weight: 700; font-size: 1.1rem; margin-top: 4px; }
        .product-select-item .badge-stock { background: #fff3cd; color: #664d03; font-weight: bold; padding: 2px 6px; border-radius: 4px; font-size: 0.85rem; }
        .customer-select-item { background: white; padding: 12px; border-bottom: 1px solid #eee; cursor: pointer; }
        .customer-select-item:active { background: #f8f9fa; }
        .customer-select-item .cust-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
        .customer-select-item .cust-name { color: #0d6efd; font-weight: 800; font-size: 1.05rem; }
        .customer-select-item .cust-phone { color: #6c757d; font-size: 0.9rem; }
        .customer-select-item .cust-info { display: flex; justify-content: space-between; font-size: 0.9rem; color: #495057; }
        .customer-select-item .cust-debt { color: #dc3545; font-weight: 700; }
        .customer-select-item .cust-no-debt { color: #198754; font-weight: 600; }
        .btn-quick-add { width: 40px; height: 40px; border-radius: 50%; background: #e7f1ff; color: #0d6efd; border: none; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; }
        .floating-cart-btn { position: fixed; bottom: 30px; right: 20px; width: 60px; height: 60px; background-color: #dc3545; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(220, 53, 69, 0.5); z-index: 1060; border: 2px solid #fff; cursor: pointer; }
        .cart-badge-count { position: absolute; top: -5px; right: -5px; background: #fff; color: #dc3545; font-size: 12px; font-weight: bold; padding: 2px 6px; border-radius: 10px; border: 1px solid #dc3545; }
        #processing-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.8); z-index: 9999; display: flex; justify-content: center; align-items: center; }
    </style>
</head>
<body>
    <main id="main-content">
        <section id="page-create-order" class="d-none">
            <div class="bg-white p-3 sticky-top shadow-sm">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5 class="m-0 fw-bold text-primary" id="page-title">Đơn Hàng Mới</h5>
                    <span class="badge bg-warning text-dark">Khởi tạo</span>
                </div>
                <div class="card border-0 bg-light" id="btn-open-customer-modal" style="cursor: pointer;">
                    <div class="card-body p-2 d-flex align-items-center">
                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 32px; height: 32px;"><i class="fas fa-user small"></i></div>
                        <div class="flex-grow-1"><div class="fw-bold text-dark" id="selected-customer-name">Khách lẻ</div></div>
                        <i class="fas fa-chevron-down text-muted small"></i>
                    </div>
                </div>
            </div>

            <div class="container-fluid mt-2 px-2" style="padding-bottom: 250px;">
                <button id="btn-open-catalog" class="btn btn-outline-primary w-100 py-3 border-dashed fw-bold mb-3 d-flex align-items-center justify-content-center" style="border-style: dashed; background: #f8f9fa;"><i class="fas fa-plus-circle me-2 fs-5"></i> CHỌN SẢN PHẨM</button>
                <div id="cart-list-container"><div class="text-center text-muted py-4"><p class="small">Giỏ hàng đang trống</p></div></div>
            </div>

            <div class="fixed-bottom bg-white p-3 border-top shadow-lg" style="bottom: 56px; z-index: 990; border-radius: 15px 15px 0 0;">
                <div class="d-flex justify-content-between align-items-center mb-2"><span class="text-muted small">Tổng cộng:</span><span class="fw-bold text-danger fs-4" id="cart-total-amount">0</span></div>
                <div class="row g-2">
                    <div class="col-12"><textarea id="order-note" class="form-control form-control-sm bg-light" rows="1" placeholder="Ghi chú..."></textarea></div>
                    <div class="col-12 d-flex gap-2">
                        <button id="btn-cancel-edit" class="btn btn-secondary fw-bold py-2 d-none" style="width: 30%">Hủy</button>
                        <button id="btn-save-order" class="btn btn-primary fw-bold py-2 flex-grow-1"><i class="fas fa-save me-2"></i> LƯU & TẠO ĐƠN</button>
                    </div>
                </div>
            </div>
        </section>
        <div id="dynamic-content"></div>
    </main>

    <nav class="bottom-nav">
        <a href="#" class="nav-item active" data-page="create-order"><i class="fas fa-plus-circle text-primary"></i><span class="text-primary fw-bold">Tạo đơn</span></a>
        <a href="#" class="nav-item" data-page="overview"><i class="fas fa-home"></i><span>Tổng quan</span></a>
        <a href="#" class="nav-item" data-page="invoices"><i class="fas fa-file-invoice"></i><span>Hóa đơn</span></a>
        <a href="#" class="nav-item" data-page="profit"><i class="fas fa-chart-pie"></i><span>Lợi nhuận</span></a>
    </nav>

    <div class="modal fade modal-fullscreen" id="productSelectionModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><div class="input-group bg-light rounded-pill px-2 flex-grow-1"><span class="input-group-text bg-transparent border-0"><i class="fas fa-search text-muted"></i></span><input type="text" class="form-control bg-transparent border-0 shadow-none" id="input-search-product" placeholder="Tìm tên, mã hàng..."><button class="btn btn-link text-dark border-0" id="btn-scan-trigger" type="button"><i class="fas fa-qrcode fs-4"></i></button></div><button type="button" class="btn-close ms-2" data-bs-dismiss="modal"></button></div><div class="modal-body position-relative"><div id="product-search-results"><div class="text-center text-muted py-5 small">Nhập từ khóa hoặc quét mã để tìm...</div></div><div class="floating-cart-btn" id="btn-back-to-cart"><i class="fas fa-shopping-basket fs-4"></i><div class="cart-badge-count" id="temp-cart-count">0</div></div></div></div></div></div>
    <div class="modal fade" id="scanBarcodeModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark"><div class="modal-header border-0 py-2"><h6 class="text-white mb-0"><i class="fas fa-camera me-2"></i>Quét Mã Vạch</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-0 position-relative"><div id="reader" style="width: 100%; min-height: 300px; background: #000;"></div><div class="text-center text-white p-2 small">Di chuyển camera vào vùng mã vạch</div></div></div></div></div>
    <div class="modal fade modal-fullscreen" id="customerSelectionModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header d-flex align-items-center"><input type="text" class="form-control rounded-pill me-2" id="input-search-customer" placeholder="Tìm khách hàng..."><button class="btn btn-outline-primary border-0 bg-white ms-1 rounded-circle d-flex align-items-center justify-content-center" id="btn-show-add-customer" style="width: 40px; height: 40px;"><i class="fas fa-user-plus"></i></button><button type="button" class="btn-close ms-2" data-bs-dismiss="modal"></button></div><div class="modal-body bg-light"><div id="customer-search-results"></div></div></div></div></div>
    <div class="modal fade" id="quickAddCustomerModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title fw-bold">Thêm Khách Hàng Mới</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div class="mb-3"><label class="form-label fw-bold">Tên khách hàng <span class="text-danger">*</span></label><input type="text" class="form-control" id="quick_customer_name" placeholder="Nhập tên..."></div><div class="mb-3"><label class="form-label">Số điện thoại</label><input type="tel" class="form-control" id="quick_customer_phone" placeholder="Nhập số điện thoại..."></div><div class="mb-3"><label class="form-label">Địa chỉ</label><input type="text" class="form-control" id="quick_customer_addr" placeholder="Nhập địa chỉ..."></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button><button type="button" class="btn btn-primary fw-bold" id="btn-save-new-customer">Lưu & Chọn</button></div></div></div></div>
    <div id="processing-overlay" style="display:none;"><div class="spinner-border text-primary" role="status"></div></div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    
    <script>
    $(document).ready(function() {
        const AJAX_URL = '/quanlybanhang/ajax/pos_mobile_ajax.php';
        let cart = [];
        let currentCustomer = { id: 1, name: 'Khách lẻ', phone: '', group: 1 };
        let orderDiscount = { value: 0, type: 'money' }; 
        let html5QrcodeScanner = null;
        let editingOrderId = 0; 

        function formatNumber(num) { return new Intl.NumberFormat('vi-VN').format(num); }
        function showToast(message, type = 'success') { Swal.fire({ toast: true, position: 'top-end', icon: type, title: message, showConfirmButton: false, timer: 1500 }); }
        function showError(message) { Swal.fire({ icon: 'error', title: 'Lỗi', text: message }); }
        function showProcessing(show) { show ? $('#processing-overlay').fadeIn(100) : $('#processing-overlay').fadeOut(100); }

        function resetPosForm() {
            cart = []; orderDiscount = { value: 0, type: 'money' }; editingOrderId = 0; 
            currentCustomer = { id: 1, name: 'Khách lẻ', phone: '', group: 1 };
            renderCart(); updateFloatingBadge();
            $('#order-note').val(''); $('#selected-customer-name').text('Khách lẻ');
            $('#page-title').text('Đơn Hàng Mới'); $('#btn-save-order').html('<i class="fas fa-save me-2"></i> LƯU & TẠO ĐƠN');
            $('#btn-cancel-edit').addClass('d-none');
        }
        $('#btn-cancel-edit').click(function() { resetPosForm(); });

        // [FIX LỖI] Thêm kiểm tra Modal instance trước khi hide
        window.selectCustomer = function(id, name, group = 1) {
            currentCustomer = { id, name, group };
            $('#selected-customer-name').text(name);
            
            // Kiểm tra xem modal có đang mở không rồi mới ẩn
            const modalEl = document.getElementById('customerSelectionModal');
            const modalInstance = bootstrap.Modal.getInstance(modalEl);
            if (modalInstance) {
                modalInstance.hide();
            }
            
            // Cập nhật lại giá trong giỏ (Giá sỉ/lẻ)
            cart.forEach(item => { item.price = (group != 1 && item.price_wholesale > 0) ? item.price_wholesale : item.price_retail; });
            renderCart();
        };

        window.editOrderFromList = function(orderData) {
            if (!orderData) return;
            Swal.fire({ title: 'Sửa đơn hàng?', text: "Đơn hàng sẽ được tải lại.", icon: 'info', showCancelButton: true, confirmButtonText: 'Đồng ý' }).then((result) => {
                if (result.isConfirmed) {
                    resetPosForm(); 
                    editingOrderId = orderData.ID;
                    $('#page-title').text('Sửa Đơn: ' + orderData.output_code);
                    $('#btn-save-order').html('<i class="fas fa-save me-2"></i> CẬP NHẬT');
                    $('#btn-cancel-edit').removeClass('d-none');

                    // Gọi hàm selectCustomer nhưng ở mode load dữ liệu (modal chưa mở nên không cần hide)
                    // Ta gán trực tiếp biến và update giao diện text
                    currentCustomer = { id: orderData.customer_id, name: orderData.customer_name, group: orderData.customer_group };
                    $('#selected-customer-name').text(orderData.customer_name);

                    try {
                        let items = JSON.parse(orderData.detail_order);
                        items.forEach(i => {
                            // Logic tính giá tùy theo khách hàng
                            let p_price = parseFloat(i.price);
                            let p_retail = parseFloat(i.price); // Tạm lấy giá bán làm giá gốc để hiển thị
                            
                            cart.push({
                                id: i.id, code: i.code, name: i.name,
                                price: p_price, price_retail: p_retail, price_wholesale: p_retail,
                                quantity: parseFloat(i.quantity), inventory: 9999,
                                discount_percent: parseFloat(i.percent), cost: parseFloat(i.origin_price)
                            });
                        });
                        renderCart(); updateFloatingBadge();
                    } catch(e) {}

                    if (parseFloat(orderData.discount_percent) > 0) {
                        orderDiscount.value = parseFloat(orderData.discount_percent); orderDiscount.type = 'percent';
                    } else {
                        orderDiscount.value = parseFloat(orderData.discount_item); orderDiscount.type = 'money';
                    }
                    $('#order-discount-val').val(orderDiscount.value);
                    $('#order-note').val(orderData.notes);
                    
                    $('.nav-item[data-page="create-order"]').click();
                }
            });
        };

        window.deleteOrder = function(orderId, orderCode) {
            Swal.fire({ title: 'Xóa đơn hàng?', text: `Xóa đơn ${orderCode}?`, icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33', confirmButtonText: 'Xóa ngay' }).then((r) => {
                if (r.isConfirmed) {
                    $.post(AJAX_URL, { action: 'delete_order', order_id: orderId }, function(res) {
                        if(res.status === 'success') {
                            showToast('Đã xóa đơn hàng');
                            if ($('.nav-item[data-page="invoices"]').hasClass('active')) { $('#btn-filter-invoices').click(); }
                        } else { showError(res.message); }
                    }, 'json');
                }
            });
        };

        // (Các hàm khác giữ nguyên)
        function loadPage(pageName) {
            $('.nav-item').removeClass('active'); $(`.nav-item[data-page="${pageName}"]`).addClass('active');
            if (pageName === 'create-order') { $('#dynamic-content').hide(); $('#page-create-order').removeClass('d-none').show(); renderCart(); } 
            else { $('#page-create-order').addClass('d-none').hide(); $('#dynamic-content').show(); let url = `/quanlybanhang/modules/pos/tabs/${pageName}_tab.php`; showProcessing(true); $('#dynamic-content').load(url, function() { showProcessing(false); }); }
        }
        $('.bottom-nav').on('click', '.nav-item', function(e) { e.preventDefault(); let page = $(this).data('page'); loadPage(page); });
        $('#btn-open-catalog').click(function() { new bootstrap.Modal(document.getElementById('productSelectionModal')).show(); setTimeout(() => { $('#input-search-product').val('').focus(); loadProducts(''); }, 300); });
        let searchTimeout; $('#input-search-product').on('input', function() { clearTimeout(searchTimeout); const term = $(this).val(); searchTimeout = setTimeout(() => loadProducts(term), 300); });
        $('#btn-scan-trigger').click(function() { $('#productSelectionModal').modal('hide'); $('#scanBarcodeModal').modal('show'); });
        $('#scanBarcodeModal').on('shown.bs.modal', function () { startScanner(); });
        $('#scanBarcodeModal').on('hidden.bs.modal', function () { if (html5QrcodeScanner) html5QrcodeScanner.clear().catch(e=>{}); $('#productSelectionModal').modal('show'); });
        function startScanner() { html5QrcodeScanner = new Html5QrcodeScanner("reader", { fps: 10, qrbox: 250, aspectRatio: 1.0 }, false); html5QrcodeScanner.render(onScanSuccess, ()=>{}); }
        function onScanSuccess(d) { if (html5QrcodeScanner) html5QrcodeScanner.clear(); $('#scanBarcodeModal').modal('hide'); $('#input-search-product').val(d); loadProducts(d, true); }
        function loadProducts(term, auto=false) { $.ajax({ url: AJAX_URL, dataType: 'json', data: { action: 'search_products', term: term }, success: function(res) { const $list = $('#product-search-results').empty(); if (res.status === 'success' && res.results && res.results.length > 0) { if (auto && res.results.length === 1 && res.results[0].code.toLowerCase() == term.toLowerCase()) { window.quickAddCart(res.results[0]); $('#input-search-product').val(''); showToast('Đã quét: '+res.results[0].name); return; } res.results.forEach(p => { let displayPrice = (currentCustomer.group != 1 && p.price_wholesale > 0) ? p.price_wholesale : p.price_retail; $list.append(`<div class="product-select-item" onclick='window.quickAddCart(${JSON.stringify(p)})'><div class="flex-grow-1 me-2"><div class="prod-name">${p.name}</div><div class="prod-meta">Mã: ${p.code} <span class="badge-stock">Tồn: ${p.inventory}</span></div><div class="prod-price">${formatNumber(displayPrice)}</div></div><button class="btn-quick-add"><i class="fas fa-plus"></i></button></div>`); }); } else { $list.html('<div class="text-center text-muted py-3">Không tìm thấy sản phẩm</div>'); } } }); }
        window.quickAddCart = function(product) { let existing = cart.find(i => i.id == product.id); if (existing) { existing.quantity++; } else { let price = (currentCustomer.group != 1 && product.price_wholesale > 0) ? product.price_wholesale : product.price_retail; cart.push({ id: product.id, name: product.name, code: product.code, price: parseFloat(price), price_retail: parseFloat(product.price_retail), price_wholesale: parseFloat(product.price_wholesale), quantity: 1, inventory: product.inventory, discount_percent: 0, cost: parseFloat(product.origin_price) }); } showToast(`Đã thêm: ${product.name}`); updateFloatingBadge(); };
        $('#btn-back-to-cart').click(function() { bootstrap.Modal.getInstance(document.getElementById('productSelectionModal')).hide(); renderCart(); });
        function updateFloatingBadge() { $('#temp-cart-count').text(cart.reduce((sum, item) => sum + item.quantity, 0)); }
        function renderCart() { const $c = $('#cart-list-container').empty(); if (cart.length === 0) { $c.html('<div class="text-center text-muted py-4"><p class="small">Giỏ hàng đang trống</p></div>'); calculateTotal(); return; } cart.forEach((item, index) => { let itemDiscount = item.price * (item.discount_percent / 100); let total = (item.price - itemDiscount) * item.quantity; $c.append(`<div class="cart-item p-3"><div class="d-flex justify-content-between"><div class="product-name">${item.name}</div><i class="fas fa-times text-danger" onclick="window.removeCartItem(${index})"></i></div><div class="product-meta"><span>Mã: ${item.code}</span><span class="inventory-badge">Tồn: ${item.inventory}</span></div><div class="d-flex justify-content-between align-items-end mt-3"><div class="product-price">${formatNumber(item.price)}</div><div class="d-flex align-items-center gap-2"><div style="width:60px"><input type="number" class="form-control form-control-sm custom-input item-discount-input" data-index="${index}" value="${item.discount_percent}" placeholder="%"></div><div class="d-flex align-items-center bg-light rounded-pill border px-1"><button class="btn-qty btn btn-sm text-danger" onclick="window.changeQty(${index},-1)">-</button><input type="number" class="form-control border-0 bg-transparent text-center p-0 item-qty-input" style="width:30px;font-weight:bold" value="${item.quantity}" readonly><button class="btn-qty btn btn-sm text-success" onclick="window.changeQty(${index},1)">+</button></div></div></div><div class="text-end fw-bold mt-2">${formatNumber(total)}</div></div>`); }); renderFooterControls(); calculateTotal(); bindEvents(); }
        function renderFooterControls() { if($('#footer-controls').length===0) $('#cart-list-container').append(`<div id="footer-controls"><div class="d-flex justify-content-between align-items-center mb-2"><span class="total-label">Giảm giá đơn:</span><div class="input-group" style="width: 140px;"><input type="number" id="order-discount-val" class="form-control text-end fw-bold" style="border-radius:20px 0 0 20px" value="${orderDiscount.value}" placeholder="0"><button class="btn ${orderDiscount.type==='percent'?'btn-primary':'btn-outline-secondary'}" id="btn-toggle-percent" style="border-radius:0 20px 20px 0;width:40px">%</button></div></div><div class="d-flex justify-content-between align-items-center pt-2 border-top"><span class="total-label">TỔNG CỘNG:</span><span class="total-amount" id="final-total-display">0</span></div></div>`); }
        function bindEvents() { $('.item-discount-input').on('input', function() { let i=$(this).data('index'), v=parseFloat($(this).val())||0; if(v>100)v=100; cart[i].discount_percent=v; calculateTotal(); }); $('#order-discount-val').on('input', function() { orderDiscount.value=parseFloat($(this).val())||0; calculateTotal(); }); $('#btn-toggle-percent').click(function() { orderDiscount.type=(orderDiscount.type==='money')?'percent':'money'; $(this).toggleClass('btn-primary btn-outline-secondary'); calculateTotal(); }); }
        function calculateTotal() { let total=0; cart.forEach((item)=>{ let d=item.price*(item.discount_percent/100); total+=(item.price-d)*item.quantity; }); let od=(orderDiscount.type==='percent')?(total*(orderDiscount.value/100)):orderDiscount.value; let final=Math.max(0, total-od); $('#final-total-display').text(formatNumber(final)); $('#cart-total-amount').text(formatNumber(final)); }
        window.changeQty = function(i,d) { let item=cart[i], n=item.quantity+d; if(n>item.inventory) return showToast('Hết hàng!','warning'); if(n<=0) return window.removeCartItem(i); item.quantity=n; renderCart(); };
        window.removeCartItem = function(i) { Swal.fire({title:'Xóa?', icon:'question', showCancelButton:true}).then((r)=>{ if(r.isConfirmed){ cart.splice(i,1); renderCart(); updateFloatingBadge(); } }); };
        $('#btn-open-customer-modal').click(function() { new bootstrap.Modal(document.getElementById('customerSelectionModal')).show(); setTimeout(()=>$('#input-search-customer').focus(),300); loadCustomers(''); });
        $('#input-search-customer').on('input', function() { loadCustomers($(this).val()); });
        function loadCustomers(t) { $.ajax({ url: AJAX_URL, dataType: 'json', data: {action:'search_customers', term:t}, success: function(res) { const l=$('#customer-search-results').empty(); l.append(`<div class="customer-select-item" onclick="window.selectCustomer(1,'Khách lẻ',1)"><div class="cust-name">Khách lẻ</div></div>`); if(res.status==='success') res.results.forEach(c=>l.append(`<div class="customer-select-item" onclick="window.selectCustomer(${c.id},'${c.name}',${c.customer_group})"><div class="cust-name">${c.name}</div><div class="cust-info">${c.phone || ''}</div></div>`)); } }); }
        $('#btn-show-add-customer').click(function() { $('#quickAddCustomerModal').modal('show'); });
        $('#btn-save-new-customer').click(function() { let name = $('#quick_customer_name').val(); if(!name) { showToast('Nhập tên!', 'warning'); return; } $.post(AJAX_URL, { action: 'save_quick_customer', customer_name: name, customer_phone: $('#quick_customer_phone').val(), customer_addr: $('#quick_customer_addr').val() }, function(res) { if(res.status === 'success') { $('#quickAddCustomerModal').modal('hide'); window.selectCustomer(res.customer_id, res.customer_name, 1); } else { showError(res.message); } }, 'json'); });

        $('#btn-save-order').click(() => {
            if (cart.length === 0) { showToast('Giỏ hàng trống', 'warning'); return; }
            let itemsData = cart.map(item => { return { ...item, discount_amount: item.price * (item.discount_percent / 100) }; });
            let actionText = editingOrderId > 0 ? 'Cập nhật đơn hàng?' : 'Tạo đơn Khởi tạo?';
            let btnText = editingOrderId > 0 ? 'Cập nhật' : 'Tạo đơn';
            Swal.fire({ title: actionText, icon: 'question', showCancelButton: true, confirmButtonText: btnText }).then((r) => {
                if(r.isConfirmed) {
                    showProcessing(true);
                    $.post(AJAX_URL, { action: 'create_temp_order', order_id: editingOrderId, customer_id: currentCustomer.id, notes: $('#order-note').val(), items: JSON.stringify(itemsData), order_discount_val: orderDiscount.value, order_discount_type: orderDiscount.type }, function(res) { showProcessing(false); if(res.status === 'success') { Swal.fire({ icon: 'success', title: 'Thành công', text: res.message }).then(() => { resetPosForm(); }); } else { showError(res.message); } }, 'json').fail((xhr) => { showProcessing(false); showError('Lỗi kết nối (500)'); });
                }
            });
        });
        loadPage('create-order');
    });
    </script>
</body>
</html>