// JavaScript for handling Shop Rate and Wholesale Rate functionality

$(document).ready(function() {
    
    // Auto-calculate rates based on sales price
    function calculateRatesFromSalesPrice() {
        var salesPrice = parseFloat($('#sales_price').val()) || 0;
        var shopRate = parseFloat($('#shop_rate').val()) || 0;
        var wholesaleRate = parseFloat($('#wholesale_rate').val()) || 0;
        
        // Auto-suggest rates if they're empty and sales price is set
        if (salesPrice > 0) {
            if (shopRate === 0) {
                // Suggest shop rate 10% higher than sales price
                $('#shop_rate').attr('placeholder', 'Suggested: ' + (salesPrice * 1.10).toFixed(2));
            }
            if (wholesaleRate === 0) {
                // Suggest wholesale rate 5% lower than sales price
                $('#wholesale_rate').attr('placeholder', 'Suggested: ' + (salesPrice * 0.95).toFixed(2));
            }
        }
    }
    
    // Modal version of the function
    function calculateModalRatesFromSalesPrice() {
        var salesPrice = parseFloat($('#m_sales_price').val()) || 0;
        var shopRate = parseFloat($('#m_shop_rate').val()) || 0;
        var wholesaleRate = parseFloat($('#m_wholesale_rate').val()) || 0;
        
        if (salesPrice > 0) {
            if (shopRate === 0) {
                $('#m_shop_rate').attr('placeholder', 'Suggested: ' + (salesPrice * 1.10).toFixed(2));
            }
            if (wholesaleRate === 0) {
                $('#m_wholesale_rate').attr('placeholder', 'Suggested: ' + (salesPrice * 0.95).toFixed(2));
            }
        }
    }
    
    // Validate that wholesale rate is not higher than sales price
    function validateRates() {
        var salesPrice = parseFloat($('#sales_price').val()) || 0;
        var shopRate = parseFloat($('#shop_rate').val()) || 0;
        var wholesaleRate = parseFloat($('#wholesale_rate').val()) || 0;
        
        // Clear previous validations
        $('.rate-validation').remove();
        
        if (wholesaleRate > salesPrice && wholesaleRate > 0 && salesPrice > 0) {
            $('#wholesale_rate').after('<span class="rate-validation text-danger"><br><small>Warning: Wholesale rate is higher than sales price</small></span>');
        }
        
        if (shopRate < salesPrice && shopRate > 0 && salesPrice > 0) {
            $('#shop_rate').after('<span class="rate-validation text-warning"><br><small>Note: Shop rate is lower than sales price</small></span>');
        }
    }
    
    // Modal version of validation
    function validateModalRates() {
        var salesPrice = parseFloat($('#m_sales_price').val()) || 0;
        var shopRate = parseFloat($('#m_shop_rate').val()) || 0;
        var wholesaleRate = parseFloat($('#m_wholesale_rate').val()) || 0;
        
        $('.modal-rate-validation').remove();
        
        if (wholesaleRate > salesPrice && wholesaleRate > 0 && salesPrice > 0) {
            $('#m_wholesale_rate').after('<span class="modal-rate-validation text-danger"><br><small>Warning: Wholesale rate is higher than sales price</small></span>');
        }
        
        if (shopRate < salesPrice && shopRate > 0 && salesPrice > 0) {
            $('#m_shop_rate').after('<span class="modal-rate-validation text-warning"><br><small>Note: Shop rate is lower than sales price</small></span>');
        }
    }
    
    // Auto-fill suggested rates
    function autoFillSuggestedRates() {
        var salesPrice = parseFloat($('#sales_price').val()) || 0;
        
        if (salesPrice > 0) {
            if (!$('#shop_rate').val()) {
                $('#shop_rate').val((salesPrice * 1.10).toFixed(2));
            }
            if (!$('#wholesale_rate').val()) {
                $('#wholesale_rate').val((salesPrice * 0.95).toFixed(2));
            }
        }
    }
    
    // Modal version of auto-fill
    function autoFillModalSuggestedRates() {
        var salesPrice = parseFloat($('#m_sales_price').val()) || 0;
        
        if (salesPrice > 0) {
            if (!$('#m_shop_rate').val()) {
                $('#m_shop_rate').val((salesPrice * 1.10).toFixed(2));
            }
            if (!$('#m_wholesale_rate').val()) {
                $('#m_wholesale_rate').val((salesPrice * 0.95).toFixed(2));
            }
        }
    }
    
    // Event listeners for main form
    $('#sales_price').on('keyup blur', function() {
        calculateRatesFromSalesPrice();
        validateRates();
    });
    
    $('#shop_rate, #wholesale_rate').on('keyup blur', function() {
        validateRates();
    });
    
    // Event listeners for modal form
    $('#m_sales_price').on('keyup blur', function() {
        calculateModalRatesFromSalesPrice();
        validateModalRates();
    });
    
    $('#m_shop_rate, #m_wholesale_rate').on('keyup blur', function() {
        validateModalRates();
    });
    
    // Add button to auto-fill suggested rates
    if ($('#sales_price').length) {
        $('#sales_price').after('<button type="button" class="btn btn-sm btn-outline-secondary ml-2" id="auto-fill-rates" title="Auto-fill suggested rates"><i class="fa fa-magic"></i></button>');
        
        $('#auto-fill-rates').on('click', function() {
            autoFillSuggestedRates();
            validateRates();
            toastr.success('Suggested rates filled automatically');
        });
    }
    
    // Modal auto-fill button
    if ($('#m_sales_price').length) {
        $('#m_sales_price').after('<button type="button" class="btn btn-sm btn-outline-secondary ml-2" id="modal-auto-fill-rates" title="Auto-fill suggested rates"><i class="fa fa-magic"></i></button>');
        
        $('#modal-auto-fill-rates').on('click', function() {
            autoFillModalSuggestedRates();
            validateModalRates();
            toastr.success('Suggested rates filled automatically');
        });
    }
    
    // Format currency on focus out
    $('.only_currency').on('blur', function() {
        var value = parseFloat($(this).val());
        if (!isNaN(value)) {
            $(this).val(value.toFixed(2));
        }
    });
    
    // Add visual indicators for rate relationships
    function updateRateIndicators() {
        var salesPrice = parseFloat($('#sales_price').val()) || 0;
        var shopRate = parseFloat($('#shop_rate').val()) || 0;
        var wholesaleRate = parseFloat($('#wholesale_rate').val()) || 0;
        
        // Remove existing indicators
        $('.rate-indicator').remove();
        
        if (salesPrice > 0) {
            if (shopRate > salesPrice) {
                $('#shop_rate').after('<span class="rate-indicator higher">+' + ((shopRate - salesPrice)/salesPrice * 100).toFixed(1) + '%</span>');
            } else if (shopRate < salesPrice && shopRate > 0) {
                $('#shop_rate').after('<span class="rate-indicator lower">-' + ((salesPrice - shopRate)/salesPrice * 100).toFixed(1) + '%</span>');
            }
            
            if (wholesaleRate < salesPrice && wholesaleRate > 0) {
                $('#wholesale_rate').after('<span class="rate-indicator lower">-' + ((salesPrice - wholesaleRate)/salesPrice * 100).toFixed(1) + '%</span>');
            } else if (wholesaleRate > salesPrice) {
                $('#wholesale_rate').after('<span class="rate-indicator higher">+' + ((wholesaleRate - salesPrice)/salesPrice * 100).toFixed(1) + '%</span>');
            }
        }
    }
    
    // Update indicators when values change
    $('#sales_price, #shop_rate, #wholesale_rate').on('keyup blur', function() {
        updateRateIndicators();
    });
    
    // Initialize on page load
    calculateRatesFromSalesPrice();
    validateRates();
    updateRateIndicators();
});

// Function to get rate by type (for POS integration)
function getItemRateByType(itemId, rateType) {
    // This function can be called from POS to get different rates
    // rateType can be 'sales', 'shop', or 'wholesale'
    var baseUrl = $('#base_url').val();
    
    return $.post(baseUrl + 'items/get_item_rate', {
        item_id: itemId,
        rate_type: rateType
    });
}
