$(document).ready(function() {
    let cart = [];
    let selectedCustomer = { id: 1, label: 'Khách lẻ' };
    let isProcessing = false;
    let searchTimeout;

    const customerSelectModalEl = document.getElementById('customerSelectModal');
    const customerAddModalEl = document.getElementById('customerAddModal');
    const notificationModalEl = document.getElementById('notificationModal');

    if (!customerSelectModalEl || !customerAddModalEl || !notificationModalEl) {
        return;
    }
    
    const customerSelectModal = new bootstrap.Modal(customerSelectModalEl);
    const customerAddModal = new bootstrap.Modal(customerAddModalEl);
    const notificationModal = new bootstrap.Modal(notificationModalEl);

    function showProcessingOverlay(show) {
        let overlay = $('#processing-overlay');
        isProcessing = show;
        if (show) {
            if (overlay.length === 0) {
                $('body').append('<div id="processing-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;align-items:center;justify-content:center;"><div class="spinner-border text-light"></div></div>');
            }
            overlay.fadeIn(100);
        } else {
            overlay.fadeOut(100);
        }
    }

    function showNotification(message, type = 'info') {
        const modal = $('#notificationModal');
        modal.find('.modal-title').text(type === 'success' ? 'Thành công' : (type === 'error' ? 'Lỗi' : 'Thông báo'));
        modal.find('.modal-body').text(message);
        notificationModal.show();
    }
    
    function loadPage(pageName, callback) {
        if(isProcessing) return;
        let url = `/quanlybanhang/modules/pos/tabs/${pageName}_tab.php`;
        $('#main-content').load(url, function(response, status, xhr) {
            if (status === "error") { 
                $(this).html("<p class='text-center text-danger p-3'>Lỗi tải trang.</p>"); 
                return;
            }
            if (callback) callback();
        });
        $('.nav-item').removeClass('active');
        $(`.nav-item[data-page="${pageName}"]`).addClass('active');
    }
    
    function initProductsPage() { fetchProducts(''); }
    function initCartPage() { renderCart(); }
    function initInvoicesPage() { }
    function initProfitPage() { }

    function fetchProducts(term = '') {
        $.getJSON('/quanlybanhang/ajax/pos_mobile_search_products_ajax.php', { term: term }, function(response) {
            window.productStore = {};
            let html = '';
            if (response.data && response.data.length) {
                response.data.forEach(p => {
                    window.productStore[p.id] = p;
                    html += `<div class="product-list-item" data-product-id="${p.id}"><div class="product-details"><div class="prd-name">${p.name}</div><div class="prd-sub-info">Tồn: <b>${p.stock}</b></div><div class="prd-price">${(p.sell_price || 0).toLocaleString('vi-VN')} đ</div></div></div>`;
                });
            } else { 
                html = '<p class="text-center p-3">Không tìm thấy sản phẩm.</p>';
            }
            $('#product-list-container').html(html);
        });
    }

    function addToCart(productId) {
        const product = window.productStore[productId];
        if (!product || product.stock <= 0) { showNotification('Sản phẩm đã hết hàng.', 'warning'); return; }
        const existingItem = cart.find(item => item.id === productId);
        if (existingItem) {
            if (existingItem.quantity < product.stock) { existingItem.quantity++; } 
            else { showNotification('Số lượng đã đạt tồn kho tối đa!', 'warning'); }
        } else {
            cart.push({ id: product.id, name: product.name, quantity: 1, price: product.sell_price, origin_price: product.cost_price, stock: product.stock });
        }
        showCartBadge();
    }

    function renderCart() {
        const container = $('#cart-items-container');
        if (!container.length) return;

        const orderButton = $('#btn-create-order');
        $('#customer-name-display').text(selectedCustomer.label);

        if (!cart.length) {
            container.html('<div class="text-center p-5"><i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i><p>Chưa có sản phẩm.</p></div>');
            $('#cart-total-amount').text('0 đ');
            orderButton.prop('disabled', true);
            return;
        }

        let html = ''; 
        let totalAmount = 0;
        let hasInvalidPrice = false;

        cart.forEach(item => {
            totalAmount += (item.price || 0) * (item.quantity || 0);
            const isInvalid = (item.price || 0) < (item.origin_price || 0);
            if (isInvalid) { hasInvalidPrice = true; }
            const priceClass = isInvalid ? 'is-invalid' : '';

            html += `<div class="order-item-card"><div class="order-item-name">${item.name}</div><div class="item-sub-info">Vốn: ${(item.origin_price || 0).toLocaleString('vi-VN')} | Tồn: ${item.stock}</div><div class="order-item-main"><input type="number" class="form-control form-control-sm price-input ${priceClass}" value="${item.price}" data-id="${item.id}"><div class="quantity-stepper"><button class="btn btn-outline-secondary btn-sm btn-quantity-minus" data-id="${item.id}">-</button><input type="number" class="form-control form-control-sm quantity-input" value="${item.quantity}" data-id="${item.id}"><button class="btn btn-outline-secondary btn-sm btn-quantity-plus" data-id="${item.id}">+</button></div></div></div>`;
        });

        container.html(html);
        $('#cart-total-amount').text(totalAmount.toLocaleString('vi-VN') + ' đ');
        
        orderButton.prop('disabled', hasInvalidPrice);
    }

    function showCartBadge() {
        const count = cart.reduce((sum, item) => sum + item.quantity, 0);
        const badge = $('.nav-item[data-page="cart"] .cart-badge');
        count > 0 ? badge.text(count).removeClass('d-none') : badge.addClass('d-none');
    }
    
    function updateCartItemQuantity(productId, newQty) {
        const item = cart.find(i => i.id === productId);
        if (!item) return;
        const qty = parseInt(newQty);
        if (isNaN(qty) || qty <= 0) {
             cart = cart.filter(p => p.id !== productId);
        } else if (qty > item.stock) {
            showNotification(`Tồn kho chỉ còn ${item.stock}.`, 'warning');
            item.quantity = item.stock;
        } else {
            item.quantity = qty;
        }
        renderCart();
        showCartBadge();
    }
    
    function handlePriceChange(productId, newPriceStr) {
        const item = cart.find(i => i.id === productId);
        if (!item) return;
        const newPrice = parseFloat(newPriceStr);
        item.price = isNaN(newPrice) ? 0 : newPrice;
        renderCart();
    }

    function createOrder() {
        if (isProcessing || cart.length === 0 || $('#btn-create-order').is(':disabled')) return;
        showProcessingOverlay(true);
        const orderToken = $('#cart-page-container').data('order-token');
        if (!orderToken) {
            showNotification('Lỗi phiên làm việc. Vui lòng tải lại trang.', 'error');
            showProcessingOverlay(false);
            return;
        }
        
        $.ajax({
            url: '/quanlybanhang/ajax/pos_mobile_create_order_ajax.php', 
            type: 'POST',
            data: { customer_id: selectedCustomer.id, cart_items: JSON.stringify(cart), order_token: orderToken },
            dataType: 'json',
            success: function(response) {
                showNotification(response.message, 'success');
                cart = [];
                selectedCustomer = { id: 1, label: 'Khách lẻ' };
                showCartBadge();
                setTimeout(() => loadPage('products', initProductsPage), 1500);
            },
            error: function(xhr) {
                showNotification(xhr.responseJSON?.message || 'Lỗi không xác định khi tạo đơn.', 'error');
                loadPage('cart', renderCart);
            },
            complete: function() {
                showProcessingOverlay(false);
            }
        });
    }

    function saveNewCustomer() {
        if(isProcessing) return;
        const form = $('#add-customer-form');
        if (!form.find('input[name="customer_name"]').val()) {
            showNotification('Vui lòng nhập tên khách hàng.', 'warning');
            return;
        }
        showProcessingOverlay(true);
        $.ajax({
            url: '/quanlybanhang/ajax/pos_create_customer_ajax.php',
            type: 'POST', data: form.serialize(), dataType: 'json',
            success: function(response) {
                selectedCustomer = response.newCustomer;
                customerAddModal.hide();
                form[0].reset();
                renderCart();
            },
            error: function(xhr) {
                showNotification(xhr.responseJSON?.message || 'Lỗi khi thêm khách hàng.', 'error');
            },
            complete: function() {
                showProcessingOverlay(false);
            }
        });
    }
    
    function fetchCustomersAndShowModal(term = '') {
        $.getJSON('/quanlybanhang/ajax/pos_customers_search_ajax.php', {term: term}, function(data) {
            let html = data?.length ? data.map(c => `<a href="#" class="list-group-item list-group-item-action customer-select-item" data-id="${c.id}" data-label="${c.label}">${c.label}</a>`).join('') : '<p class="text-center p-3">Không có khách hàng</p>';
            $('#customer-list').html(html);
        });
    }

    const mainContent = $('#main-content');
    
    $('.bottom-nav').on('click', '.nav-item', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if ($(this).hasClass('active') || isProcessing || !page) return;
        
        const initializers = { 
            'products': initProductsPage, 
            'cart': initCartPage,
            'invoices': initInvoicesPage,
            'profit': initProfitPage
        };
        
        if (initializers[page]) {
            loadPage(page, initializers[page]);
        }
    });

    mainContent.on('keyup', '#product-search-input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => fetchProducts($(this).val()), 300);
    });

    mainContent.on('submit', '#invoice-filter-form', function(e) {
        e.preventDefault();
        if (isProcessing) return;
        const fromDate = $(this).find('input[name="from"]').val();
        const toDate = $(this).find('input[name="to"]').val();
        const url = `/quanlybanhang/modules/pos/tabs/invoices_tab.php?from=${fromDate}&to=${toDate}`;
        mainContent.html('<div class="text-center p-5"><div class="spinner-border" role="status"></div></div>');
        mainContent.load(url);
    });

    mainContent.on('click', '.product-list-item', function() { addToCart($(this).data('product-id')); });
    mainContent.on('click', '#customer-info-button', function() { fetchCustomersAndShowModal(''); customerSelectModal.show(); });
    mainContent.on('click', '.btn-quantity-plus', function(){ const id=$(this).data('id'); updateCartItemQuantity(id, (cart.find(i=>i.id===id)?.quantity || 0) + 1) });
    mainContent.on('click', '.btn-quantity-minus', function(){ const id=$(this).data('id'); updateCartItemQuantity(id, (cart.find(i=>i.id===id)?.quantity || 0) - 1) });
    mainContent.on('change', '.quantity-input', function(){ updateCartItemQuantity($(this).data('id'), $(this).val()) });
    mainContent.on('change', '.price-input', function(){ handlePriceChange($(this).data('id'), $(this).val()) });
    mainContent.on('click', '#btn-create-order', createOrder);
    
    $(customerSelectModalEl).on('keyup', '#customer-search-input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => fetchCustomersAndShowModal($(this).val()), 300);
    });
    $(customerSelectModalEl).on('click', '.customer-select-item', function(e) {
        e.preventDefault();
        selectedCustomer = { id: $(this).data('id'), label: $(this).data('label') };
        customerSelectModal.hide();
        renderCart();
    });
    $(customerSelectModalEl).on('click', '#btn-show-add-customer-modal', function() {
        customerSelectModal.hide();
        customerAddModal.show();
    });
    $(customerAddModalEl).on('click', '#btn-back-to-select-customer', function() {
        customerAddModal.hide();
        customerSelectModal.show();
    });
    $(customerAddModalEl).on('click', '#btn-save-new-customer', saveNewCustomer);
    
    loadPage('products', initProductsPage);
});