/**
 * Mobile Quick Edit Modal
 * Handles opening and managing the mobile quick edit modal for cart items
 */

// Open Mobile Quick Edit Modal
function openMobileQuickEdit(index) {
    if (typeof cart === 'undefined' || !cart[index]) return;
    
    var item = cart[index];
    
    // Populate modal fields
    $('#mobileEditIndex').val(index);
    $('#mobileEditProductName').text(item.productName);
    $('#mobileEditProductCode').text(item.productCode);
    $('#mobileEditRate').val(item.rate.toFixed(2));
    $('#mobileEditQty').val(item.quantity.toFixed(2));
    $('#mobileEditDiscount').val(item.discount || 0);
    
    // Set discount type radio buttons
    var discType = item.discountType || 'PERCENTAGE';
    if (discType === 'AMOUNT') {
        $('#mobileDiscAmount').prop('checked', true);
        $('#mobileDiscAmount').parent().addClass('active');
        $('#mobileDiscPercentage').parent().removeClass('active');
    } else {
        $('#mobileDiscPercentage').prop('checked', true);
        $('#mobileDiscPercentage').parent().addClass('active');
        $('#mobileDiscAmount').parent().removeClass('active');
    }
    
    // Update modal title and show delete button for existing item
    $('#mobileQuickEditModal .modal-title').html('<i class="fas fa-edit"></i> Quick Edit Item');
    $('#btnMobileDeleteItem').show();
    
    // Calculate and show preview
    updateMobileEditPreview();
    
    // Show modal
    $('#mobileQuickEditModal').modal('show');
}

// Update Mobile Edit Preview
function updateMobileEditPreview() {
    var rate = parseFloat($('#mobileEditRate').val()) || 0;
    var qty = parseFloat($('#mobileEditQty').val()) || 0;
    var discount = parseFloat($('#mobileEditDiscount').val()) || 0;
    var discountType = $('input[name="mobileDiscType"]:checked').val();
    
    var subtotal = rate * qty;
    var discountValue = 0;
    
    if (discount > 0) {
        if (discountType === 'PERCENTAGE') {
            discountValue = (subtotal * discount) / 100;
        } else {
            discountValue = discount;
        }
    }
    
    var total = subtotal - discountValue;
    
    $('#mobileEditSubtotal').text('₹' + subtotal.toFixed(2));
    $('#mobileEditDiscountValue').text('-₹' + discountValue.toFixed(2));
    $('#mobileEditTotal').text('₹' + total.toFixed(2));
}
