if (window.posJsLoaded) {
    console.warn('pos.js already loaded. Skipping duplicate initialization.');
} else {
    window.posJsLoaded = true;

    var cart = [];
    var productsList = [];

    $(document).ready(function () {
        initPOS();
    });

    function initPOS() {
        bindPOSEvents();
        loadAllProducts();
        renderCart();
    }

    function bindPOSEvents() {
        $(document).off('click.posAddToCart', '.add-to-cart-btn');
        $(document).on('click.posAddToCart', '.add-to-cart-btn', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var productId = parseInt($(this).data('product-id'));
            var product = null;

            for (var i = 0; i < productsList.length; i++) {
                if (parseInt(productsList[i].id) === productId) {
                    product = productsList[i];
                    break;
                }
            }

            if (!product) {
                showPOSError('Product not found. Please reload POS page.');
                return false;
            }

            handleAddToCart(product);
            return false;
        });

        $(document).off('click.posConfirmImei', '#confirmImeiSelect');
        $(document).on('click.posConfirmImei', '#confirmImeiSelect', function () {
            var selected = $('input[name="selectedImei"]:checked');
            if (selected.length === 0) {
                showPOSError('Please select an IMEI number.');
                return;
            }
            var productId = parseInt($('#selectProductId').val());
            var product = null;
            for (var i = 0; i < productsList.length; i++) {
                if (parseInt(productsList[i].id) === productId) {
                    product = productsList[i];
                    break;
                }
            }
            if (!product) {
                showPOSError('Product not found.');
                return;
            }
            var sellingPrice = parseFloat($('#imeiPrice').val()) || 0;
            var imeiId = parseInt(selected.val());
            var imeiNum = selected.data('imei');
            addToCart(product, imeiId, imeiNum, sellingPrice);
            $('#imeiModal').modal('hide');
        });

        $(document).off('click.posRemoveCart', '.remove-cart-item');
        $(document).on('click.posRemoveCart', '.remove-cart-item', function () {
            var index = parseInt($(this).data('index'));
            if (index >= 0 && index < cart.length) {
                cart.splice(index, 1);
                renderCart();
            }
        });

        $(document).off('click.posIncreaseQty', '.increase-qty');
        $(document).on('click.posIncreaseQty', '.increase-qty', function () {
            var index = parseInt($(this).data('index'));
            if (index >= 0 && index < cart.length) {
                if (cart[index].product_type === 'phone') {
                    showPOSError('Phone quantity cannot be changed.');
                    return;
                }
                cart[index].quantity += 1;
                cart[index].total_price = cart[index].quantity * cart[index].selling_price;
                renderCart();
            }
        });

        $(document).off('click.posDecreaseQty', '.decrease-qty');
        $(document).on('click.posDecreaseQty', '.decrease-qty', function () {
            var index = parseInt($(this).data('index'));
            if (index >= 0 && index < cart.length) {
                if (cart[index].product_type === 'phone') {
                    showPOSError('Phone quantity cannot be changed.');
                    return;
                }
                cart[index].quantity -= 1;
                if (cart[index].quantity <= 0) {
                    cart.splice(index, 1);
                } else {
                    cart[index].total_price = cart[index].quantity * cart[index].selling_price;
                }
                renderCart();
            }
        });

        $(document).off('click.posClearCart', '#clearCart');
        $(document).on('click.posClearCart', '#clearCart', function () {
            if (cart.length > 0 && confirm('Clear all items from cart?')) {
                cart = [];
                renderCart();
            }
        });

        $(document).off('submit.posQuickCustomer', '#quickCustomerForm');
        $(document).on('submit.posQuickCustomer', '#quickCustomerForm', function (e) {
            e.preventDefault();
            $.post('/DigiMobiz/ajax/quick_customer.php', $(this).serialize(), function (data) {
                if (data.success) {
                    $('#saleCustomer').append('<option value="' + data.id + '" selected>' + data.name + ' (' + data.phone + ')</option>');
                    $('#quickCustomerModal').modal('hide');
                    $('#quickCustomerForm')[0].reset();
                } else {
                    alert(data.message || 'Error adding customer');
                }
            }, 'json');
        });
    }

    function showLoading() {
        $('#productLoader').show();
        $('#productError').hide();
        $('#productGrid').html('');
    }

    function showError(msg) {
        $('#productLoader').hide();
        $('#productError').text(msg).show();
        $('#productGrid').html('<div class="empty-state col-12"><i class="fas fa-exclamation-triangle"></i><p>' + msg + '</p></div>');
    }

    function showPOSError(msg) {
        alert(msg);
    }

    function loadAllProducts() {
        $('#productSearch').val('');
        $('#categoryFilter').val('');
        $('#typeFilter').val('');
        showLoading();
        $.get('/DigiMobiz/ajax/get_products.php', function (data) {
            renderProducts(data);
        }, 'json').fail(function () {
            showError('Failed to load products. Check server connection.');
        });
    }

    function filterByCategory() {
        var cat = $('#categoryFilter').val();
        var type = $('#typeFilter').val();
        showLoading();
        $.get('/DigiMobiz/ajax/get_products.php', { category_id: cat, type: type }, function (data) {
            renderProducts(data);
        }, 'json').fail(function () {
            showError('Failed to filter products.');
        });
    }

    function searchProduct(query) {
        if (query.length === 0) { loadAllProducts(); return; }
        if (query.length < 2) return;
        showLoading();
        $.get('/DigiMobiz/ajax/search_product.php', { q: query }, function (data) {
            renderProducts(data);
        }, 'json').fail(function () {
            showError('Search failed.');
        });
    }

    function renderProducts(response) {
        $('#productLoader').hide();
        $('#productError').hide();

        if (!response || !response.success) {
            showError(response && response.message ? response.message : 'Failed to load products.');
            return;
        }

        productsList = response.products || [];
        if (productsList.length === 0) {
            $('#productGrid').html('<div class="empty-state col-12"><i class="fas fa-box-open"></i><p>No products available for sale.</p></div>');
            return;
        }

        var html = '';
        for (var i = 0; i < productsList.length; i++) {
            var p = productsList[i];
            var img = p.product_image ? '<img src="/DigiMobiz/' + p.product_image + '" class="img-fluid mb-2" style="max-height:50px;object-fit:contain;" onerror="this.style.display=\'none\'">' : '<div class="py-3 text-muted"><i class="fas fa-mobile-alt fa-2x"></i></div>';
            var isPhone = p.product_type === 'phone';
            var stockLabel = isPhone ? 'Available IMEI' : 'Stock';
            var stockValue = isPhone ? (p.available_imei_count || 0) : (p.current_stock || 0);
            var stockBadge = stockValue > 0 ? '<span class="badge badge-completed">In Stock</span>' : '<span class="badge badge-cancelled">Out of Stock</span>';
            var btnText = isPhone ? 'Select IMEI' : 'Add to Cart';

            html += '<div class="product-item">';
            html += img;
            html += '<div class="product-name">' + escapeHtml(p.product_name) + '</div>';
            if (p.brand_name) html += '<div class="product-meta text-muted small">' + escapeHtml(p.brand_name) + '</div>';
            html += '<div class="product-meta text-muted small">' + escapeHtml(p.sku || p.barcode || '') + '</div>';
            html += '<div class="product-price">' + p.selling_price_formatted + '</div>';
            html += '<div class="product-stock small">' + stockLabel + ': ' + stockValue + ' ' + stockBadge + '</div>';
            html += '<button type="button" class="btn btn-sm btn-primary mt-2 w-100 add-to-cart-btn" data-product-id="' + p.id + '">' + btnText + '</button>';
            html += '</div>';
        }
        $('#productGrid').html(html);
    }

    function handleAddToCart(product) {
        if (!product || !product.id) {
            console.error('Invalid product:', product);
            showPOSError('Invalid product selected.');
            return;
        }

        if (product.product_type === 'phone') {
            var availImei = product.available_imei_count || 0;
            if (availImei < 1) {
                showPOSError('No available IMEI for this phone.');
                return;
            }
            $('#selectProductId').val(product.id);
            $('#selectProductName').text(product.product_name);
            $('#selectSellingPrice').val(product.selling_price);
            $('#imeiPrice').val(product.selling_price);
            loadIMEIList(product.id);
            $('#imeiModal').modal('show');
        } else {
            var availStock = product.current_stock || 0;
            if (availStock < 1) {
                showPOSError('Product is out of stock!');
                return;
            }
            addToCart(product);
        }
    }

    function addToCart(product, imeiId, imeiNumber, overridePrice) {
        if (!product || !product.id) {
            console.error('Invalid product object:', product);
            showPOSError('Invalid product selected.');
            return;
        }

        var productId = parseInt(product.id);
        var productName = product.product_name || '';
        var productType = product.product_type || '';
        var sellingPrice = (overridePrice !== undefined) ? parseFloat(overridePrice) : parseFloat(product.selling_price || 0);
        var costPrice = parseFloat(product.cost_price || 0);
        var currentStock = parseInt(product.current_stock || 0);
        var barcode = product.barcode || '';
        var productCode = product.product_code || '';

        if (!productName) {
            console.error('Missing product_name:', product);
            showPOSError('Product name is missing.');
            return;
        }
        if (isNaN(sellingPrice) || sellingPrice < 0) sellingPrice = 0;

        if (productType === 'phone') {
            if (!imeiId || !imeiNumber) {
                showPOSError('Please select an available IMEI before adding this phone.');
                return;
            }
            for (var i = 0; i < cart.length; i++) {
                if (cart[i].imei_id == imeiId) {
                    showPOSError('This IMEI is already added to cart.');
                    return;
                }
            }
            cart.push({
                product_id: productId,
                product_code: productCode,
                product_name: productName,
                product_type: productType,
                barcode: barcode,
                imei_id: imeiId,
                imei_number: imeiNumber,
                quantity: 1,
                cost_price: costPrice,
                selling_price: sellingPrice,
                discount_amount: 0,
                tax_amount: 0,
                total_price: sellingPrice
            });
        } else {
            var existingItem = null;
            for (var i = 0; i < cart.length; i++) {
                if (cart[i].product_id === productId && !cart[i].imei_id) {
                    existingItem = cart[i];
                    break;
                }
            }
            if (existingItem) {
                var maxStock = currentStock;
                if (existingItem.quantity + 1 > maxStock) {
                    showPOSError('Not enough stock available. Stock: ' + maxStock);
                    return;
                }
                existingItem.quantity += 1;
                existingItem.total_price = existingItem.quantity * existingItem.selling_price;
            } else {
                if (currentStock <= 0) {
                    showPOSError('This product is out of stock.');
                    return;
                }
                cart.push({
                    product_id: productId,
                    product_code: productCode,
                    product_name: productName,
                    product_type: productType,
                    barcode: barcode,
                    imei_id: null,
                    imei_number: null,
                    quantity: 1,
                    cost_price: costPrice,
                    selling_price: sellingPrice,
                    discount_amount: 0,
                    tax_amount: 0,
                    total_price: sellingPrice
                });
            }
        }

        renderCart();
    }

    function loadIMEIList(productId) {
        $.get('/DigiMobiz/ajax/get_imei.php', { product_id: productId }, function (data) {
            var html = '';
            for (var i = 0; i < data.length; i++) {
                html += '<div class="form-check">';
                html += '<input class="form-check-input imei-radio" type="radio" name="selectedImei" value="' + data[i].id + '" data-imei="' + escapeHtml(data[i].imei_number) + '">';
                html += '<label class="form-check-label">' + escapeHtml(data[i].imei_number) + '</label></div>';
            }
            $('#imeiList').html(html || '<p class="text-muted">No available IMEI found</p>');
        }, 'json').fail(function () {
            $('#imeiList').html('<p class="text-danger">Failed to load IMEI list.</p>');
        });
    }

    function renderCart() {
        var html = '';
        var subtotal = 0;
        for (var i = 0; i < cart.length; i++) {
            var item = cart[i];
            var itemName = item.product_name || 'Unknown Product';
            var itemPrice = parseFloat(item.selling_price || 0);
            var itemQty = parseInt(item.quantity || 1);
            var total = itemPrice * itemQty;
            subtotal += total;
            var imeiText = item.imei_number ? '<br><small class="text-muted">IMEI: ' + escapeHtml(item.imei_number) + '</small>' : '';

            html += '<div class="cart-item" data-index="' + i + '">';
            html += '<div class="d-flex justify-content-between align-items-start">';
            html += '<div><strong>' + escapeHtml(itemName) + '</strong>' + imeiText + '</div>';
            html += '<button type="button" class="btn btn-sm btn-danger remove-cart-item" data-index="' + i + '"><i class="fas fa-times"></i></button>';
            html += '</div>';
            html += '<div class="d-flex justify-content-between align-items-center mt-2">';
            html += '<div class="input-group input-group-sm" style="width:100px;">';
            html += '<button class="btn btn-outline-secondary decrease-qty" data-index="' + i + '">-</button>';
            html += '<input type="text" class="form-control text-center" value="' + itemQty + '" readonly style="width:40px;">';
            html += '<button class="btn btn-outline-secondary increase-qty" data-index="' + i + '">+</button></div>';
            html += '<span class="fw-bold">' + total.toFixed(2) + '</span>';
            html += '</div></div>';
        }
        $('#cartItems').html(html || '<p class="text-muted text-center">Cart is empty</p>');
        $('#cartSubtotal').text(subtotal.toFixed(2));
        $('#cartCount').text(cart.length);
        updatePosTotals();
    }

    function updatePosTotals() {
        var subtotal = 0;
        for (var i = 0; i < cart.length; i++) {
            subtotal += parseFloat(cart[i].selling_price || 0) * parseInt(cart[i].quantity || 1);
        }

        var discountType = $('#discountType').val();
        var discountVal = parseFloat($('#discountValue').val()) || 0;
        var taxType = $('#taxType').val();
        var taxVal = parseFloat($('#taxValue').val()) || 0;

        var discountAmt = discountType === 'Percentage' ? (subtotal * discountVal / 100) : discountVal;
        if (discountAmt > subtotal) discountAmt = subtotal;
        var afterDiscount = subtotal - discountAmt;
        var taxAmt = taxType === 'Percentage' ? (afterDiscount * taxVal / 100) : taxVal;
        var total = afterDiscount + taxAmt;

        var paid = parseFloat($('#salePaidAmount').val()) || 0;
        var balance = total - paid;

        $('#posDiscount').text(discountAmt.toFixed(2));
        $('#posTax').text(taxAmt.toFixed(2));
        $('#posTotal').text(total.toFixed(2));
        $('#posBalance').text(balance.toFixed(2));
    }

    function saveSale() {
        if (cart.length === 0) { showPOSError('Cart is empty!'); return; }

        var subtotal = 0;
        var itemsValid = true;
        for (var i = 0; i < cart.length; i++) {
            var item = cart[i];
            if (parseFloat(item.selling_price || 0) <= 0) {
                showPOSError('Price must be greater than 0 for: ' + (item.product_name || 'Unknown'));
                itemsValid = false;
                return;
            }
            subtotal += parseFloat(item.selling_price || 0) * parseInt(item.quantity || 1);
        }
        if (!itemsValid) return;

        var customerId = $('#saleCustomer').val();
        var discountType = $('#discountType').val();
        var discountValue = parseFloat($('#discountValue').val()) || 0;
        var taxType = $('#taxType').val();
        var taxValue = parseFloat($('#taxValue').val()) || 0;
        var paymentMethod = $('#salePaymentMethod').val();
        var paidAmount = parseFloat($('#salePaidAmount').val()) || 0;

        var discountAmt = discountType === 'Percentage' ? (subtotal * discountValue / 100) : discountValue;
        if (discountAmt > subtotal) discountAmt = subtotal;
        var afterDiscount = subtotal - discountAmt;
        var taxAmt = taxType === 'Percentage' ? (afterDiscount * taxValue / 100) : taxValue;
        var total = afterDiscount + taxAmt;

        if (paidAmount > total) {
            if (!confirm('Paid amount (' + paidAmount.toFixed(2) + ') exceeds total (' + total.toFixed(2) + '). Continue?')) {
                return;
            }
        }

        var data = {
            customer_id: customerId || '',
            discount_type: discountType,
            discount_value: discountValue,
            tax_type: taxType,
            tax_value: taxValue,
            payment_method: paymentMethod,
            paid_amount: paidAmount,
            items: cart
        };

        $.ajax({
            url: '/DigiMobiz/pos/save_sale.php',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            dataType: 'json',
            success: function (result) {
                if (result.success) {
                    alert('Invoice #' + result.invoice_no + ' saved successfully!');
                    cart = [];
                    renderCart();
                    $('#salePaidAmount').val(0);
                    $('#discountValue').val(0);
                    $('#taxValue').val(0);
                    if (result.invoice_id) {
                        window.open('/DigiMobiz/pos/invoice.php?id=' + result.invoice_id, '_blank');
                    }
                } else {
                    alert(result.message || 'Error saving sale.');
                }
            },
            error: function (xhr, status, error) {
                alert('Error saving sale. Please try again. (' + error + ')');
            }
        });
    }

    function saveAndPrint() {
        saveSale();
    }

    function holdSale() {
        if (cart.length === 0) { showPOSError('Cart is empty!'); return; }
        if (confirm('Hold current sale? You can resume later.')) {
            $.post('/DigiMobiz/pos/hold_sale.php', {
                items: cart,
                customer_id: $('#saleCustomer').val(),
                discount_type: $('#discountType').val(),
                discount_value: $('#discountValue').val(),
                tax_type: $('#taxType').val(),
                tax_value: $('#taxValue').val()
            }, function (result) {
                if (result.success) {
                    alert('Sale held successfully.');
                    cart = [];
                    renderCart();
                } else {
                    alert('Error holding sale.');
                }
            }, 'json');
        }
    }

    function escapeHtml(text) {
        if (text === null || text === undefined) return '';
        return String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
}
