$(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' }; 

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

    // --- 1. ĐIỀU HƯỚNG & GIAO DIỆ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(response, status, xhr) {
                showProcessing(false);
                if (status == "error") {
                    $('#dynamic-content').html('<div class="text-center p-5 text-muted">Chức năng đang cập nhật...</div>');
                }
            });
        }
    }

    $('.bottom-nav').on('click', '.nav-item', function(e) {
        e.preventDefault();
        let page = $(this).data('page');
        loadPage(page);
    });

    // --- 2. TÌM KIẾM SẢN PHẨM ---
    $('#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>'); 
                }
            },
            error: function(xhr) {
                $list.html('<div class="text-center text-danger py-3">Lỗi tải dữ liệu</div>');
            }
        });
    }

    // --- 3. GIỎ HÀNG ---
    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;
            let html = `
            <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;">
                            <label class="d-block text-center small text-muted mb-0" style="font-size:9px">Giảm %</label>
                            <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>`;
            $container.append(html);
        });
        renderFooterControls(); calculateTotal(); bindEvents();
    }

    function renderFooterControls() {
        if ($('#footer-controls').length === 0) {
            let percentBtnClass = orderDiscount.type === 'percent' ? 'btn-primary' : 'btn-outline-secondary';
            let html = `
            <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>`;
            $('#cart-list-container').append(html);
        }
    }

    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() { $('#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');
                $('#quick_customer_name').val(''); $('#quick_customer_phone').val('');
                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) }; });
        Swal.fire({ title: 'Tạo đơn Khởi tạo?', icon: 'question', showCancelButton: true, confirmButtonText: 'Lưu Đơn' }).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
                }, function(res) {
                    showProcessing(false);
                    if(res.status === 'success') {
                        Swal.fire({ icon: 'success', title: 'Thành công', text: 'Đã tạo đơn: ' + res.code }).then(() => {
                            cart = []; orderDiscount = {value:0, type:'money'}; renderCart(); updateFloatingBadge();
                            $('#order-note').val(''); window.selectCustomer(1, 'Khách lẻ', 1);
                        });
                    } else { showError(res.message); }
                }, 'json').fail((xhr) => { showProcessing(false); console.log(xhr.responseText); showError('Lỗi kết nối (500)'); });
            }
        });
    });
    
    // --- KÍCH HOẠT TRANG ĐẦU TIÊN ---
    loadPage('create-order');
});