/**
 * Price validation script for WooCommerce Multi Locations Inventory Management
 * 
 * Handles validation between regular and sale prices across locations.
 * Instead of alerts, error messages are displayed in red below the sale price input.
 */
jQuery(document).ready(function($) {
    "use strict";
  
    // Helper function to display an error message below a field.
    function showError(field, msg){
      // Remove any existing error messages.
      field.closest('p').find('.wcmlim-error').remove();
      // Append a new error message with red styling.
      field.closest('p').append('<span class="wcmlim-error" style="color:red; display:block; margin-top:4px;">'+msg+'</span>');
    }
  
    // Helper function to remove any error message from the field's container.
    function clearError(field){
      field.closest('p').find('.wcmlim-error').remove();
    }
  
    // Helper to find a field using a selector and matching loc-id and pro-id attributes.
    function findField(selector, loc, prod){
      return $(selector+'[loc-id="'+loc+'"][pro-id="'+prod+'"]');
    }
  
    // Listen for changes on sale price fields for both simple and variable products.
    $(document).on('input change', '.wcmlim_product_sale_price, .wcmlim_variable_product_sale_price', function(){
      var saleField = $(this);
      var loc = saleField.attr('loc-id'),
          prod = saleField.attr('pro-id'),
          // Find the parent container for the sale field.
          parent = saleField.closest('.col-md-3'),
          // Try to locate the regular price field within the same sibling container.
          regField = parent.siblings('.col-md-3')
                      .find('input.wcmlim_product_regular_price[loc-id="'+loc+'"][pro-id="'+prod+'"]');
  
      // If not found, fallback to a global search based on field class.
      if(!regField.length){
        regField = saleField.hasClass('wcmlim_variable_product_sale_price') ? 
                   findField('.wcmlim_variable_product_regular_price', loc, prod) : 
                   findField('.wcmlim_product_regular_price', loc, prod);
      }
  
      // Update the value attribute of the sale field to the current value.
      saleField.attr('value', saleField.val());
  
      // Clear any previous error messages for this sale field.
      clearError(saleField);
  
      // Read and parse the regular and sale price values.
      var regVal = regField.val(),
          reg = parseFloat(regVal),
          sale = parseFloat(saleField.val());
  
      // Condition 1: If regular price is empty, invalid, or <= 0, clear sale price and show error.
      if(!regVal || isNaN(reg) || reg <= 0){
        saleField.val('');
        showError(saleField, 'Regular price must be set before adding a sale price.');
        return;
      }
      // Condition 2: If sale price is equal to or greater than regular price, clear sale price and show error.
      if(!isNaN(sale) && sale >= reg){
        saleField.val('');
        showError(saleField, 'Sale price must be less than the regular price.');
      }
    });
    
    // Listen for changes on regular price fields for both simple and variable products.
    $(document).on('input change', '.wcmlim_product_regular_price, .wcmlim_variable_product_regular_price', function(){
      var regField = $(this);
      var loc = regField.attr('loc-id'),
          prod = regField.attr('pro-id'),
          // Find the parent container for the regular field.
          parent = regField.closest('.col-md-3'),
          // Try to locate the sale price field within the same sibling container.
          saleField = parent.siblings('.col-md-3')
                       .find('input.wcmlim_product_sale_price[loc-id="'+loc+'"][pro-id="'+prod+'"]');
  
      // If not found, fallback to a global search based on field class.
      if(!saleField.length){
        saleField = regField.hasClass('wcmlim_variable_product_regular_price') ? 
                    findField('.wcmlim_variable_product_sale_price', loc, prod) : 
                    findField('.wcmlim_product_sale_price', loc, prod);
      }
  
      // Update the value attribute of the regular field.
      regField.attr('value', regField.val());
      
      // Clear any previous error messages from the sale price field container.
      clearError(saleField);
      
      // Parse the regular and sale price values.
      var reg = parseFloat(regField.val()),
          sale = parseFloat(saleField.val());
      
      if(!regField.val()){
        saleField.val('');
        showError(saleField, 'Regular price must be set before adding a sale price.');
        return;
      }

      // If the sale price is equal to or greater than the new regular price, clear the sale price and show error.
      if(!isNaN(sale) && sale >= reg){
        saleField.val('');
        showError(saleField, 'Regular price must be greater than the sale price.');
      }
    });
});
