<?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>
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge bg-warning text-dark">Khởi tạo</span>
                        <button class="btn btn-sm btn-outline-danger border-0" id="btn-logout" title="Đăng xuất">
                            <i class="fas fa-sign-out-alt"></i>
                        </button>
                    </div>
                </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="scanner-container" class="d-none bg-dark text-white text-center p-0" style="height: 300px; overflow: hidden; margin-bottom: 10px; position: relative;">
                        <div id="reader" style="width: 100%; height: 100%;"></div>
                        <button class="btn btn-sm btn-danger position-absolute top-0 end-0 m-2" id="btn-stop-scan" style="z-index: 1001">Tắt Cam</button>
                    </div>
                    
                    <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 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 currentOrderId = 0;
        let html5QrcodeScanner = null; // Biến quản lý Camera

        // Âm thanh Bíp
        const beepSound = new Audio('data:audio/wav;base64,UklGRl9vT19XQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YU'); 

        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); }

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

        // --- 1. ĐIỀU HƯỚNG ---
        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();
                showProcessing(true); $('#dynamic-content').load(`/quanlybanhang/modules/pos/tabs/${pageName}_tab.php`, function() { showProcessing(false); }); }
        }
        $('.bottom-nav').on('click', '.nav-item', function(e) { e.preventDefault(); loadPage($(this).data('page')); });

        // --- 2. XỬ LÝ CAMERA QUÉT MÃ ---
        $('#btn-scan-trigger').click(function() {
            $('#scanner-container').removeClass('d-none'); // Hiện khung
            if (html5QrcodeScanner === null) {
                html5QrcodeScanner = new Html5Qrcode("reader");
            }
            const config = { fps: 10, qrbox: { width: 250, height: 250 } };
            html5QrcodeScanner.start({ facingMode: "environment" }, config, onScanSuccess).catch(err => {
                console.error("Lỗi bật camera", err);
                showToast("Không thể bật Camera", "error");
            });
        });

        function onScanSuccess(decodedText, decodedResult) {
            html5QrcodeScanner.pause(); // Tạm dừng để xử lý
            $.ajax({
                url: AJAX_URL,
                dataType: 'json',
                data: { action: 'get_product_by_barcode', barcode: decodedText },
                success: function(res) {
                    if (res.status === 'success') {
                        beepSound.play().catch(e => {}); // Kêu tít
                        window.quickAddCart(res.product); // Thêm ngay
                        setTimeout(() => { html5QrcodeScanner.resume(); }, 1200); // Quét tiếp sau 1.2s
                    } else {
                        showToast("Không tìm thấy SP: " + decodedText, "warning");
                        setTimeout(() => { html5QrcodeScanner.resume(); }, 1500);
                    }
                },
                error: function() {
                    showToast("Lỗi kết nối", "error");
                    setTimeout(() => { html5QrcodeScanner.resume(); }, 1500);
                }
            });
        }

        $('#btn-stop-scan').click(function() {
            if (html5QrcodeScanner) {
                html5QrcodeScanner.stop().then(() => {
                    $('#scanner-container').addClass('d-none');
                }).catch(err => console.log(err));
            } else {
                $('#scanner-container').addClass('d-none');
            }
        });

        // Đóng modal thì tắt cam
        document.getElementById('productSelectionModal').addEventListener('hidden.bs.modal', function () {
            if (html5QrcodeScanner) {
                try { html5QrcodeScanner.stop(); } catch(e) {}
                $('#scanner-container').addClass('d-none');
            }
        });

        // --- 3. TÌM KIẾM & GIỎ HÀNG ---
        $('#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);
        });

        function loadProducts(term) {
            $('#product-search-results').html('<div class="text-center py-3"><div class="spinner-border spinner-border-sm text-muted"></div></div>');
            $.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) {
                        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="fw-bold text-dark">${p.name}</div>
                                    <div class="small text-muted">Mã: ${p.code} | Tồn: <span class="text-danger fw-bold">${p.inventory}</span></div>
                                    <div class="fw-bold text-primary mt-1">${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) {
                if (existing.quantity + 1 > product.inventory) { showToast('Hết hàng trong kho!', 'warning'); return; }
                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)); $('#btn-back-to-cart').addClass('animate__animated animate__pulse'); setTimeout(() => $('#btn-back-to-cart').removeClass('animate__animated animate__pulse'), 500); }

        function renderCart() {
            const $container = $('#cart-list-container').empty();
            if (cart.length === 0) { $container.html('<div class="text-center text-muted py-5"><i class="fas fa-shopping-cart fa-3x mb-3"></i><p>Chưa có sản phẩm</p></div>'); calculateTotal(); return; }
            cart.forEach((item, index) => {
                let itemDiscountAmt = item.price * (item.discount_percent / 100);
                let lineTotal = (item.price - itemDiscountAmt) * item.quantity;
                $container.append(`
                <div class="cart-item p-3">
                    <div class="d-flex justify-content-between align-items-start"><div class="product-name">${item.name}</div><i class="fas fa-times text-danger px-2" style="cursor:pointer" 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 text-danger item-discount-input" data-index="${index}" value="${item.discount_percent > 0 ? item.discount_percent : ''}" placeholder="0"></div>
                            <div class="d-flex align-items-center bg-light rounded-pill border px-1" style="height: 38px;"><button class="btn btn-sm border-0 text-danger fw-bold" 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;" data-index="${index}" value="${item.quantity}" readonly><button class="btn btn-sm border-0 text-success fw-bold" onclick="window.changeQty(${index}, 1)">+</button></div>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-2 pt-2 border-top border-light"><span class="text-muted small">Thành tiền:</span><span class="fw-bold text-dark fs-6 line-total-display">${formatNumber(lineTotal)}</span></div>
                </div>`);
            });
            renderFooterControls(); calculateTotal(); bindEvents();
        }

        function renderFooterControls() {
            if ($('#footer-controls').length === 0) {
                let percentBtnClass = orderDiscount.type === 'percent' ? 'btn-primary' : 'btn-outline-secondary';
                $('#cart-list-container').append(`<div id="footer-controls"><div class="d-flex justify-content-between align-items-center mb-2"><span class="fw-bold text-dark">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 > 0 ? orderDiscount.value : ''}" placeholder="0"><button class="btn ${percentBtnClass}" type="button" 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 border-2 mt-2"><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').off('input').on('input', function() { let idx = $(this).data('index'), val = parseFloat($(this).val()) || 0; if (val > 100) val = 100; cart[idx].discount_percent = val; calculateTotal(); });
            $('#order-discount-val').off('input').on('input', function() { orderDiscount.value = parseFloat($(this).val()) || 0; calculateTotal(); });
            $('#btn-toggle-percent').off('click').on('click', function() { orderDiscount.type = (orderDiscount.type === 'money') ? 'percent' : 'money'; $(this).toggleClass('btn-primary btn-outline-secondary'); calculateTotal(); });
        }

        function calculateTotal() {
            let totalGoods = 0;
            cart.forEach((item, idx) => { let itemDiscountAmt = item.price * (item.discount_percent / 100); let lineTotal = (item.price - itemDiscountAmt) * item.quantity; totalGoods += lineTotal; $('.cart-item').eq(idx).find('.line-total-display').text(formatNumber(lineTotal)); });
            let totalOrderDiscount = (orderDiscount.type === 'percent') ? (totalGoods * (orderDiscount.value / 100)) : orderDiscount.value;
            let finalTotal = Math.max(0, totalGoods - totalOrderDiscount);
            $('#final-total-display').text(formatNumber(finalTotal)); $('#cart-total-amount').text(formatNumber(finalTotal));
        }

        window.changeQty = function(index, delta) { let item = cart[index], newQty = item.quantity + delta; if (newQty > item.inventory) { showToast('Vượt quá tồn kho!', 'warning'); return; } if (newQty <= 0) { window.removeCartItem(index); return; } item.quantity = newQty; renderCart(); };
        window.removeCartItem = function(index) { Swal.fire({ title: 'Xóa sản phẩm?', icon: 'question', showCancelButton: true, confirmButtonText: 'Xóa' }).then((res) => { if (res.isConfirmed) { cart.splice(index, 1); renderCart(); updateFloatingBadge(); } }); };

        // --- 4. KHÁCH HÀNG & LƯU ĐƠN ---
        $('#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(term) { $.ajax({ url: AJAX_URL, dataType: 'json', data: { action: 'search_customers', term: term }, success: function(res) { const $list = $('#customer-search-results').empty(); $list.append(`<button class="list-group-item list-group-item-action py-3" onclick="window.selectCustomer(1, 'Khách lẻ', 1)"><div class="fw-bold"><i class="fas fa-user me-2"></i>Khách lẻ</div></button>`); if (res.status === 'success' && res.results) { res.results.forEach(c => { $list.append(`<button class="list-group-item list-group-item-action py-3 px-3 border-bottom" onclick="window.selectCustomer(${c.id}, '${c.name}', ${c.customer_group})"><div class="d-flex justify-content-between"><div class="fw-bold text-primary fs-5">${c.name}</div><div class="text-muted small">${c.phone || ''}</div></div><div class="d-flex justify-content-between small mt-2 text-secondary"><span>Tổng: <b>${formatNumber(c.total_spent)}</b></span><span class="${c.total_debt > 0 ? 'text-danger fw-bold' : 'text-success'}">Nợ: ${formatNumber(c.total_debt)}</span></div></button>`); }); } } }); }
        window.selectCustomer = function(id, name, group = 1) { currentCustomer = { id, name, group }; $('#selected-customer-name').text(name); bootstrap.Modal.getInstance(document.getElementById('customerSelectionModal')).hide(); cart.forEach(item => { item.price = (group != 1 && item.price_wholesale > 0) ? item.price_wholesale : item.price_retail; }); renderCart(); };
        $('#btn-show-add-customer').click(function() { $('#quick_customer_name').val(''); $('#quick_customer_phone').val(''); $('#quick_customer_addr').val(''); $('#quickAddCustomerModal').modal('show'); });
        $('#btn-save-new-customer').click(function() { let name = $('#quick_customer_name').val(); if(!name) { showToast('Nhập tên khách hàng!', '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); showToast('Đã thêm khách hàng'); } 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 = currentOrderId > 0 ? 'Cập nhật đơn hàng?' : 'Tạo đơn Khởi tạo?'; let confirmBtnText = currentOrderId > 0 ? 'Cập nhật' : 'Lưu Đơn';
            Swal.fire({ title: actionText, icon: 'question', showCancelButton: true, confirmButtonText: confirmBtnText }).then((r) => {
                if(r.isConfirmed) { showProcessing(true); $.post(AJAX_URL, { action: 'create_temp_order', customer_id: currentCustomer.id, notes: $('#order-note').val(), items: JSON.stringify(itemsData), order_discount_val: orderDiscount.value, order_discount_type: orderDiscount.type, order_id: currentOrderId }, 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)'); }); }
            });
        });

        $('#btn-cancel-edit').click(function() { resetPosForm(); });
        
        // --- GLOBAL FUNCS FOR INVOICES TAB ---
        window.deleteOrder = function(id, code) { Swal.fire({ title: 'Xóa đơn ' + code + '?', text: "Hành động này không thể hoàn tác!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33', confirmButtonText: 'Xóa ngay' }).then((result) => { if (result.isConfirmed) { $.post(AJAX_URL, { action: 'delete_order', order_id: id }, function(res) { if(res.status === 'success') { showToast('Đã xóa đơn hàng'); loadPage('invoices'); } else { showError(res.message); } }, 'json'); } }); }
        window.editOrderFromList = function(order) { currentOrderId = order.ID; currentCustomer = { id: order.customer_id, name: order.customer_name, phone: order.customer_phone, group: order.customer_group || 1 }; $('#selected-customer-name').text(order.customer_name); cart = []; let items = []; try { items = JSON.parse(order.detail_order); } catch(e) {} items.forEach(item => { cart.push({ id: item.id, name: item.name, code: item.code, price: parseFloat(item.price), price_retail: parseFloat(item.price), price_wholesale: parseFloat(item.price), quantity: parseFloat(item.quantity), inventory: 999, discount_percent: parseFloat(item.percent || 0), cost: parseFloat(item.origin_price || 0) }); }); let discPer = parseFloat(order.discount_percent); let discItem = parseFloat(order.discount_item); if (discPer > 0) { orderDiscount.value = discPer; orderDiscount.type = 'percent'; $('#btn-toggle-percent').addClass('btn-primary').removeClass('btn-outline-secondary'); } else { orderDiscount.value = discItem; orderDiscount.type = 'money'; $('#btn-toggle-percent').removeClass('btn-primary').addClass('btn-outline-secondary'); } $('#order-discount-val').val(orderDiscount.value > 0 ? orderDiscount.value : ''); $('#order-note').val(order.notes); loadPage('create-order'); $('#page-title').text('Sửa Đơn: ' + order.output_code); $('#btn-cancel-edit').removeClass('d-none'); $('#btn-save-order').html('<i class="fas fa-edit me-2"></i> CẬP NHẬT'); renderCart(); };
        
        // --- KẾT THÚC ---
        loadPage('create-order');
    });
    </script>
</body>
</html>