/**
 * Mobile Product Search Functions
 * Handles mobile product search, display results, and quick add functionality
 */

// Search Products Function
function searchMobileProducts(searchTerm) {
    $.ajax({
        url: 'api/search-product.php',
        method: 'POST',
        data: { 
            query: searchTerm
        },
        dataType: 'json',
        success: function(response) {
            if (response.success && response.products && response.products.length > 0) {
                displayMobileSearchResults(response.products);
            } else {
                $('#mobileSearchResults').html(
                    '<div class="mobile-search-empty">' +
                    '<i class="fas fa-box-open"></i>' +
                    '<p>No products found</p>' +
                    '</div>'
                );
            }
        },
        error: function(xhr, status, error) {
            console.error('Search error:', error);
            $('#mobileSearchResults').html(
                '<div class="mobile-search-empty">' +
                '<i class="fas fa-exclamation-triangle"></i>' +
                '<p>Error searching products</p>' +
                '</div>'
            );
        }
    });
}

// Display Search Results
function displayMobileSearchResults(products) {
    var html = '';
    
    products.forEach(function(product) {
        var stockClass = '';
        var stockText = '';
        var stock = parseFloat(product.CurrentStock) || 0;
        
        if (stock <= 0) {
            stockClass = 'out-of-stock';
            stockText = 'Out of Stock';
        } else if (product.isLowStock) {
            stockClass = 'low-stock';
            stockText = 'Stock: ' + stock;
        } else {
            stockClass = 'in-stock';
            stockText = 'Stock: ' + stock;
        }
        
        var price = parseFloat(product.Rate) || parseFloat(product.SalesPrice) || 0;
        
        html += '<div class="mobile-product-item" data-product-id="' + product.ID + '" ' +
                'data-product-code="' + (product.ProductCode || '') + '" ' +
                'data-product-name="' + product.ProductName + '" ' +
                'data-product-price="' + price + '" ' +
                'data-product-stock="' + stock + '">' +
                '<div class="mobile-product-info">' +
                '<div class="mobile-product-name">' + product.ProductName + '</div>' +
                '<div class="mobile-product-details">' +
                '<span class="mobile-product-code">' + (product.ProductCode || 'N/A') + '</span>' +
                '<span class="mobile-product-stock ' + stockClass + '">' + stockText + '</span>' +
                '</div>' +
                '</div>' +
                '<div class="mobile-product-price">₹' + price.toFixed(2) + '</div>' +
                '</div>';
    });
    
    $('#mobileSearchResults').html(html);
    
    // Attach click handlers to open mobile quick add modal
    $('.mobile-product-item').on('click', function() {
        var productId = $(this).data('product-id');
        var productCode = $(this).data('product-code');
        var productName = $(this).data('product-name');
        var productPrice = parseFloat($(this).data('product-price')) || 0;
        var productStock = parseFloat($(this).data('product-stock')) || 0;
        
        openMobileQuickAdd(productId, productCode, productName, productPrice, productStock);
    });
}

// Open Mobile Quick Add Modal (for new items from search)
function openMobileQuickAdd(productId, productCode, productName, productPrice, productStock) {
    // Store product data temporarily
    window.tempMobileProduct = {
        id: productId,
        code: productCode,
        name: productName,
        price: productPrice,
        stock: productStock
    };
    
    // Close search modal
    $('#mobileProductSearchModal').modal('hide');
    
    // Wait for search modal to close, then open quick edit modal
    setTimeout(function() {
        // Populate modal fields with product data
        $('#mobileEditIndex').val(-1); // -1 indicates new item
        $('#mobileEditProductName').text(productName);
        $('#mobileEditProductCode').text(productCode);
        $('#mobileEditRate').val(productPrice.toFixed(2));
        $('#mobileEditQty').val(1);
        $('#mobileEditDiscount').val(0);
        
        // Set discount type to percentage by default
        $('#mobileDiscPercentage').prop('checked', true);
        $('#mobileDiscPercentage').parent().addClass('active');
        $('#mobileDiscAmount').parent().removeClass('active');
        
        // Update modal title and hide delete button for new item
        $('#mobileQuickEditModal .modal-title').html('<i class="fas fa-plus-circle"></i> Add Item to Cart');
        $('#btnMobileDeleteItem').hide();
        
        // Calculate and show preview
        updateMobileEditPreview();
        
        // Show modal
        $('#mobileQuickEditModal').modal('show');
        
        // Focus on quantity
        setTimeout(function() {
            $('#mobileEditQty').focus().select();
        }, 300);
    }, 300);
}

// Select Product from Mobile Search (old function - kept for compatibility)
function selectMobileProduct(productId) {
    // Close modal
    $('#mobileProductSearchModal').modal('hide');
    
    // Clear search input
    $('#mobileSearchInput').val('');
    $('#mobileSearchResults').html(
        '<div class="mobile-search-empty">' +
        '<i class="fas fa-search"></i>' +
        '<p>Type to search for products</p>' +
        '</div>'
    );
    
    // Fetch and load the product
    $.ajax({
        url: 'api/get-product.php',
        method: 'POST',
        data: { productId: productId },
        dataType: 'json',
        success: function(response) {
            if (response.success && response.product) {
                var product = response.product;
                
                // Populate product fields
                $('#productId').val(product.ID);
                $('#productCode').val(product.ProductCode || product.ItemCode);
                $('#productName').val(product.ProductName || product.ItemName);
                $('#rate').val(product.Rate || product.SalesPrice || product.Price);
                $('#rateMobile').val(product.Rate || product.SalesPrice || product.Price);
                $('#currentStock').text(product.CurrentStock || 0);
                $('#quantity').val(1).focus();
                $('#quantityMobile').val(1);
                
                // Store available prices if they exist
                if (product.MRP || product.ShopRate || product.WholesaleRate) {
                    var prices = {
                        MRP: product.MRP,
                        SalesPrice: product.SalesPrice,
                        ShopRate: product.ShopRate,
                        WholesaleRate: product.WholesaleRate
                    };
                    $('#availablePrices').val(JSON.stringify(prices));
                }
                
                // Calculate total if function exists
                if (typeof calculateCurrentItemTotal === 'function') {
                    calculateCurrentItemTotal();
                }
            }
        },
        error: function() {
            MsgBox.alert('Error loading product details');
        }
    });
}
