/**
 * Mobile Cart Synchronization
 * Syncs cart table to mobile cards display
 */

// Function to sync cart table to mobile cards
function syncCartToMobileCards() {
    var cartCards = $('#cartCards');
    var cartRows = $('#cartItems tr:not(.empty-cart)');
    
    if (cartRows.length === 0) {
        cartCards.html('<div class="text-center text-muted py-4 empty-cart-cards"><i class="fas fa-shopping-cart fa-3x mb-2"></i><p>Cart is Empty</p></div>');
        return;
    }
    
    var cardsHtml = '';
    cartRows.each(function(index) {
        var row = $(this);
        var cells = row.find('td');
        
        if (cells.length > 0) {
            // Column indices: 0=S.No, 1=Code, 2=Product, 3=BasicRate, 4=Price, 5=Qty, 6=Disc, 7=Total, 8=Action
            var sno = cells.eq(0).text().trim();
            var code = cells.eq(1).text().trim();
            var product = cells.eq(2).clone().find('button').remove().end().text().trim(); // Remove button from product name
            
            // Get price from input field in column 4
            var priceInput = cells.eq(4).find('input.cart-rate-input');
            var price = priceInput.length > 0 ? priceInput.val() : '0';
            
            // Get quantity from input field in column 5
            var qtyInput = cells.eq(5).find('input.cart-qty-input');
            var qty = qtyInput.length > 0 ? qtyInput.val() : '0';
            
            // Get discount text from column 6 - extract percentage if available
            var discText = cells.eq(6).clone().find('small').remove().end().text().trim();
            var discountPercent = '';
            
            // Check if discount contains percentage symbol
            if (discText.includes('%')) {
                // Extract the percentage value
                var percentMatch = discText.match(/([\d.]+)%/);
                if (percentMatch) {
                    discountPercent = parseFloat(percentMatch[1]).toFixed(1) + '%';
                }
            } else if (discText !== '-') {
                // If no percentage, calculate from amount
                var disc = discText.replace(/[^0-9.]/g, '');
                if (disc && parseFloat(disc) > 0 && parseFloat(price) > 0) {
                    var calculatedPercent = ((parseFloat(disc) / parseFloat(price)) * 100).toFixed(1);
                    discountPercent = calculatedPercent + '%';
                }
            }
            
            // Get total from column 7
            var totalCell = cells.eq(7);
            var totalText = totalCell.clone().find('small, strong').remove().end().text().trim();
            var total = totalText.replace(/[^0-9.]/g, '');
            
            // If total is still in strong tag, try to get it
            if (!total || parseFloat(total) === 0) {
                var strongText = totalCell.find('strong').text().trim();
                total = strongText.replace(/[^0-9.]/g, '');
            }
            
            // If still no total, calculate it
            if (!total || parseFloat(total) === 0) {
                total = (parseFloat(price) * parseFloat(qty)).toFixed(2);
            }
            
            // Format for display - Compact: ₹600.00 - 10% X Qty: 1.00 = ₹540.00
            var priceDisplay = price && parseFloat(price) > 0 ? '₹' + parseFloat(price).toFixed(2) : '₹0.00';
            var qtyDisplay = qty && parseFloat(qty) > 0 ? parseFloat(qty).toFixed(2) : '0';
            var totalDisplay = total && parseFloat(total) > 0 ? '₹' + parseFloat(total).toFixed(2) : '₹0.00';
            
            // Build compact line
            var compactLine = '<span class="price-value">' + priceDisplay + '</span>';
            
            if (discountPercent) {
                compactLine += ' <span class="separator">-</span> <span class="discount-value">' + discountPercent + '</span>';
            }
            
            compactLine += ' <span class="separator">X</span> <span class="qty-label">Qty:</span> <span class="qty-value">' + qtyDisplay + '</span>';
            compactLine += ' <span class="separator">=</span> <span class="total-value">' + totalDisplay + '</span>';
            
            cardsHtml += `
                <div class="cart-card-item mobile-editable-card mobile-tap-edit" data-index="${index}">
                    <div class="cart-card-single-line">
                        <div class="cart-card-number">${sno}</div>
                        <div class="cart-card-info">
                            <div class="product-name">${product}</div>
                            <div class="product-details">${compactLine}</div>
                        </div>
                        <button class="btn btn-danger btn-sm cart-card-delete" data-index="${index}" title="Delete" onclick="event.stopPropagation();">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `;
        }
    });
    
    cartCards.html(cardsHtml);
    
    // Attach event handlers to make entire card clickable (opens quick edit modal)
    $('.mobile-editable-card').off('click').on('click', function(e) {
        e.preventDefault();
        var index = $(this).data('index');
        openMobileQuickEdit(index);
    });
    
    // Attach event handlers to delete button (prevent propagation to card click)
    $('.cart-card-delete').off('click').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var index = $(this).data('index');
        // Trigger the delete button in the table
        $('#cartItems tr').eq(index).find('.btn-delete-item').click();
    });
}
