// POS Rate Management JavaScript Functions

$(document).ready(function() {
    
    // Initialize rate type selector with default value
    if (!$("#rate_type_selector").val()) {
        $("#rate_type_selector").val('sales');
    }
    
    // Add visual indicator for current rate type
    updateRateTypeIndicator();
    
    // Add tooltips to rate selector
    $("#rate_type_selector").attr('title', 'Select pricing mode for new items added to cart');
    
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
});

// Function to update rate type visual indicator
function updateRateTypeIndicator() {
    var rateType = $("#rate_type_selector").val();
    var indicatorText = '';
    var indicatorColor = '';
    
    switch(rateType) {
        case 'sales':
            indicatorText = 'S';
            indicatorColor = '#28a745';
            break;
        case 'shop':
            indicatorText = 'R';
            indicatorColor = '#007bff';
            break;
        case 'wholesale':
            indicatorText = 'W';
            indicatorColor = '#ffc107';
            break;
    }
    
    // Remove existing indicator
    $('.rate-type-indicator').remove();
    
    // Add new indicator
    $("#rate_type_selector").parent().css('position', 'relative').append(
        '<div class="rate-type-indicator" style="background: ' + indicatorColor + '">' + indicatorText + '</div>'
    );
}

// Enhanced updateCartRates function with better error handling and feedback
function updateCartRates() {
    var new_rate_type = $("#rate_type_selector").val();
    var rowcount = $("#hidden_rowcount").val();
    var updated_items = 0;
    var failed_items = 0;
    
    if (!rowcount || rowcount == 0) {
        toastr.info("No items in cart to update");
        updateRateTypeIndicator();
        return;
    }
    
    // Show loading indicator
    var loadingToast = toastr.info("Updating prices...", "", {timeOut: 0, extendedTimeOut: 0});
    
    for(var i = 0; i < rowcount; i++) {
        if(document.getElementById('tr_item_id_'+i)) {
            try {
                // Get stored rates for this item
                var all_rates_str = $("#tr_all_rates_"+i).val();
                if(all_rates_str) {
                    var all_rates = JSON.parse(all_rates_str);
                    var new_price;
                    var rate_name = '';
                    
                    // Select appropriate rate
                    switch(new_rate_type) {
                        case 'shop':
                            new_price = (all_rates.shop && all_rates.shop != '0' && all_rates.shop != 'null') ? all_rates.shop : all_rates.sales;
                            rate_name = 'Shop Rate';
                            break;
                        case 'wholesale':
                            new_price = (all_rates.wholesale && all_rates.wholesale != '0' && all_rates.wholesale != 'null') ? all_rates.wholesale : all_rates.sales;
                            rate_name = 'Wholesale Rate';
                            break;
                        default:
                            new_price = all_rates.sales;
                            rate_name = 'Sales Rate';
                    }
                    
                    // Validate price
                    if (!new_price || isNaN(new_price) || new_price <= 0) {
                        new_price = all_rates.sales; // Fallback to sales price
                    }
                    
                    // Update the price input field
                    $("#sales_price_"+i).val(to_Fixed(new_price));
                    
                    // Update the rate type for this row
                    $("#tr_rate_type_"+i).val(new_rate_type);
                    
                    // Visual feedback - highlight the updated row
                    $("#row_"+i).addClass('alert-info').delay(2000).queue(function() {
                        $(this).removeClass('alert-info').dequeue();
                    });
                    
                    // Recalculate subtotal for this item
                    var item_id = $("#tr_item_id_"+i).val();
                    make_subtotal(item_id, i);
                    
                    updated_items++;
                    
                } else {
                    failed_items++;
                    console.log("No rate data found for row " + i);
                }
            } catch(e) {
                failed_items++;
                console.log("Error updating rates for row " + i + ": " + e.message);
            }
        }
    }
    
    // Clear loading toast
    toastr.clear(loadingToast);
    
    // Update visual indicator
    updateRateTypeIndicator();
    
    // Show result notification
    if (updated_items > 0) {
        var message = "Updated " + updated_items + " item(s) to " + 
                     new_rate_type.charAt(0).toUpperCase() + new_rate_type.slice(1) + " Rate";
        if (failed_items > 0) {
            message += " (" + failed_items + " failed)";
        }
        toastr.success(message);
    } else {
        toastr.warning("No items were updated");
    }
}

// Function to get display name for rate type
function getRateTypeDisplayName(rateType) {
    switch(rateType) {
        case 'shop':
            return 'Shop Rate';
        case 'wholesale':
            return 'Wholesale Rate';
        case 'sales':
        default:
            return 'Sales Rate';
    }
}

// Function to validate if rate exists for item
function hasValidRate(all_rates, rate_type) {
    if (!all_rates) return false;
    
    switch(rate_type) {
        case 'shop':
            return all_rates.shop && all_rates.shop != '0' && all_rates.shop != 'null' && !isNaN(all_rates.shop);
        case 'wholesale':
            return all_rates.wholesale && all_rates.wholesale != '0' && all_rates.wholesale != 'null' && !isNaN(all_rates.wholesale);
        case 'sales':
        default:
            return all_rates.sales && all_rates.sales != '0' && all_rates.sales != 'null' && !isNaN(all_rates.sales);
    }
}

// Function to show rate information for debugging
function showRateInfo() {
    var rowcount = $("#hidden_rowcount").val();
    console.log("=== CART RATE INFORMATION ===");
    
    for(var i = 0; i < rowcount; i++) {
        if(document.getElementById('tr_item_id_'+i)) {
            var item_id = $("#tr_item_id_"+i).val();
            var item_name = $("#td_data_"+i+"_0").text();
            var all_rates_str = $("#tr_all_rates_"+i).val();
            var current_price = $("#sales_price_"+i).val();
            var current_rate_type = $("#tr_rate_type_"+i).val();
            
            console.log("Row " + i + " - " + item_name + ":");
            console.log("  Current Rate Type: " + current_rate_type);
            console.log("  Current Price: " + current_price);
            console.log("  All Rates: " + all_rates_str);
        }
    }
    
    console.log("Selected Rate Type: " + $("#rate_type_selector").val());
}

// Add keyboard shortcut for rate switching
$(document).keydown(function(e) {
    if (e.altKey) {
        switch(e.which) {
            case 49: // Alt+1 for Sales Rate
                $("#rate_type_selector").val('sales').trigger('change');
                e.preventDefault();
                break;
            case 50: // Alt+2 for Shop Rate
                $("#rate_type_selector").val('shop').trigger('change');
                e.preventDefault();
                break;
            case 51: // Alt+3 for Wholesale Rate
                $("#rate_type_selector").val('wholesale').trigger('change');
                e.preventDefault();
                break;
        }
    }
});

// Enhanced addrow function to better handle rate selection
var originalAddrow = window.addrow;
window.addrow = function(id, item_obj) {
    // Store current rate type before adding item
    var current_rate_type = $("#rate_type_selector").val();
    
    // Call original addrow function
    var result = originalAddrow.call(this, id, item_obj);
    
    // Show notification about which rate was used
    setTimeout(function() {
        var rate_display_name = getRateTypeDisplayName(current_rate_type);
        toastr.info("Item added with " + rate_display_name, "", {timeOut: 2000});
    }, 100);
    
    return result;
};
