<?php
use Automattic\WooCommerce\Utilities\OrderUtil; // at the beginning of the file

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 * 
 * @link       http://www.techspawn.com
 * @since      1.0.0
 * @package    Wcmlim
 * @subpackage Wcmlim/admin
 * @author     techspawn1 <contact@techspawn.com>
 */
class Wcmlim_Admin
{



  /**
   * The ID of this plugin.
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $plugin_name    The ID of this plugin.
   */
  private $plugin_name;

  /**
   * The version of this plugin.
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $version    The current version of this plugin.
   */
  private $version;

  /**
   * Initialize the class and set its properties.
   *
   * @since    1.0.0
   * @param      string    $plugin_name       The name of this plugin.
   * @param      string    $version    The version of this plugin.
   */

  private $option_name = 'wcmlim';

  public function __construct($plugin_name, $version)
  {

    $this->plugin_name = $plugin_name;
    $this->version = $version;
    
    // Initialize screen options hooks
    $this->init_screen_options_hooks();

  }

  /**
   * Register the stylesheets for the admin area.
   *
   * @since    1.0.0
   */
  public function enqueue_styles()
  {
    // Don't load admin styles in customizer
    if (is_customize_preview()) {
      return;
    }

    if (isset($_GET['page']) && $_GET['page'] == "wcmlim-product-central") {
      wp_enqueue_style($this->plugin_name . 'css-datatable', 'https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css', array(), $this->version, 'all');
      wp_enqueue_style($this->plugin_name . '-central', plugin_dir_url(__FILE__) . 'css/wcmlim-admin-central-min.css', array(), $this->version, 'all');
    }
    wp_enqueue_style($this->plugin_name . '_chosen_css', plugin_dir_url(__FILE__) . 'css/chosen.min.css', array(), $this->version, 'all');
    wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/wcmlim-admin.css', array(), $this->version, 'all');
    /*alertify css added*/

    
    if (((isset($_GET['page'])) && $_GET['page'] == "multi-location-inventory-management") || 
    ((isset($_GET['post_type'])) && ($_GET['post_type'] !== "product")) || 
    (isset($_GET['page']) && $_GET['page'] == 'wcmlim-product-central') || 
    (isset($_GET['page']) && $_GET['page'] == 'wc-orders') || 
    ((isset($_GET['post_type'])) && ($_GET['post_type'] == "shop_order")) || 
    (isset($_GET['taxonomy']) && $_GET['taxonomy'] == 'locations') || 
    (isset($_GET['page']) && strpos($_GET['page'], 'wcmlim') === 0) || 
    (isset($_GET['taxonomy']) && ($_GET['taxonomy'] == 'locations' || $_GET['taxonomy'] == 'location_group'))) {
      wp_enqueue_style($this->plugin_name . 'alertify', plugin_dir_url(__FILE__) . 'css/alertify.min.css', array(), $this->version, 'all');
      wp_enqueue_style($this->plugin_name . 'alertify-theme', plugin_dir_url(__FILE__) . 'css/default.min.css', array(), $this->version, 'all');

    }

    /* Display Preview */
    if (isset($_GET['page']) && $_GET['page'] == "wcmlim-map-settings") {
      wp_enqueue_style('wp-color-picker');
    }

    if (isset($_GET['page']) && $_GET['page'] == "wcmlim-display-settings") {
      wp_enqueue_style($this->plugin_name . '_designbox_css', WCMLIM_URL_PATH . '/public/css/wcmlim-public-min.css', array(), $this->version, 'all');
    }

    wp_enqueue_style($this->plugin_name . '_frontview_css', WCMLIM_URL_PATH . '/public/css/wcmlim-frontview-min.css', array(), $this->version, 'all');
  }

  /**
   * Register the JavaScript for the admin area.
   *
   * @since    1.0.0
   */

  public function enqueue_scripts()
  {
    // Don't load admin scripts in customizer
    if (is_customize_preview()) {
      return;
    }

    /**
     * This function is provided for demonstration purposes only.
     *
     * An instance of this class should be passed to the run() function
     * defined in Wcmlim_Loader as all of the hooks are defined
     * in that particular class.
     *
     * The Wcmlim_Loader will then create the relationship
     * between the defined hooks and the functions defined in this
     * class.
     */

    $api_key = get_option('wcmlim_google_api_key');
    if (isset($_GET['page']) && $_GET['page'] == "wcmlim-product-central") {
      wp_enqueue_script('wcmlim-datatable', 'https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js', array('jquery'), '1.10.21', true);
      wp_enqueue_script($this->plugin_name . '_wcmlim_product-central', plugin_dir_url(__FILE__) . 'js/wcmlim-central-min.js', array('jquery'), $this->version . rand(), false);
      wp_localize_script($this->plugin_name. '_wcmlim_product-central', 'multi_inventory', array("ajaxurl" => admin_url("admin-ajax.php"), 'check_nonce' => wp_create_nonce('wcmlim_locations_nonce')));
    }

    $get_map_dependency = $this->wcmlim_is_map_dependecies_needed();

    if ($get_map_dependency == true) {
      wp_enqueue_script($this->plugin_name . '_chosen_js', plugin_dir_url(__FILE__) . 'js/chosen.jquery.min.js', array('jquery'), $this->version . rand(), false);

    }

    wp_enqueue_script($this->plugin_name . '_google_map', "https://maps.googleapis.com/maps/api/js?key={$api_key}&libraries=places&callback=Function.prototype", array('jquery'), $this->version, true);


    wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/wcmlim-admin.js', array('jquery'), $this->version . rand(), false);
    wp_enqueue_script($this->plugin_name . '_chosen_settingstoggle_js', plugin_dir_url(__FILE__) . 'js/wcmlim-admin-settingstoggle.js', array('jquery'), $this->version . rand(), false);
    wp_enqueue_script($this->plugin_name . '_validation_js', plugin_dir_url(__FILE__) . 'js/product_edit_validation.min.js', array('jquery'), $this->version . rand(), false);
    wp_enqueue_script($this->plugin_name . '_generic_js', plugin_dir_url(__FILE__) . 'js/wcmlim_generic.js', array('jquery'), $this->version . rand(), false);

    // Locations price validation script
    wp_enqueue_script($this->plugin_name . '_price_validation', plugin_dir_url(__FILE__) . 'js/wcmlim-price-validation.js', array('jquery'), $this->version . rand(), true );

    /*alertify js added*/


    wp_enqueue_script($this->plugin_name . '_alerify', plugin_dir_url(__FILE__) . 'js/alertify.min.js', array('jquery'), $this->version . rand(), false);
    

    wp_localize_script($this->plugin_name, 'multi_inventory', array("ajaxurl" => admin_url("admin-ajax.php"), 'check_nonce' => wp_create_nonce('wcmlim_locations_nonce')));
    /* Display Preview && fontawesome */

    // Add Validation to "Exclude all locations" settings - User should not able to exclude all locations -code init
    $notexcludedLocations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    $allowedcount_for_exclude = count($notexcludedLocations) - 1;
    $dataToPass = array(
      'keys' => $allowedcount_for_exclude
    );
    wp_localize_script($this->plugin_name, 'passedData', $dataToPass);

    //Location widget enable disable setting 
    $locationWidget = "on";
    $_location_widget = array(
      'keys' => $locationWidget
    );
    wp_localize_script($this->plugin_name, 'locationWidget', $_location_widget);
    // Add Validation to "Exclude all locations" settings - User should not able to exclude all locations -code init
    $notexcludedLocations_group = get_terms(array('taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0));
    $allowedcount_for_exclude_group = count($notexcludedLocations_group) - 1;
    $dataToPass_group = array(
      'keys' => $allowedcount_for_exclude_group
    );
    wp_localize_script($this->plugin_name, 'passedData_group', $dataToPass_group);
    // Add Validation to "Exclude all locations" settings - User should not able to exclude all locations -code end

    wp_enqueue_script('wp-color-picker');
    wp_enqueue_script($this->plugin_name . 'preview', plugin_dir_url(__FILE__) . 'js/wcmlim-admin-preview-min.js', array('jquery'), $this->version . rand(), false);
    /* bulk assign location to users and products */
    wp_enqueue_script($this->plugin_name . '_set_bulk_defaultloc', plugin_dir_url(__FILE__) . 'js/set-bulk-default-loc-min.js', array('jquery'), $this->version . rand(), false);
    /*update all products js*/
    wp_enqueue_script($this->plugin_name . '_update_all_products', plugin_dir_url(__FILE__) . 'js/updateallproducts-min.js', array('jquery'), $this->version . rand(), false);

    $enable_COGSprice = 'on';
    if ($enable_COGSprice == 'on') {
      wp_enqueue_script($this->plugin_name . '_cogsValidation', plugin_dir_url(__FILE__) . 'js/wcmlim-cogs-validation-min.js', array('jquery'), $this->version . rand(), false);
    }

  }


  

public function is_wcmlim_plugin_page() {
    // Check 'page' parameter
    if (isset($_GET['page'])) {
        $page = $_GET['page'];
        if (
            strpos($page, 'wcmlim') === 0 ||
            in_array($page, [
                'multi-location-inventory-management',
                'wcmlim-product-central',
                'wc-orders',
                'wcmlim-settings',
                'wcmlim-display-settings',
                'wcmlim-map-settings',
                'wcmlim-addon-settings',
                'wcmlim_options_import_export_settings'
            ])
        ) {
            return true;
        }
    }

    // Check 'taxonomy' parameter
    if (isset($_GET['taxonomy']) && in_array($_GET['taxonomy'], ['locations', 'location_group'])) {
        return true;
    }

    // Check 'post_type' parameter
    if (isset($_GET['post_type']) && $_GET['post_type'] === 'shop_order') {
        return true;
    }

    return false;
}





  public function wcmlim_is_map_dependecies_needed()
  {
    if (
      (isset($_GET['page']) && strpos($_GET['page'], 'wcmlim') === 0) || 
      (isset($_GET['taxonomy']) && ($_GET['taxonomy'] == 'locations' || $_GET['taxonomy'] == 'location_group'))) 
      {
      return true;
    }

    $wcmlim_geo_location = get_option('wcmlim_geo_location');
    $wcmlim_next_closest_location = get_option('wcmlim_next_closest_location');
    $wcmlim_get_direction_for_location = get_option('wcmlim_get_direction_for_location');

    if ($wcmlim_geo_location == 'on' || $wcmlim_next_closest_location == 'on' || $wcmlim_get_direction_for_location == 'on') {
      return true;
    } else {   
      return false;
    }

  }

  /**
   * Show doc and support options on plugin page.
   *
   * @since 1.2.8
   */
  public function plugin_row_meta($plugin_meta, $plugin_file)
  {
    if (WCMLIM_BASE === $plugin_file) {
      $row_meta = [
        'docs' => '<a href="https://techspawn.com/docs/woocommerce-multi-locations-inventory-management/" aria-label="' . esc_attr(__('View Documentation', 'wcmlim')) . '" target="_blank">' . __('Docs', 'wcmlim') . '</a>',
        'ideo' => '<a href="http://techspawn.com/support/" aria-label="' . esc_attr(__('Support', 'wcmlim')) . '" target="_blank">' . __('Support', 'wcmlim') . '</a>',
      ];

      $plugin_meta = array_merge($plugin_meta, $row_meta);
    }

    return $plugin_meta;
  }

  /**
   * Register the Menu page for the plugin.
   *
   * @since    1.0.0
   */
 public function wcmlim_register_menu_page() {

  $isLocationsGroup = get_option('wcmlim_enable_location_group');

    // Main menu page
    add_menu_page(
        __('MULTILOCA', 'wcmlim'),
        __('MULTILOCA', 'wcmlim'),
        'manage_options',
        'multi-location-inventory-management', // Unique slug for the main menu
        array($this, 'wcmlim_multiloca_menu'), // Callback for the main menu
        plugin_dir_url(__FILE__) . 'img/pins.png',
        '65'
    );
    // Submenu: Manage Locations
    add_submenu_page(
        'multi-location-inventory-management',
        __('Manage Locations', 'wcmlim'),
        __('Manage Locations', 'wcmlim'),
        'manage_options',
        'edit-tags.php?taxonomy=locations&post_type=product'
    );

    if ($isLocationsGroup === 'on') {
        // Submenu: Manage Group
        add_submenu_page(
            'multi-location-inventory-management',
            __('Manage Group', 'wcmlim'),
            __('Manage Group', 'wcmlim'),
            'manage_options',
            'edit-tags.php?taxonomy=location_group&post_type=product'

        );
    }

    // Submenu: Settings
    add_submenu_page(
        'multi-location-inventory-management', // Parent slug
        __('Settings', 'wcmlim'),
        __('Settings', 'wcmlim'),
        'manage_options',
        'wcmlim-settings', // Unique slug for this submenu
        array($this, 'wcmlim_settings_page') // Callback for the submenu
    );

    // Submenu: Display Settings
    add_submenu_page(
        'multi-location-inventory-management',
        __('Display Settings', 'wcmlim'),
        __('Display Settings', 'wcmlim'),
        'manage_options',
        'wcmlim-display-settings',
        array($this, 'wcmlim_display_settings')
    );

   // Product Central
    $hook_suffix = add_submenu_page(
        'multi-location-inventory-management',
        __('Product Central', 'wcmlim'),
        __('Product Central', 'wcmlim'),
        'manage_options',
        'wcmlim-product-central',
        array($this, 'wcmlim_display_products')
      );
      // Hook Screen Options loader
    add_action("load-$hook_suffix", array($this, 'my_custom_screen_options'));
      //check whether premium plugin is active or not.
      if( in_array( 'multiloca-premium/multiloca-premium-addon.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
        // Add display rules tab which are the conditional logics
        add_submenu_page(
            'multi-location-inventory-management',
            __('Location Display Rules', 'wcmlim'),
            __('Location Display Rules', 'wcmlim'),
            'manage_options',
            'wcmlim-display-rules',
            array($this, 'wcmlim_display_rules')
        );
      }
    
    // Submenu: Store Locator
    add_submenu_page(
        'multi-location-inventory-management',
        __('Store Locator', 'wcmlim'),
        __('Store Locator', 'wcmlim'),
        'manage_options',
        'wcmlim-map-settings',
        array($this, 'wcmlim_map_settings')
    );

    $wcmlim_assign_location_shop_manager = get_option("wcmlim_assign_location_shop_manager");
    if($wcmlim_assign_location_shop_manager == "on") {
      // Submenu: Location Managers
      add_submenu_page(
          'multi-location-inventory-management',
          __('Location Managers', 'wcmlim'),
          __('Location Managers', 'wcmlim'),
          'manage_options',
          'wcmlim-user-settings',
          array($this, 'wcmlim_user_settings')
      );
    }
     

    // Submenu: Addons
    add_submenu_page(
        'multi-location-inventory-management',
        __('Addons', 'wcmlim'),
        __('Addons', 'wcmlim'),
        'manage_options',
        'wcmlim-addon-settings',
        array($this, 'wcmlim_addon_settings')
    );

    // Submenu: Config
    add_submenu_page(
        'multi-location-inventory-management',
        __('Config', 'wcmlim'),
        __('Config', 'wcmlim'),
        'manage_options',
       'wcmlim_options_import_export_settings',
        array($this, 'wcmlim_options_import_export')
    );
}

public function my_custom_screen_options() {    
    // Add JavaScript for handling column checkboxes
    add_action('admin_print_footer_scripts', array($this, 'product_central_screen_options_js'));
}

// JavaScript to handle column checkboxes
public function product_central_screen_options_js() {
    global $current_screen;
    
    if ($current_screen->id !== 'multiloca_page_wcmlim-product-central') {
        return;
    }
    
    // Ensure nonce is available
    if (!wp_script_is('common', 'done')) {
        wp_enqueue_script('common');
    }
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Create nonce field if it doesn't exist
        if (!$('#screen-options-nonce').length) {
            $('#screen-options-wrap').append('<input type="hidden" id="screen-options-nonce" value="<?php echo wp_create_nonce('screen-options-nonce'); ?>" />');
        }
        // Handle column checkbox changes
        $('.hide-column-tog').on('change', function() {
            var column = $(this).val();
            var checked = $(this).is(':checked');
            console.log('Checkbox changed: ' + column + ' = ' + (checked ? 'checked' : 'unchecked'));
            
            // Save the preference via AJAX
            var data = {
                action: 'save_product_central_columns',
                _ajax_nonce: $('#screen-options-nonce').val()
            };
            
            // Add all column states
            $('.hide-column-tog').each(function() {
                var col = $(this).val();
                var isChecked = $(this).is(':checked');
                data[col + '-hide'] = isChecked ? '1' : '0';
            });
            
            console.log('Sending AJAX data:', data);
            
            $.post(ajaxurl, data, function(response) {
                console.log('AJAX response:', response);
                // Optionally handle response
                if (response == '1') {
                    // Success - optionally show/hide columns in table
                    console.log('Column preferences saved successfully');
                } else {
                    console.log('Failed to save column preferences');
                }
            }).fail(function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                console.log('Response text:', xhr.responseText);
            });
        });
        
        // Handle inventory management location checkbox changes
        $('.hide-column-tog-inv').on('change', function() {
            var location_id = $(this).val();
            var checked = $(this).is(':checked');
            console.log('Location checkbox changed: ' + location_id + ' = ' + (checked ? 'selected' : 'deselected'));
            
            // Save the selected locations via AJAX
            var data = {
                action: 'save_inventory_locations',
                _ajax_nonce: $('#screen-options-nonce').val(),
                selected_locations: []
            };
            
            // Collect all selected location IDs
            $('.hide-column-tog-inv:checked').each(function() {
                data.selected_locations.push($(this).val());
            });
            
            console.log('Sending Location Selection AJAX data:', data);
            
            $.post(ajaxurl, data, function(response) {
                console.log('Location Selection AJAX response:', response);
                if (response.success) {
                    console.log('Location selections saved successfully');
                    // Refresh the page to show updated columns
                    setTimeout(function() {
                        window.location.reload();
                    }, 500);
                } else {
                    console.log('Failed to save location selections');
                }
            }).fail(function(xhr, status, error) {
                console.error('Location Selection AJAX Error:', status, error);
                console.log('Response text:', xhr.responseText);
            });
        });
    });
    </script>
    <?php
}

  /**
   * Add columns functionality for screen options
   */
  public function init_screen_options_hooks() {
    add_filter('screen_settings', array($this, 'product_central_screen_settings'), 10, 2);
    add_action('wp_ajax_save_product_central_columns', array($this, 'save_product_central_columns_handler'));
    add_action('wp_ajax_save_inventory_locations', array($this, 'save_inventory_locations_handler'));
  }

  public function product_central_screen_settings($settings, $screen) {
    if ($screen->id !== 'multiloca_page_wcmlim-product-central') {
        return $settings;
    }
    
    // Get current tab (default to tab-1 if not set)
    $current_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'tab-1';
    
    // Get saved column preferences from options table
    $saved_columns = get_option('ProductCentralControlOptions', array());
    
    if (!is_array($saved_columns)) {
        $saved_columns = array();
    }
    
    $columns_html = '';
    
    // Show "Columns" section only on Products Editor (tab-1) and Settings (tab-2)
    if (in_array($current_tab, array('tab-1', 'tab-2'))) {
        // Define available columns - must match get_columns() in class-wcmlim-product-central.php
        $columns = array(
            'cb' => 'Checkbox',
            'id' => 'Product ID',
            'thumbnail' => 'Thumbnail', 
            'name' => 'Name',
            'sku' => 'SKU',
            'type' => 'Type',
            'regular_price' => 'Regular Price',
            'sale_price' => 'Sale Price',
            'stock_status' => 'Stock Status',
            'manage_stock' => 'Manage Stock',
            'stock_at_location' => 'Stock At Locations',
            'stock_quantity' => 'Stock Quantity',
            'short_description' => 'Short Description',
            'description' => 'Description',
            'status' => 'Status',
            'backorders' => 'Backorders',
            'weight' => 'Weight',
            'length' => 'Length',
            'width' => 'Width',
            'height' => 'Height'
        );
        
        $columns_html .= '<fieldset class="metabox-prefs">';
        $columns_html .= '<legend>Columns</legend>';
        
        foreach ($columns as $column_key => $column_label) {
            // Default to visible (checked) if column preference not set, or if explicitly set to 'Show'
            $is_visible = !isset($saved_columns[$column_key]) || $saved_columns[$column_key] === 'Show';
            $checked = $is_visible ? 'checked="checked"' : '';
            $columns_html .= '<label for="' . $column_key . '-hide">';
            $columns_html .= '<input class="hide-column-tog" name="' . $column_key . '-hide" type="checkbox" id="' . $column_key . '-hide" value="' . $column_key . '" ' . $checked . '>';
            $columns_html .= $column_label . '</label>';
        }
        
        $columns_html .= '</fieldset>';
    }
    
    // Show "Inventory Management" section only on Inventory Management (tab-3) and Inventory Settings (tab-4)
    if (in_array($current_tab, array('tab-3', 'tab-4'))) {
        $columns_html .= '<fieldset class="metabox-prefs">';
        $columns_html .= '<legend>Inventory Settings</legend>';
        
        // Get only location columns (not all inventory columns)
        $location_columns = $this->get_location_columns_for_screen_options();
        $selected_location_ids = get_option('wcmlim_inventory_selected_locations', array());
        
        foreach ($location_columns as $location_id => $location_name) {
            // Check if location is selected (checked = selected/visible)
            $is_selected = in_array($location_id, $selected_location_ids);
            $checked = $is_selected ? 'checked="checked"' : '';
            $columns_html .= '<label for="location_' . $location_id . '-hide">';
            $columns_html .= '<input class="hide-column-tog-inv" name="location_' . $location_id . '" type="checkbox" id="location_' . $location_id . '-hide" value="' . $location_id . '" ' . $checked . '>';
            $columns_html .= esc_html($location_name) . '</label>';
        }
        
        $columns_html .= '</fieldset>';
    }

    return $settings . $columns_html;
  }

  /**
   * Get all available locations for screen options (not just selected ones)
   */
  private function get_location_columns_for_screen_options() {
    $locations = get_terms(array(
        'taxonomy'   => 'locations',
        'hide_empty' => false,
        'parent'     => 0
    ));

    $location_options = array();
    if (!empty($locations) && !is_wp_error($locations)) {
        foreach ($locations as $location) {
            $location_options[$location->term_id] = $location->name;
        }
    }

    return $location_options;
  }

  public function save_product_central_columns_handler() {
    // Add debugging
    error_log('AJAX Handler called - POST data: ' . print_r($_POST, true));
    
    check_ajax_referer('screen-options-nonce', '_ajax_nonce');
    
    if (!current_user_can('manage_options')) {
        error_log('User does not have manage_options capability');
        wp_die(-1);
    }
    
    $user_id = get_current_user_id();
    $columns = array();
    
    error_log('Processing columns for user ID: ' . $user_id);
    
    // Define available columns - must match get_columns() in class-wcmlim-product-central.php
    $available_columns = array(
        'id', 'thumbnail', 'name', 'sku', 'type', 'regular_price', 'sale_price',
        'stock_status', 'manage_stock', 'stock_at_location', 'stock_quantity',
        'short_description', 'description', 'status', 'backorders', 'weight',
        'length', 'width', 'height'
    );
    
    // Add 'cb' column to available columns and save column visibility preferences
    $all_columns = array_merge(array('cb'), $available_columns);
    
    foreach ($all_columns as $column) {
        // Check if field exists and has value '1' (checked state) - use "Show" for visible columns
        $is_visible = isset($_POST[$column . '-hide']) && $_POST[$column . '-hide'] === '1';
        $columns[$column] = $is_visible ? 'Show' : 'Hide';
        error_log('Column ' . $column . ' (' . $column . '-hide): ' . (isset($_POST[$column . '-hide']) ? $_POST[$column . '-hide'] : 'not set') . ' = ' . $columns[$column]);
    }
    
    $result = update_option('ProductCentralControlOptions', $columns);
    error_log('Update option result: ' . ($result ? 'success' : 'failed'));
    error_log('Saved columns: ' . print_r($columns, true));
    
    wp_die(1);
  }

  public function save_inventory_locations_handler() {
    // Add debugging
    error_log('Location Selection AJAX Handler called - POST data: ' . print_r($_POST, true));
    
    check_ajax_referer('screen-options-nonce', '_ajax_nonce');
    
    if (!current_user_can('manage_options')) {
        error_log('User does not have manage_options capability');
        wp_send_json_error(['message' => 'Insufficient permissions']);
        return;
    }
    
    // Get selected location IDs from POST data
    $selected_locations = isset($_POST['selected_locations']) ? $_POST['selected_locations'] : array();
    
    // Validate that it's an array
    if (!is_array($selected_locations)) {
        error_log('Selected locations is not an array');
        wp_send_json_error(['message' => 'Invalid data format']);
        return;
    }
    
    // Sanitize the location IDs (ensure they're integers)
    $selected_locations = array_map('intval', $selected_locations);
    $selected_locations = array_filter($selected_locations); // Remove empty values
    
    error_log('Processing selected locations: ' . print_r($selected_locations, true));
    
    // Save to the same option used by inventory management
    $result = update_option('wcmlim_inventory_selected_locations', $selected_locations);
    
    error_log('Update wcmlim_inventory_selected_locations result: ' . ($result ? 'success' : 'failed'));
    
    if ($result) {
        wp_send_json_success(['message' => 'Locations saved successfully']);
    } else {
        wp_send_json_error(['message' => 'Failed to save locations']);
    }
  }

  /**
   * Stock wise product sorting as per location on shop-page.
   *
   * @since    3.0.1
   */

  public function filter_woocommerce_get_catalog_ordering_args($args)
  {
    $orderby_value = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
    $loc_key = (int)(getLocation('wcmlim_selected_location') ?? 0);
    if ($loc_key != 0) {
      $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
      if (isset($terms[$loc_key])) {
        $meta_key = "wcmlim_stock_at_" . $terms[$loc_key]->term_id;
        if ($orderby_value == 'high-to-low') {
          $args['orderby'] = 'meta_value_num';
          $args['order'] = 'DESC';
          $args['meta_key'] = $meta_key;
        } elseif ($orderby_value == 'low-to-high') {
          $args['orderby'] = 'meta_value_num';
          $args['order'] = 'ASC';
          $args['meta_key'] = $meta_key;
        }
      }
    }
    return $args;
  }

  public function custom_woocommerce_catalog_orderby($sortby)
  {
    $sortby['high-to-low'] = 'Sort By Stock: High To Low';
    $sortby['low-to-high'] = 'Sort By Stock: Low To High';
    return $sortby;
  }

  /**
   * Hightlight the submenu page for custom taxonomy.
   *
   * @since    1.0.0
   */

  public function wcmlim_submenu_highlight($parent_file)
  {
    global $current_screen;
    $taxonomy = $current_screen->taxonomy;
    if ($taxonomy == 'locations') {
      $parent_file = 'multi-location-inventory-management';
    } else if ($taxonomy == 'location_group') {
      $parent_file = 'multi-location-inventory-management';
    }
    return $parent_file;
  }

  /**
   * Hightlight the submenu page is active for custom taxonomy.
   *
   * @since    1.0.0
   */

  public function wcmlim_hightlight_submenu($submenu_file)
  {
    $locations = 'edit-tags.php?taxonomy=locations&post_type=product';
    $loc_group = 'edit-tags.php?taxonomy=location_group&post_type=product';

    if (get_option('wcmlim_license') == '' || get_option('wcmlim_license') == 'invalid') {
      // Redirect if accessing "Manage Locations" or "Manage Group" without a valid license
      if (esc_html($locations) == $submenu_file || esc_html($loc_group) == $submenu_file) {
        echo '<script>window.location.href = "?page=multi-location-inventory-management";</script>';
        exit; // Prevent further execution
      }
    }

    if (esc_html($locations) == $submenu_file) {
      return 'edit-tags.php?taxonomy=locations&post_type=product';
    } elseif (esc_html($loc_group) == $submenu_file) {
      return 'edit-tags.php?taxonomy=location_group&post_type=product';
    }
    return $submenu_file;
  }

  /**
   * load the admin page.
   *
   * @since    1.0.0
   */

  public function wcmlim_menu_page()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-admin-display.php';
  }


  public function wcmlim_multiloca_menu()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-multiloca.php';

  }

  public function wcmlim_settings_page()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-settings.php';
  }
  /**
   * load the display settings page.
   *
   * @since    1.0.0
   */

  public function wcmlim_display_settings()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-display-settings.php';
  }



  /**
   * load the map settings page.
   *
   * @since    1.0.0
   */

  public function wcmlim_map_settings()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-map-settings.php';
  }

  public function wcmlim_user_settings()
  {
    // Enqueue necessary scripts for user management
    wp_enqueue_script('jquery');
    
    // Localize script with AJAX data for user management
    wp_localize_script('jquery', 'wcmlim_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wcmlim_user_management_nonce')
    ));
    
    // Also make ajaxurl available globally
    wp_localize_script('jquery', 'ajaxurl', admin_url('admin-ajax.php'));
    
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-user-settings.php';
  }

  public function wcmlim_addon_settings()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-addon-settings.php';
  }

  public function wcmlim_options_import_export()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-options-import-export-setting.php';
  }

  /**
   * Product Central Callback Function.
   *
   * @since    1.2.9
   */

  public function wcmlim_display_products()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-product-central.php';
  }

  // This file includes the conditional logics tab.
  public function wcmlim_display_rules()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-display-rules.php';
  }

  /**
   * load the location shortcode settings page.
   *
   * @since    1.0.0
   */

  public function wcmlim_location_shortcode_settings()
  {
    require plugin_dir_path(__FILE__) . 'partials/wcmlim-location-shortcode-settings.php';
  }


  /**
   * Register the settings for plugin.
   *
   * @since    1.0.0
   */

  public function wcmlim_register_setting()
  {

    register_setting($this->plugin_name, $this->option_name . '_restrict_guest_user_location');
    register_setting($this->plugin_name, $this->option_name . '_show_location_selection');
    register_setting($this->plugin_name, $this->option_name . '_distance_calculator_by_coordinates');
    register_setting($this->plugin_name, $this->option_name . '_distance_calculator_by_cloudfare');


    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_geo_location');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_suggestion_off');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_hide_show_location_dropdown');
    
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_exclude_locations_from_frontend');
    
    // Register address management settings
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_user_address_management');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_google_maps_api_key_address');


    add_settings_field(
      $this->option_name . '_enable_default_location',
      __('Set Default Location for a Specific Product', 'wcmlim'),
      array($this, $this->option_name . '_enable_default_location_callback'),
      $this->plugin_name . '_location_shortcode_settings',
      $this->option_name . '_location_shortcode_settings',
      array('label_for' => $this->option_name . '_enable_default_location')
    );

    add_settings_field(
      $this->option_name . '_enable_userspecific_location',
      __('Set Specific location For Users', 'wcmlim'),
      array($this, $this->option_name . '_enable_userspecific_location_callback'),
      $this->plugin_name . '_location_shortcode_settings',
      $this->option_name . '_location_shortcode_settings',
      array('label_for' => $this->option_name . '_enable_userspecific_location')
    );


    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_exclude_locations_group_frontend');
    
    $radiolisitng = get_option('wcmlim_select_or_dropdown');


add_settings_section(
  $this->option_name . '_location_threshold_settings',
  __('', 'wcmlim'),
  null, // No callback needed for section
  $this->plugin_name . '_location_shortcode_settings'
);

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_clear_cart');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_default_location');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_backorder_for_locations');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_specific_location');    
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_autodetect_location');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_autodetect_location_by_maxmind');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_autodetect_location_with_ipinfo');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_price');                
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_cron_for_product');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_cron_for_product_userdefined');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_assign_location_shop_manager');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_location_group');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_distance_calculator_by_coordinates');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_distance_calculator_by_cloudfare');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_userspecific_location');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_restrict_guest_user_location');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_sorting_by_proximity');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_filter_by_proximity');

    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_location_priority_order'); 

    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_select_or_dropdown');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_radio_loc_fulladdress');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_radio_loc_format');
    register_setting($this->plugin_name . '_location_shortcode_settings', $this->option_name . '_enable_COGSprice');


    /*
     * Custom Error Notice Message 
     * added options
     * @since    1.2.15
     */

    add_settings_field(
      $this->option_name . '_prod_instock_valid',
      __('Location Stock Unavailable', 'wcmlim'),
      array($this, $this->option_name . '_prod_instock_valid_cb'),
      $this->plugin_name . '_custom_notice',
      $this->option_name . '_custom_notice',
      array('label_for' => $this->option_name . '_prod_instock_valid')
    );

    register_setting($this->plugin_name . '_custom_notice', $this->option_name . '_prod_instock_valid');
    register_setting($this->plugin_name . '_custom_notice', $this->option_name . '_var_message1');


    add_settings_field(
      $this->option_name . '_order_fulfil_edit',
      __('Allow to Fulfil Order from Backend', 'wcmlim'),
      array($this, $this->option_name . '_order_fulfil_edit_callback'),
      $this->plugin_name . '_backend_only_mode',
      $this->option_name . '_backend_only_mode',
      array('label_for' => $this->option_name . '_order_fulfil_edit', 'class' => 'hidden')
    );

    add_settings_field(
      $this->option_name . '_backend_display_stock',
      __('Display Location Stock', 'wcmlim'),
      array($this, $this->option_name . '_backend_display_stock_callback'),
      $this->plugin_name . '_backend_only_mode',
      $this->option_name . '_backend_only_mode',
      array('label_for' => $this->option_name . '_backend_display_stock')
    );


    add_settings_field(
      $this->option_name . '_order_fulfilment_rules',
      __('Order Fulfilment Rules', 'wcmlim'),
      array($this, $this->option_name . '_order_fulfilment_rules_callback'),
      $this->plugin_name . '_backend_only_mode',
      $this->option_name . '_backend_only_mode',
      array('label_for' => $this->option_name . '_order_fulfilment_rules')
    );

    $backend_display_stock = get_option('wcmlim_backend_display_stock');

    register_setting($this->plugin_name . '_backend_only_mode', $this->option_name . '_order_fulfil_edit');
    register_setting($this->plugin_name . '_backend_only_mode', $this->option_name . '_order_fulfilment_rules');
    register_setting($this->plugin_name . '_backend_only_mode', $this->option_name . '_backend_display_stock');

    register_setting($this->plugin_name . '_shipping_zone_method_settings', $this->option_name . '_enable_tax_to_each_item');


    register_setting($this->plugin_name . '_product_shop_page_settings', $this->option_name . '_enable_location_onshop_variable');
    register_setting($this->plugin_name . '_product_shop_page_settings', $this->option_name . '_enable_location_onshop');
    register_setting($this->plugin_name . '_product_shop_page_settings', $this->option_name . '_enable_location_price_onshop');
    register_setting($this->plugin_name . '_product_shop_page_settings', $this->option_name . '_hide_outofstock_products');

    register_setting($this->plugin_name . '_shortcode_setting', $this->option_name . '_listing_inline_location');
    register_setting($this->plugin_name . '_shortcode_setting', $this->option_name . '_preferred_location');
    register_setting($this->plugin_name . '_shortcode_setting', $this->option_name . '_location_popup');
    register_setting($this->plugin_name . '_shortcode_setting', $this->option_name . '_listing_popup_location');

    // Display setting section
    add_settings_section(
      $this->option_name . '_display_settings',
      __('Locations Interface', 'wcmlim'),
      array($this, $this->option_name . '_display_settings_cb'),
      $this->option_name . '_display_settings'
    );

    // Add the Select Location View setting
    add_settings_field(
      $this->option_name . '_backend_display_stock_view',   // Setting ID
      __('Select Location View', 'wcmlim'),                 // Field Title
      array($this, $this->option_name . '_backend_display_stock_view_callback'), // Callback function
      $this->option_name . '_display_settings',
          $this->option_name . '_display_settings',  // Section ID
      array('label_for' => $this->option_name . '_backend_display_stock_view')  // For better accessibility
    );

    // Add the Display Fields Settings
    add_settings_field(
      $this->option_name . '_backend_display_feilds_settings',  // Setting ID
      __('Display Fields Settings', 'wcmlim'),                   // Field Title
      array($this, $this->option_name . '_backend_display_feilds_settings_callback'), // Callback function
      $this->option_name . '_display_settings',
          $this->option_name . '_display_settings',         // Section ID
      array('label_for' => $this->option_name . '_backend_display_feilds_settings')  // For better accessibility
    );

    // Add the Maximum Location Count setting
    add_settings_field(
      $this->option_name . '_maximum_location_count',  // Setting ID
      __('Maximum Location Count', 'wcmlim'),          // Field Title
      array($this, $this->option_name . '_maximum_location_count_callback'), // Callback function
      $this->option_name . '_display_settings',
          $this->option_name . '_display_settings',    // Section ID
      array('label_for' => $this->option_name . '_maximum_location_count')  // For better accessibility
    );

      // Register the settings for the new Location Display Settings
    register_setting(
      $this->plugin_name . '_display_settings',  // Option group
      $this->option_name . '_backend_display_stock_view'  // Option name for Select Location View
    );

    register_setting(
      $this->plugin_name . '_display_settings',  // Option group
      $this->option_name . '_backend_display_feilds_settings'  // Option name for Display Fields Settings
    );

    register_setting(
      $this->plugin_name . '_display_settings',  // Option group
      $this->option_name . '_maximum_location_count'  // Option name for Maximum Location Count
    );

    
    register_setting($this->option_name . '_display_settings', $this->option_name . '_backend_display_feilds_settings_order');

    add_settings_section(
      $this->option_name . '_map_settings',
      "",
      array($this, $this->plugin_name . '_general_cb'),
      $this->plugin_name . '_map_settings'
    );

    add_settings_field(
      $this->option_name . '_default_zoom',
      __('Default Zoom on Map', 'wcmlim'),
      array($this, $this->option_name . '_default_zoom_callback'),
      $this->option_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_default_zoom')
    );

    add_settings_field(
      $this->option_name . '_default_origin_center',
      __('Default Origin on Map', 'wcmlim'),
      array($this, $this->option_name . '_default_origin_center_callback'),
      $this->plugin_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_default_origin_center')
    );

    add_settings_field(
      $this->option_name . '_default_list_align',
      __('Location List Alignment On Map', 'wcmlim'),
      array($this, $this->option_name . '_default_list_align_callback'),
      $this->plugin_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_default_list_align')
    );

    add_settings_field(
      $this->option_name . '_default_map_color',
      __('Default Map Color', 'wcmlim'),
      array($this, $this->option_name . '_default_map_color_callback'),
      $this->plugin_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_default_map_color')
    );

    add_settings_field(
      $this->option_name . '_filter_visibility_shortcode',
      __('Product/Category Filter on Map', 'wcmlim'),
      array($this, $this->option_name . '_filter_visibility_shortcode_callback'),
      $this->option_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_filter_visibility_shortcode')
    );

    add_settings_field(
      $this->option_name . '_product_filter_store_locator',
      __('Add Product Filter to Store Locator', 'wcmlim'),
      array($this, $this->option_name . '_product_filter_store_locator_callback'),
      $this->option_name . '_map_settings',
      $this->option_name . '_map_settings',
      array('label_for' => $this->option_name . '_product_filter_store_locator')
    );

    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_default_list_align');
    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_default_origin_center');
    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_default_zoom');
    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_filter_visibility_shortcode');
    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_product_filter_store_locator');
    register_setting($this->plugin_name . '_map_settings', $this->option_name . '_default_map_color');

    /**
     * Design Preview Options and controls
     * @since    1.1.5
     */

    add_settings_field(
      $this->option_name . '_preview_stock_bgcolor',
      __('Multilocation Box', 'wcmlim'),
      array($this, $this->option_name . '_preview_stock_bgcolor_cb'),
      $this->option_name . '_display_settings',
      $this->option_name . '_display_settings',
      array('label_for' => $this->option_name . '_preview_stock_bgcolor')
    );



    /** Header - 1 */
    add_settings_field(
      $this->option_name . '_txt_stock_info',
      __('Header', 'wcmlim'),
      array($this, $this->option_name . '_txt_stock_info_cb'),
      $this->option_name . '_display_settings',
      $this->option_name . '_display_settings',
      array('label_for' => $this->option_name . '_txt_stock_info')
    );

    /** Sold out */
    add_settings_field(
      $this->option_name . '_soldout_button_text',
      __('Out Of Stock', 'wcmlim'),
      array($this, $this->option_name . '_soldout_button_text_cb'),
      $this->option_name . '_display_settings',
      $this->option_name . '_display_settings',
      array('label_for' => $this->option_name . '_soldout_button_text')
    );

    /** Instock */
    add_settings_field(
      $this->option_name . '_instock_button_text',
      __('In Stock ', 'wcmlim'),
      array($this, $this->option_name . '_instock_button_text_cb'),
      $this->option_name . '_display_settings',
      $this->option_name . '_display_settings',
      array('label_for' => $this->option_name . '_instock_button_text')
    );

    /** Available on backorder */
    add_settings_field(
      $this->option_name . '_onbackorder_button_text',
      __('Available on backorder', 'wcmlim'),
      array($this, $this->option_name . '_onbackorder_button_text_cb'),
      $this->option_name . '_display_settings',
      $this->option_name . '_display_settings',
      array('label_for' => $this->option_name . '_onbackorder_button_text')
    );

    register_setting($this->option_name . '_display_settings', $this->option_name . '_preview_stock_bgcolor');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_txt_stock_info');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_location_display_heading_setting');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_oncheck_button_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_oncheck_button_text_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_soldout_button_text');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_soldout_button_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_soldout_button_text_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_instock_button_text');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_hide_stock_count');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_onbackorder_button_text');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_onbackorder_button_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_onbackorder_button_text_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_onbackorder_borderradius');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_instock_button_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_instock_button_text_color');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_display_stock_info');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_txtcolor_stock_info');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_txtcolor_preferred_loc');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_display_preferred_loc');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_txtcolor_nearest_stock');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_display_nearest_stock');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_display_separator_line');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_refbox_borderradius');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_instock_borderradius');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_soldout_borderradius');
    register_setting($this->option_name . '_display_settings', $this->option_name . '_input_borderradius');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_oncheck_borderradius');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_preview_stock_width');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sel_padding_top');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sel_padding_bottom');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sel_padding_right');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sel_padding_left');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_inp_padding_top');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_inp_padding_bottom');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_inp_padding_right');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_inp_padding_left');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_btn_padding_top');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_btn_padding_bottom');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_btn_padding_right');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_btn_padding_left');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_display_icon');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_iconcolor_loc');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_iconsize_loc');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_is_padding_top');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_is_padding_bottom');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_is_padding_right');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_is_padding_left');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sbox_padding_top');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sbox_padding_bottom');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sbox_padding_right');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_sbox_padding_left');
    register_setting($this->plugin_name . '_display_settings', $this->option_name . '_selbox_bgcolor');
    
    // Hook to save Place IDs for Google Rating - use sanitize callback for proper hook
    register_setting(
      $this->plugin_name . '_display_settings',
      'wcmlim_place_id',
      array($this, 'save_google_place_ids_callback')
    );
  }

  /**
   * Save Google Place IDs for locations
   *
   * @since 1.0.0
   */
  public function save_google_place_ids_callback($value) {
    // Check if Place IDs are submitted
    if (isset($_POST['wcmlim_place_id']) && is_array($_POST['wcmlim_place_id'])) {
      foreach ($_POST['wcmlim_place_id'] as $term_id => $place_id) {
        $term_id = intval($term_id);
        $place_id = sanitize_text_field($place_id);
        
        // Update term meta
        if (!empty($place_id)) {
          update_term_meta($term_id, 'place_id', $place_id);
          
          // Clear cached rating when Place ID changes
          $cache_key = 'wcmlim_rating_' . md5($term_id . '_' . $place_id);
          delete_transient($cache_key);
        } else {
          // Remove Place ID if empty
          delete_term_meta($term_id, 'place_id');
        }
      }
    }
    
    // Return the value (but we don't actually store it as an option)
    return $value;
  }

  public function wcmlim_prod_instock_valid_cb()
  {
    $pinstock_valid = get_option($this->option_name . '_prod_instock_valid');
    if ($pinstock_valid == false) {
      update_option($this->option_name . '_prod_instock_valid', 'You can’t add more items than are available in stock .');
    }
    ?>
    <label for="<?php esc_attr_e($this->option_name . '_prod_instock_valid'); ?>"></label>
    <textarea rows="2" cols="50" name="<?php esc_attr_e($this->option_name . '_prod_instock_valid'); ?>"
      id="<?php esc_attr_e($this->option_name . '_prod_instock_valid'); ?>"
      value="<?php esc_attr_e($pinstock_valid); ?>"><?php esc_attr_e($pinstock_valid); ?></textarea>
    <?php echo '<label class="wcmlim-setting-option-des">' . __('While updating product quatity and don’t have more items to add on cart.', 'wcmlim') . '</label>'; ?>
    </p>
    <?php
  }
  /**Variation Message */
  public function wcmlim_var_message1_cb()
  { /** Separator  */
  }
  

    /**
   * callback function for general checkbox.
   *
   * @since    1.0.0
   */

  public function wcmlim_general_cb()
  {
    echo '<p>' . __('Please change the settings accordingly.', 'wcmlim') . '</p>';
  }


  /**
   * callback function for backend mode.
   *
   * @since    3.0.7
   */

  public function wcmlim_general_backend_mode()
  {
    echo '<p>' . __('Enabling the settings below will disable other frontend-related functionalities.', 'wcmlim') . '</p>';
  }
  /**
   * callback function for general checkbox.
   *
   * @since    1.0.0
   */

  public function wcmlim_location_mini_store_shortcode_cb()
  {
    echo '<p>' . __('Please change the settings accordingly.', 'wcmlim') . '</p>';
  }

  /**
   * callback function for location switch.
   *
   * @since    1.0.0
   * @Update   1.2.11
   */

  public function wcmlim_preferred_location_callback()
  {
    $isLocationSet = get_option($this->option_name . '_preferred_location');

    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_preferred_location') ?>"
        name="<?php esc_attr_e($this->option_name . '_preferred_location') ?>" <?php echo ($isLocationSet == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <label class="wcmlim-setting-option-des"><b><?php echo __('Shortcode Instructions: ', 'wcmlim'); ?></b><br>
      <?php echo __("To display a locations dropdown on your website, simply use the ", 'wcmlim'); ?><code>[wcmlim_locations_switch]</code>
      <?php echo __('shortcode.', 'wcmlim'); ?>
      <?php echo __(" You can put it anywhere into page content using editor just by copy-paste.", 'wcmlim'); ?><br>
    </label>
    <?php
  }
  public function wcmlim_location_popup_callback()
  {
    $locationpopup = get_option($this->option_name . '_location_popup');

    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_location_popup') ?>"
        name="<?php esc_attr_e($this->option_name . '_location_popup') ?>" <?php echo ($locationpopup == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <label class="wcmlim-setting-option-des"><b><?php echo __('Shortcode Instructions: ', 'wcmlim'); ?></b><br>
      <?php echo __("To display a locations popup on your website, simply use the ", 'wcmlim'); ?><code>[wcmlim_locations_popup]</code>
      <?php echo __('shortcode.', 'wcmlim'); ?>
      <?php echo __(' You can put it anywhere into page content using editor just by copy-paste.', 'wcmlim'); ?><br>
    </label>
    <?php
  }


  /**
   * Function for list mode on shortcode.
   *
   * @since    1.2.11     
   */
  public function wcmlim_listing_inline_location_callback()
  {

    $loc_listing = get_option($this->option_name . '_listing_inline_location');
    if ($loc_listing == "on") {
      update_option("wcmlim_show_in_popup", "list");
    }
    ?>
    <p>
      <label class="switch">
        <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_listing_inline_location') ?>"
          name="<?php esc_attr_e($this->option_name . '_listing_inline_location') ?>" <?php echo ($loc_listing == 'on') ? 'checked="checked"' : ''; ?>>
        <span class="slider round"></span>
      </label>
      <?php echo '<label class="wcmlim-setting-option-des">' . __('Enable this to display locations in listing format. ', 'wcmlim') . '</label>'; ?>
    </p>
    <?php
  }

  /**
   * callback function for Enabling Regular And Sale Price
   *
   * @since    1.0.0
   */

  public function wcmlim_enable_price_cb()
  {
    $checked = get_option($this->option_name . '_enable_price');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_price') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_price') ?>" <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br>
    <?php echo '<label class="wcmlim-setting-option-des">' . __("To enable the ability to set both regular prices and sale prices directly from the product page, you can implement this feature within your e-commerce platform or application.", 'wcmlim') . '</label>'; ?>
  <?php
  }

  public function wcmlim_location_fee_cb()
  {
    $checked = get_option($this->option_name . '_location_fee');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_location_fee') ?>"
        name="<?php esc_attr_e($this->option_name . '_location_fee') ?>" <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br>
    <?php echo '<label class="wcmlim-setting-option-des">' . __("Set the custom fee for each products location", 'wcmlim') . '</label>'; ?>
  <?php
  }


  /**
   * callback function for Enabling COGS Price
   *
   * 
   */
  public function wcmlim_enable_COGSprice_cb()
  {
    $checked = get_option($this->option_name . '_enable_COGSprice');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_COGSprice') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_COGSprice') ?>" <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br>
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Enable this to set COGS price for each location from all products page.', 'wcmlim') . '</label>'; ?>
    <?php echo '<span class="locationshow_note">' . __('<strong>Note:-</strong> <b>Regular price and Sales price for each location</b> setting should be active', 'wcmlim') . '</span>'; ?>
  <?php
  }


  /**
   * callback function for Enabling locations on shop
   *
   * @since    1.0.0
   */
  public function wcmlim_hide_outofstock_products_callback()
  {
    $hideOutOfStock = get_option($this->option_name . '_hide_outofstock_products');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_hide_outofstock_products') ?>"
        name="<?php esc_attr_e($this->option_name . '_hide_outofstock_products') ?>" <?php echo ($hideOutOfStock == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Enable this setting to show only the products which are in-stock at the selected location and hide out-of-stock products on the Shop page.', 'wcmlim') . '</label>'; ?>
  <?php
  }


  /**
   * callback function for Enabling locations on shop
   *
   * @since    1.1.8
   */

  public function wcmlim_enable_location_price_onshop_callback()
  {
    $isLocationPriceOnshop = get_option($this->option_name . '_enable_location_price_onshop');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_location_price_onshop') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_location_price_onshop') ?>" <?php echo ($isLocationPriceOnshop == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Enable this to Show location price for the selected location on the Shop page.', 'wcmlim') . '</label>'; ?>
  <?php
  }

  //removed old filter product on shop page option


  /**
   * *callback function for restirct users to specific locations
   *
   * @since    1.0.0
   */

  public function wcmlim_enable_userspecific_location_callback()
  {
    $userSpecific = get_option($this->option_name . '_enable_userspecific_location');


    ?>
    <label class="switch userRestrict">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_userspecific_location') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_userspecific_location') ?>" <?php echo ($userSpecific == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __("Enable this setting to set a default location for a specific user. This setting can be done in the edit location screen of the locations OR from the edit user screen of the available users.", 'wcmlim') . '</label>';
    ?>

    <?php
  }


  /**
   * *callback function for enable default location
   *
   * @since    1.2.5
   */

  public function wcmlim_enable_backorder_for_locations_callback()
  {
    $backorder_for_locations = get_option($this->option_name . '_enable_backorder_for_locations');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_backorder_for_locations') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_backorder_for_locations') ?>" <?php echo ($backorder_for_locations == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __("To enable the capability to set the backorder status for a specific product from its dedicated product page.", 'wcmlim') . '</label>'; ?>
  <?php
  }


  /**
   * *callback function for enable-disable locations
   *
   * @since    1.2.5
   */

  public function wcmlim_enable_specific_location_callback()
  {
    $specific_locations_for_product = get_option($this->option_name . '_enable_specific_location');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_specific_location') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_specific_location') ?>" <?php echo ($specific_locations_for_product == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php
    echo '<label class="wcmlim-setting-option-des">' .
      __("You have the option to enable or disable location-related features.", 'wcmlim') . '</label>'; ?>
    <?php echo '<span class="locationshow_note">' . __('<strong>Note:-</strong> You can choose between either <b>Enable Locations For Each Product</b> or <b>Hide the Location Dropdown/List on the Product Page.</b> Only one of these settings should be active at a time.', 'wcmlim') . '</span>'; ?>
  <?php
  }

  /**
   * *callback function for enable default location
   *
   * @since    3.3.0
   */

  public function wcmlim_enable_default_location_callback()
  {
    $_is_default = get_option($this->option_name . '_enable_default_location');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_default_location') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_default_location') ?>" <?php echo ($_is_default == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Enable this setting to set a default location for a specific product via the Edit Product page. This location will be preselected on the single product page.', 'wcmlim') . '</label>'; ?>
  <?php
  }


  /**
   * *callback function for cron options
   *
   * @since    1.2.5
   */
  public function wcmlim_cron_for_product_callback()
  {
    $cronf_product = get_option("wcmlim_cron_for_product");
    $cronf_product_ud = get_option("wcmlim_cron_for_product_userdefined"); ?>
    <select name="wcmlim_cron_for_product" id="wcmlim_cron_for_product">
      <option value="default"><?php _e('Select', 'wcmlim'); ?></option>
      <option value="hourly" <?php if ($cronf_product == 'hourly') {
        echo "selected='selected'";
      } ?>>
        <?php _e('Hourly', 'wcmlim'); ?>
      </option>
      <option value="daily" <?php if ($cronf_product == 'daily') {
        echo "selected='selected'";
      } ?>>
        <?php _e('Daily', 'wcmlim'); ?>
      </option>
      <option value="twicedaily" <?php if ($cronf_product == 'twicedaily') {
        echo "selected='selected'";
      } ?>>
        <?php _e('Twice a Day', 'wcmlim'); ?>
      </option>
    </select>
    or Every <input type="number" min="1" name="wcmlim_cron_for_product_userdefined" value="<?php if (!empty($cronf_product_ud)) {
      echo $cronf_product_ud;
    } ?>"> Minute
    <br />
    <label class="wcmlim-setting-option-des">
      <b>WARNING:</b> Activating this option will synchronize inventory levels to display the total stock across all
      locations for each product. We strongly recommend backing up your database or WooCommerce inventory before enabling
      this feature.
    </label>
    <?php

  }


  public function wcmlim_location_sorting_priority_cb() {
  }



  function check_location_group_callback()
  {
    $terms = get_terms(array('taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0));
    if (sizeof($terms) > 0) {
      echo 'true';
    } else {
      echo 'false';
    }
    wp_die();
  }
  
  /**
   * *callback function for enable tax for each item
   *
   * @since    1.1.8
   */

  public function wcmlim_enable_tax_to_each_item_callback()
  {
    $allow_tax_location = get_option($this->option_name . '_enable_tax_to_each_item');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_enable_tax_to_each_item') ?>"
        name="<?php esc_attr_e($this->option_name . '_enable_tax_to_each_item') ?>" <?php echo ($allow_tax_location == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Turning on this switch will allow to select set WC Tax For Each Line Item.', 'wcmlim') . '</label>'; ?>
  <?php
  }

  /**
   * *callback function for next closest location
   *
   * @since    1.1.5
   */
  public function wcmlim_next_closest_location_callback()
  {
    $nextCL = get_option($this->option_name . '_next_closest_location');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_next_closest_location') ?>"
        name="<?php esc_attr_e($this->option_name . '_next_closest_location') ?>" <?php echo ($nextCL == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __("It shows the closest stock location available in the store based on your search.", 'wcmlim') . '</label>'; ?>
    <?php echo '<span class="locationshow_note">' . __('<strong>Note:-</strong> You should first enable the Nearby Location Finder search box setting.', 'wcmlim') . '</span>'; ?>
  <?php
  }


  /**
   * *callback function for Default zoom for map
   *
   * @since    1.1.8
   */

  public function wcmlim_default_zoom_callback()
  {
    $default_zoom = get_option($this->option_name . '_default_zoom');
    if (empty($default_zoom)) {
      $default_zoom = update_option($this->option_name . '_default_zoom', '10');
    }
    $default_zoom = get_option($this->option_name . '_default_zoom');

    ?>
    <input type="number" id="<?php esc_attr_e($this->option_name . '_default_zoom') ?>"
      name="<?php esc_attr_e($this->option_name . '_default_zoom') ?>" value="<?php echo $default_zoom; ?>"
      placeholder="eg. 10">
    <br /><label><?php esc_html_e('Map will be load with given Default zoom level/scale', 'wcmlim'); ?></label>
    <?php
  }
  /**
   * *callback function for Default zoom for map
   *
   * @since    1.1.8
   */

  public function wcmlim_filter_visibility_shortcode_callback()
  {
    $filter_visibility_shortcode = get_option($this->option_name . '_filter_visibility_shortcode');
    if (!isset($filter_visibility_shortcode) && empty($filter_visibility_shortcode)) {
      $filter_visibility_shortcode = update_option($this->option_name . '_filter_visibility_shortcode', 'on');
    }
    $filter_visibility_shortcode = get_option($this->option_name . '_filter_visibility_shortcode');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_filter_visibility_shortcode') ?>"
        name="<?php esc_attr_e($this->option_name . '_filter_visibility_shortcode') ?>" <?php echo ($filter_visibility_shortcode == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br><label><?php esc_html_e('Show product/category filter on Location Finder', 'wcmlim'); ?></label>
    <?php
  }

  /**
   * callback function for product filter store locator
   *
   * @since    3.0.0
   */

  public function wcmlim_product_filter_store_locator_callback()
  {
    $product_filter_enabled = get_option($this->option_name . '_product_filter_store_locator');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_product_filter_store_locator') ?>"
        name="<?php esc_attr_e($this->option_name . '_product_filter_store_locator') ?>" <?php echo ($product_filter_enabled == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br><label><?php esc_html_e('Show product list on side with location map showing stock, price, and address for selected product', 'wcmlim'); ?></label>
    <?php
  }

  /**
   * *callback function for Default color for map
   *
   * @since    1.1.8
   */

  public function wcmlim_default_map_color_callback()
  {
    $map_theme_color = get_option($this->option_name . '_default_map_color');
    if ($map_theme_color == false) {
      update_option($this->option_name . '_default_map_color', '#187dc7');
    }
    ?>
    <input class="map_shortcode_wcmlim-setting-option-des color_field"
      id="map_shortcode_wcmlim-setting-option-des color_field" type="text"
      name="<?php esc_attr_e($this->option_name . '_default_map_color'); ?>"
      value="<?php esc_attr_e($map_theme_color); ?>" />
    <br /><label><?php esc_html_e('Set theme color for Location Finder Map/Location Finder List', 'wcmlim'); ?></label>
    <?php
  }

  /**
   * *callback function for Default origin center for map
   *
   * @since    1.1.8
   */

  public function wcmlim_default_origin_center_callback()
  {
    $default_origin_center = get_option($this->option_name . '_default_origin_center');
    ?>
    <input type="text" id="wcmlim_autocomplete_address"
      name="<?php esc_attr_e($this->option_name . '_default_origin_center') ?>"
      value="<?php echo $default_origin_center; ?>" placeholder="<?php esc_attr_e('Enter Address', 'wcmlim'); ?>">
    <br /><label><?php esc_html_e('Map will be load with given Default location as center', 'wcmlim'); ?></label>
    <?php
  }

  /**
   * *callback function for Default align location list map
   *
   * @since    1.1.8
   */

  public function wcmlim_default_list_align_callback()
  {
    $default_list_align = get_option($this->option_name . '_default_list_align');
    ?>
    <select name="<?php esc_attr_e($this->option_name . '_default_list_align') ?>"
      id="<?php esc_attr_e($this->option_name . '_default_list_align') ?>">
      <option value="default">
        <?php esc_html_e('Select Alignment', 'wcmlim'); ?>
      </option>
      <option value="right" <?php if ($default_list_align == 'right') {
        echo "selected='selected'";
      } ?>>
        <?php esc_html_e('Right Align', 'wcmlim'); ?>
      </option>
      <option value="left" <?php if ($default_list_align == 'left') {
        echo "selected='selected'";
      } ?>>
        <?php esc_html_e('Left Align', 'wcmlim'); ?>
      </option>
    </select>
    <br /><label><?php esc_html_e('Set Locations list alignment on Location Finder Map', 'wcmlim'); ?></label>
    <?php
  }

  /**
   * *callback function for Order Fulfilment
   *
   * @since    1.1.6
   */

  public function wcmlim_order_fulfil_edit_callback()
  {
    $order_fulfil_edit = get_option($this->option_name . '_order_fulfil_edit');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_order_fulfil_edit') ?>"
        name="<?php esc_attr_e($this->option_name . '_order_fulfil_edit') ?>" <?php echo ($order_fulfil_edit == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label><br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __('Enabling backend mode and selected any one options for order fulfilment rule. The stock levels of the Locations will get updated accordingly as per selecting.', 'wcmlim') . '</label>'; ?>
  <?php
  }

/**
   * *callback function to show location stock in backend only mode
   *
   * @since    1.1.8
   */

  public function wcmlim_backend_display_stock_callback()
  {
    $allow_only_backend = get_option($this->option_name . '_backend_display_stock');
    ?>
    <label class="switch">
      <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_backend_display_stock') ?>"
        name="<?php esc_attr_e($this->option_name . '_backend_display_stock') ?>" <?php echo ($allow_only_backend == 'on') ? 'checked="checked"' : ''; ?>>
      <span class="slider round"></span>
    </label>
    <br />
    <?php echo '<label class="wcmlim-setting-option-des">' . __("Enable this option to show location wise stock on product single page", 'wcmlim') . '</label>'; ?>
  <?php
  }

  public function wcmlim_backend_display_stock_view_callback() {
    // Get the selected view option from the database
    $selected_view = get_option($this->option_name . '_backend_display_stock_view');

    // Ensure the selected is default to list view if not set
    if (empty($selected_view)) {
      $selected_view = 'list_view';
      update_option($this->option_name . '_backend_display_stock_view', $selected_view);
    }        

    // Generate the field ID
    $field_id = $this->option_name . '_backend_display_stock_view';
    // Render the dropdown
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-vertical-setting">
        <label class="wcmlim-vertical-label">
          <strong><?php echo __('Location View Style', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(How locations appear on product page)</span>
        </label>
        <select class="wcmlim-wide-input" name="<?php echo esc_attr($field_id); ?>" id="<?php echo esc_attr($field_id); ?>">
            <option value="twocol_view" <?php selected($selected_view, 'twocol_view'); ?>>
                <?php _e('Two Column View', 'wcmlim'); ?>
            </option>
            <option value="threecol_view" <?php selected($selected_view, 'threecol_view'); ?>>
                <?php _e('Third Column View', 'wcmlim'); ?>
            </option>
            <option value="list_view" <?php selected($selected_view, 'list_view', true); ?>>
              <?php _e('List View', 'wcmlim'); ?>
            </option>
            <option value="card_view" <?php selected($selected_view, 'card_view'); ?>>
                <?php _e('Card View', 'wcmlim'); ?>
            </option>
            <option value="select_view" <?php selected($selected_view, 'select_view'); ?>>
                <?php _e('Select View', 'wcmlim'); ?>
            </option>
            <option value="table_view" <?php selected($selected_view, 'table_view'); ?>>
                <?php _e('Table View', 'wcmlim'); ?>
            </option>
            <option value="expanded_view" <?php selected($selected_view, 'expanded_view'); ?>>
                <?php _e('Expanded View', 'wcmlim'); ?>
            </option>
            <option value="simple_text_view" <?php selected($selected_view, 'simple_text_view'); ?>>
                <?php _e('Simple View', 'wcmlim'); ?>
            </option>
            <option value="drawer_view" <?php selected($selected_view, 'drawer_view'); ?>>
                <?php _e('Drawer View', 'wcmlim'); ?>
            </option>
            <option value="popup_view" <?php selected($selected_view, 'popup_view'); ?>>
                <?php _e('Popup View', 'wcmlim'); ?>
            </option>
        </select>
      </div>
    </div>
    <hr>
    <?php
}

  /**
   * Callback function for Maximum Location Count setting
   *
   * @since    1.0.0
   */
  public function wcmlim_maximum_location_count_callback() {
    // Get the saved value from the database
    $max_count = get_option($this->option_name . '_maximum_location_count', '');
    
    // Generate the field ID
    $field_id = $this->option_name . '_maximum_location_count';
    
    // Render the input field
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-vertical-setting">
        <label class="wcmlim-vertical-label">
          <strong><?php echo __('Maximum Location Count', 'wcmlim'); ?></strong> 
          <span class="wcmlim-label-desc">(Limit the number of visible locations on frontend)</span>
        </label>
        <input 
          type="number" 
          class="wcmlim-wide-input" 
          name="<?php echo esc_attr($field_id); ?>" 
          id="<?php echo esc_attr($field_id); ?>" 
          value="<?php echo esc_attr($max_count); ?>"
          min="1"
          step="1"
          placeholder="<?php _e('Leave empty for unlimited', 'wcmlim'); ?>"
          style="width: 300px;"
        />
        <p class="description">
          <?php _e('Enter the maximum number of locations to display. Leave empty to show all locations. This limit is applied to visible locations after all other filters (out of stock hiding, user restrictions, etc.).', 'wcmlim'); ?>
        </p>
      </div>
    </div>
    <hr>
    <?php
  }



public function wcmlim_backend_display_feilds_settings_callback(){
  // Option name for section order
  $order_option_name = $this->option_name . '_backend_display_feilds_settings_order';

  $default_section_keys = array('general', 'address', 'location_note', 'contact', 'business_hours', 'google_rating');

  // Get saved order or use default
  $saved_order = get_option($order_option_name, $default_section_keys);
  if (!is_array($saved_order) || count($saved_order) !== count($default_section_keys)) {
    $saved_order = $default_section_keys;
  }

  // Get the saved value of the fields (ensure it's always an array)
  $settings = get_option('wcmlim_backend_display_feilds_settings', []);

  if (!is_array($settings)) {
    $settings = [];
  }

  $sections = [
    'general' => [
      'title' => 'General',
      'fields' => [
        'distance' => 'Distance'
      ]
    ],
    'address' => [
      'title' => 'Address Fields',
      'fields' => [
        'street_number' => 'Street Number',
        'route' => 'Route',
        'locality' => 'Locality',
        'postcode' => 'Postcode',
        'country' => 'Country'
      ]
    ],
    'location_note' => [
      'title' => 'Location Note',
      'fields' => [
        'location_note' => 'Location Note'
      ]
    ],
    'contact' => [
      'title' => 'Contact Details',
      'fields' => [
        'email' => 'Email',
        'phone' => 'Phone'
      ]
    ],
    'business_hours' => [
      'title' => 'Business Hours',
      'fields' => [
        'start_time' => 'Start Time',
        'end_time' => 'End Time'
      ]
    ],
    'google_rating' => [
      'title' => 'Google Rating',
      'fields' => [
        'google_rating' => 'Google Star Rating & Review Count'
      ]
    ],
  ];

  // UI: Section titles in sortable rows with view button
  // Title and short description
  echo '<div id="wcmlim-fields-settings-container">';
  ?>
  <label class="wcmlim-vertical-label">
          <strong><?php echo __('Location Fields Display Settings', 'wcmlim'); ?></strong>
        </label>
  <?php
  // echo '<h4 style="margin-bottom:6px;">Location Fields Display Settings</h4>';
  echo '<p class="description" style="margin-bottom:12px;">' . __('Choose which fields to display for each location on the product page. Drag sections to reorder them. Postcode and Country are always shown.', 'wcmlim') . '</p>';

  echo '<ul id="wcmlim-fields-sections-sortable">';
  foreach ($saved_order as $section_key) {
      if (!isset($sections[$section_key])) continue;
      $section = $sections[$section_key];
      echo '<li class="wcmlim-fields-section-row" data-section="' . esc_attr($section_key) . '">';
      // Hamburger icon for drag (left)
      echo '<span class="wcmlim-hamburger-icon" style="margin-right:8px;cursor:grab;display:inline-block;width:12px;vertical-align:middle;">
        <span style="display:block;height:2px;background:#888;margin:2px 0;border-radius:1px;"></span>
        <span style="display:block;height:2px;background:#888;margin:2px 0;border-radius:1px;"></span>
        <span style="display:block;height:2px;background:#888;margin:2px 0;border-radius:1px;"></span>
      </span>';
      // Title (left)
      echo '<span class="wcmlim-section-title" style="text-align:left;flex:1;">' . esc_html($section['title']) . '</span>';
      // Settings icon (right)
      echo '<button type="button" class="wcmlim-view-fields-btn" data-section="' . esc_attr($section_key) . '" title="Edit Fields" style="margin-left:auto;">';
      echo '<span class="dashicons dashicons-admin-generic wcmlim-settings-icon" id="wcmlim-settings-' . esc_attr($section_key) . '"></span>';
      echo '</button>';
      
      // Toggle switch
      $section_enabled = false;
      foreach ($section['fields'] as $field_key => $label) {
          if (in_array($field_key, $settings)) {
              $section_enabled = true;
              break;
          }
      }
      $toggle_class = $section_enabled ? 'enabled' : 'disabled';
      echo '<div class="wcmlim-toggle-wrapper" style="margin-left:10px;">';
      echo '<label class="wcmlim-toggle-switch" data-section="' . esc_attr($section_key) . '">';
      echo '<input type="checkbox" class="wcmlim-section-toggle" data-section="' . esc_attr($section_key) . '" ' . ($section_enabled ? 'checked' : '') . '>';
      echo '<span class="wcmlim-toggle-slider ' . $toggle_class . '"></span>';
      echo '</label>';
      echo '</div>';
      
      // Hidden input for order - this will be saved by WordPress settings API
      echo '<input type="hidden" name="' . esc_attr($order_option_name) . '[]" value="' . esc_attr($section_key) . '" />';
      echo '</li>';
  }
  echo '</ul>';
  echo '</div>';

  // Popups for each section
  foreach ($sections as $section_key => $section) {
    echo '<div class="wcmlim-fields-popup" id="wcmlim-popup-' . esc_attr($section_key) . '" style="display:none;">';
    echo '<div class="wcmlim-popup-content">';
    echo '<h3>' . esc_html($section['title']) . '</h3>';
    
    // Special handling for Google Rating section - show Place ID table
    if ($section_key === 'google_rating') {
      echo '<p class="description" style="margin-bottom:15px;">' . __('Enter the Google Place ID for each location to display ratings and reviews.', 'wcmlim') . '</p>';
      
      // Get all locations
      $all_locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
      
      if (!empty($all_locations) && !is_wp_error($all_locations)) {
        echo '<table class="wcmlim-place-id-table" style="width:100%;border-collapse:collapse;margin-bottom:20px;">';
        echo '<thead>';
        echo '<tr style="background:#f5f5f5;border-bottom:2px solid #ddd;">';
        echo '<th style="padding:10px;text-align:left;font-weight:600;">' . __('Location Name', 'wcmlim') . '</th>';
        echo '<th style="padding:10px;text-align:left;font-weight:600;">' . __('Google Place ID', 'wcmlim') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        foreach ($all_locations as $location) {
          $place_id = get_term_meta($location->term_id, 'place_id', true);
          echo '<tr style="border-bottom:1px solid #eee;">';
          echo '<td style="padding:10px;font-weight:500;">' . esc_html($location->name) . '</td>';
          echo '<td style="padding:10px;">';
          echo '<input type="text" name="wcmlim_place_id[' . esc_attr($location->term_id) . ']" value="' . esc_attr($place_id) . '" placeholder="' . esc_attr__('Enter Place ID', 'wcmlim') . '" style="width:100%;padding:6px 10px;border:1px solid #ddd;border-radius:3px;" />';
          echo '</td>';
          echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';
        
        echo '<p class="description" style="font-size:12px;color:#666;margin-bottom:15px;">';
        echo '💡 <strong>' . __('How to find Place ID:', 'wcmlim') . '</strong> ' . sprintf(__('Visit %s or use the Places API to find your location\'s Place ID.', 'wcmlim'), '<a href="https://developers.google.com/maps/documentation/places/web-service/place-id" target="_blank">' . __('Google Place ID Finder', 'wcmlim') . '</a>');
        echo '</p>';
      }
    }
    
    echo '<ul class="wcmlim-fields-list">';
    foreach ($section['fields'] as $field_key => $label) {
      $checked = in_array($field_key, $settings) ? 'checked' : '';
      echo '<li>';
      echo '<input type="checkbox" name="wcmlim_backend_display_feilds_settings[]" class="wcmlim-location_fields_display" value="' . esc_attr($field_key) . '" ' . $checked . '>';
      echo '<label>' . esc_html($label) . '</label>';
      echo '</li>';
      if ($field_key == 'distance') {
        echo '<select name="wcmlim_distance_unit" id="wcmlim_distance_unit">';
        echo '<option value="km" ' . (get_option('wcmlim_location_distance_unit') === 'km' ? 'selected' : '') . '>';
        _e('Kilometers', 'wcmlim');
        echo '</option>';
        echo '<option value="miles" ' . (get_option('wcmlim_location_distance_unit') === 'miles' ? 'selected' : '') . '>';
        _e('Miles', 'wcmlim');
        echo '</option>';
        echo '</select>';
        echo '<p>' . __('Select the distance unit to display (Kilometers or Miles).', 'wcmlim') . '</p>';
      }
    }
    echo '</ul>';
    echo '<button type="button" class="wcmlim-popup-close">' . __('Close', 'wcmlim') . '</button>';
    echo '</div>';
    echo '</div>';
  }

  // Styles
  echo '<style>
  #wcmlim-fields-sections-sortable { list-style-type: none; padding: 0; margin: 0; }
  .wcmlim-fields-section-row { display: flex; align-items: center; justify-content: flex-start; padding: 8px 12px; margin-bottom: 6px; background: #f9f9f9; border: 1px solid #eee; border-radius: 3px; transition: all 0.3s ease; height: 15px; }
  .wcmlim-fields-section-row:hover { background: #f0f0f0; }
  .wcmlim-fields-section-row.disabled { background: #f5f5f5; color: #999; }
  .wcmlim-fields-section-row.disabled .wcmlim-section-title { color: #999; }
  .wcmlim-fields-section-row.disabled .wcmlim-view-fields-btn { opacity: 0.5; pointer-events: none; }
  .wcmlim-hamburger-icon { cursor: grab !important; transition: opacity 0.2s; }
  .wcmlim-hamburger-icon:hover { opacity: 0.7; }
  .wcmlim-hamburger-icon:active { cursor: grabbing !important; }
  .wcmlim-section-title { font-size: 14px; font-weight: 600; text-align:left; flex:1; }
  
  /* Toggle Switch Styles */
  .wcmlim-toggle-wrapper { display: flex; align-items: center; }
  .wcmlim-toggle-switch { position: relative; display: inline-block; width: 28px; height: 14px; margin: 0; }
  .wcmlim-toggle-switch input { opacity: 0; width: 0; height: 0; }
  .wcmlim-toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .3s; border-radius: 14px; }
  .wcmlim-toggle-slider:before { position: absolute; content: ""; height: 10px; width: 10px; left: 2px; bottom: 2px; background-color: white; transition: .3s; border-radius: 50%; }
  .wcmlim-toggle-switch input:checked + .wcmlim-toggle-slider { background-color: #2196F3; }
  .wcmlim-toggle-switch input:checked + .wcmlim-toggle-slider:before { transform: translateX(14px); }
  .wcmlim-toggle-slider.enabled { background-color: #2196F3; }
  .wcmlim-toggle-slider.disabled { background-color: #ccc; }
  .wcmlim-view-fields-btn { margin-left:auto; background: none; border: none; cursor: pointer; padding: 4px; }
  .wcmlim-settings-icon { font-size: 16px !important; vertical-align: middle; }
  .wcmlim-fields-popup { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.3); z-index: 9999; display: flex; align-items: center; justify-content: center; }
  .wcmlim-popup-content { background: #fff; padding: 25px 20px; border-radius: 6px; min-width: 320px; box-shadow: 0 2px 16px rgba(0,0,0,0.15); }
  .wcmlim-fields-list { list-style-type: none; padding: 0; margin: 0; }
  .wcmlim-fields-list li { display: flex; align-items: center; margin-bottom: 8px; }
  .wcmlim-fields-list label { margin-left: 6px; font-size: 14px; }
  .wcmlim-popup-close { margin-top: 15px; background: #187dc7; color: #fff; border: none; border-radius: 3px; padding: 6px 16px; cursor: pointer; font-size: 13px; }
  .ui-sortable-helper { box-shadow: 0 3px 6px rgba(0,0,0,0.15); transform: rotate(1deg); }
  .ui-sortable-placeholder { background: #e1f5fe !important; border: 2px dashed #0073aa !important; height: 36px !important; }
  </style>';

  // Scripts for sortable and popup (no animation)
  echo '<script>
  jQuery(function($){
    // Sortable rows
    $("#wcmlim-fields-sections-sortable").sortable({
      axis: "y",
      handle: ".wcmlim-hamburger-icon",
      cursor: "move",
      update: function(event, ui) {
        // Update hidden input values based on new order
        $("#wcmlim-fields-sections-sortable li").each(function(index) {
          var sectionKey = $(this).data("section");
          // Update the hidden input value to match the new order
          $(this).find("input[type=\"hidden\"]").val(sectionKey);
        });
      }
    });

    // Function to update toggle state based on checkboxes
    function updateToggleState(section) {
      var popup = $("#wcmlim-popup-" + section);
      var checkboxes = popup.find("input[type=\"checkbox\"].wcmlim-location_fields_display");
      var hasChecked = checkboxes.is(":checked");
      var toggle = $(".wcmlim-section-toggle[data-section=\"" + section + "\"]");
      var sectionRow = $(".wcmlim-fields-section-row[data-section=\"" + section + "\"]");
      
      if (hasChecked) {
        toggle.prop("checked", true);
        toggle.siblings(".wcmlim-toggle-slider").removeClass("disabled").addClass("enabled");
        sectionRow.removeClass("disabled");
      } else {
        toggle.prop("checked", false);
        toggle.siblings(".wcmlim-toggle-slider").removeClass("enabled").addClass("disabled");
        sectionRow.addClass("disabled");
      }
    }
    
    // Function to get section from toggle
    function getSectionFromToggle(toggle) {
      return toggle.data("section");
    }

    // Toggle switch functionality
    $(".wcmlim-section-toggle").on("change", function(){
      var isEnabled = $(this).is(":checked");
      var section = getSectionFromToggle($(this));
      var popup = $("#wcmlim-popup-" + section);
      var checkboxes = popup.find("input[type=\"checkbox\"].wcmlim-location_fields_display");
      var sectionRow = $(".wcmlim-fields-section-row[data-section=\"" + section + "\"]");
      
      if (isEnabled) {
        // Enable toggle - check all checkboxes
        checkboxes.prop("checked", true);
        $(this).siblings(".wcmlim-toggle-slider").removeClass("disabled").addClass("enabled");
        sectionRow.removeClass("disabled");
      } else {
        // Disable toggle - uncheck all checkboxes
        checkboxes.prop("checked", false);
        $(this).siblings(".wcmlim-toggle-slider").removeClass("enabled").addClass("disabled");
        sectionRow.addClass("disabled");
      }
    });

    // Monitor checkbox changes to update toggle state
    $(document).on("change", "input[type=\"checkbox\"].wcmlim-location_fields_display", function(){
      var popup = $(this).closest(".wcmlim-fields-popup");
      var section = popup.attr("id").replace("wcmlim-popup-", "");
      updateToggleState(section);
    });

    // Initial state check for all sections
    $(".wcmlim-fields-section-row").each(function(){
      var section = $(this).data("section");
      updateToggleState(section);
    });

    // Popup logic (no animation)
    $(".wcmlim-view-fields-btn").on("click", function(){
      var section = $(this).data("section");
      $("#wcmlim-popup-"+section).show();
    });
    $(".wcmlim-popup-close").on("click", function(){
      $(this).closest(".wcmlim-fields-popup").hide();
    });
    // Close popup on outside click
    $(".wcmlim-fields-popup").on("click", function(e){
      if(e.target === this){ $(this).hide(); }
    });
  });
  </script>';

}
  /**
   * callback function for display settings checkbox.
   *
   * @since    1.0.0
   */

  public function wcmlim_display_settings_cb()
  {
    echo '<p>' . __('Please change the settings accordingly.', 'wcmlim') . '</p>';
  }

  /**
   * callback function for location select options.
   *
   * @since    1.0.0
   */

  public function wcmlim_location_select_cb()
  {
    $checked = get_option($this->option_name . '_location_select');
    ?>
    <label for="wcmlim_location_select_none">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_location_select') ?>"
        id="wcmlim_location_select_none" <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('None', 'wcmlim'); ?>
    </label>

    <label for="wcmlim_location_select_dropdown">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_location_select') ?>"
        id="wcmlim_location_select_dropdown" <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Dropdown', 'wcmlim'); ?>
    </label>
    <?php
  }

  /**
   * callback function for Enabling search nearest location
   *
   * @since    1.0.0
   */

  public function wcmlim_search_nearest_location_cb()
  {
    $searchNearest = get_option($this->option_name . '_search_nearest_location');
    ?>
    <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_search_nearest_location') ?>"
      name="<?php esc_attr_e($this->option_name . '_search_nearest_location') ?>" <?php echo ($searchNearest == 'on') ? 'checked="checked"' : ''; ?>>
    <?php
  }

  /**
   * callback function for button style options.
   *
   * @since    1.0.0
   */

  public function wcmlim_button_style_cb()
  {
    $checked = get_option($this->option_name . '_button_style');
    ?>
    <label for="wcmlim_button_style_one">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_button_style') ?>" id="wcmlim_button_style_one"
        <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Style 1', 'wcmlim'); ?>
    </label>

    <label for="wcmlim_button_style_two">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_button_style') ?>" id="wcmlim_button_style_two"
        <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Style 2', 'wcmlim'); ?>
    </label>

    <label for="wcmlim_button_style_three">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_button_style') ?>" id="wcmlim_button_style_three"
        <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Style 3', 'wcmlim'); ?>
    </label>
    <?php
  }

  /**
   * callback function for button text options.
   *
   * @since    1.0.0
   */

  public function wcmlim_button_text_cb()
  {
    $button_text = get_option($this->option_name . '_button_text');
    ?>
    <input type="text" name="<?php esc_attr_e($this->option_name . '_button_text'); ?>"
      id="<?php esc_attr_e($this->option_name . '_button_text'); ?>" value="<?php esc_attr_e($button_text); ?>">
    <br>
    <p><?php echo __('text to appear on the bottom', 'wcmlim'); ?></p>
    <?php
  }

  /**
   * callback function for button color options.
   *
   * @since    1.0.0
   */

  public function wcmlim_button_color_cb()
  {
    $button_color = get_option($this->option_name . '_button_color');
    ?>
    <input type="text" name="<?php esc_attr_e($this->option_name . '_button_color'); ?>"
      id="<?php esc_attr_e($this->option_name . '_button_color'); ?>" value="<?php esc_attr_e($button_color); ?>">
    <br>
    <p><?php echo __('Hex color of the bottom', 'wcmlim'); ?></p>
    <?php
  }

  /**
   * callback function for button border radius options.
   *
   * @since    1.0.0
   */

  public function wcmlim_button_border_radius_cb()
  {
    $button_radius = get_option($this->option_name . '_button_border_radius');
    ?>
    <input type="text" name="<?php esc_attr_e($this->option_name . '_button_border_radius'); ?>"
      id="<?php esc_attr_e($this->option_name . '_button_border_radius'); ?>" value="<?php esc_attr_e($button_radius); ?>">
    <br>
    <p><?php echo __('Level of curve on design (0px for no curves)', 'wcmlim'); ?></p>
    <?php
  }

  /**
   * callback function for stock level number options.
   *
   * @since    1.0.0
   */

  public function wcmlim_show_stocklevel_numbers_cb()
  {
    $stockNumber = get_option($this->option_name . '_show_stocklevel_numbers');
    ?>
    <label for="wcmlim_show_stocklevel_numbers_yes">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_show_stocklevel_numbers') ?>"
        id="wcmlim_show_stocklevel_numbers_yes" <?php echo ($stockNumber == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Yes', 'wcmlim'); ?>
    </label>

    <label for="wcmlim_show_stocklevel_numbers_no">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_show_stocklevel_numbers') ?>"
        id="wcmlim_show_stocklevel_numbers_no" <?php echo ($stockNumber == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('No', 'wcmlim'); ?>
    </label>
    <?php
  }

  /**
   * callback function for suggested location options.
   *
   * @since    1.0.0
   */

  public function wcmlim_suggested_location_cb()
  {
    $suggestLocation = get_option($this->option_name . '_suggested_location');
    ?>
    <label for="wcmlim_suggested_location_yes">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_suggested_location') ?>"
        id="wcmlim_suggested_location_yes" <?php echo ($suggestLocation == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('Yes', 'wcmlim'); ?>
    </label>

    <label for="wcmlim_suggested_location_no">
      <input type="radio" name="<?php esc_attr_e($this->option_name . '_suggested_location') ?>"
        id="wcmlim_suggested_location_no" <?php echo ($suggestLocation == 'on') ? 'checked="checked"' : ''; ?> />
      <?php echo __('No', 'wcmlim'); ?>
    </label>
    <?php
  }

  /**
   * callback function for suggested location distance options.
   *
   * @since    1.0.0
   */

  public function wcmlim_suggested_location_distance_cb()
  {
    $suggested_dis = get_option($this->option_name . '_suggested_location_distance');
    ?>
    <input type="text" name="<?php esc_attr_e($this->option_name . '_suggested_location_distance'); ?>"
      id="<?php esc_attr_e($this->option_name . '_suggested_location_distance'); ?>"
      value="<?php esc_attr_e($suggested_dis); ?>">
    <?php
  }

  /**
   * callback function for custom css enable or not.
   *
   * @since    1.2.4
   */


  
  /**
   * callback function for show location distance options.
   *
   * @since    1.1.4
   */
  public function wcmlim_exclude_locations_from_frontend_cb()
  {
    $excludedLocations = get_option($this->option_name . '_exclude_locations_from_frontend');
    $restrictGuest = get_option('wcmlim_enable_restrict_guestuser_location');
    $selectedGuestLoc = get_option('wcmlim_restrict_guest_user_location');

    // Determine if the selected guest location should be hidden
    $hideSelectedGuestLoc = ($restrictGuest === 'on');

    ?>
    <select multiple="multiple" class="multiselect" name="wcmlim_exclude_locations_from_frontend[]"
      id="wcmlim_exclude_locations_from_frontend" data-placeholder="Select Some Locations">
      <?php
      $args = ['taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0];
      $all_locations = get_terms($args);

      foreach ((array) $all_locations as $location) {
        // Check if the current location is the selected guest location and if it should be hidden
        if ($hideSelectedGuestLoc && $location->term_id == $selectedGuestLoc) {
          continue;
        }
        ?>
        <option value="<?php echo esc_attr($location->term_id); ?>" <?php if (!empty($excludedLocations) && in_array($location->term_id, $excludedLocations)) {
             echo 'selected="selected"';
           } ?>>
          <?php echo esc_html($location->name); ?>
        </option>
      <?php } ?>
    </select>
    <br />
    <!-- Add Validation to "Exclude all locations" settings - User should not be able to exclude all locations - code init -->
    <p class="exclude_prod_onfront"></p>
    <!-- Add Validation to "Exclude all locations" settings - User should not be able to exclude all locations - code init -->
    <label class="wcmlim-setting-option-des"><?php _e("Select specific locations to exclude from showing your customers.
", 'wcmlim'); ?></label>
    <?php
  }

  /**
   * Removed default taxonomy coloumn and add new one.
   *
   * @since    1.0.0
   */

  public function wcmlim_remove_default_tcoloumn($columns)
  {
    unset($columns['taxonomy-locations']);
    return array_slice($columns, 0, 5, true)
      + array('stock_at_locations' => __('Stock at Locations', 'wcmlim'))
      + array_slice($columns, 5, NULL, true);
    return $columns;
  }

  /**
   * Add location price coloumn.
   *
   * @since    1.0.0
   */

  public function wcmlim_add_price_at_location_tcoloumn($columns)
  {
    $new_columns = array();

    foreach ($columns as $column_name => $column_info) {

      $new_columns[$column_name] = $column_info;

      if ('stock_at_locations' === $column_name) {
        $new_columns['price_at_locations'] = __('Price at Locations', 'wcmlim');
      }
    }

    return $new_columns;
  }


  /**
   * Returns new taxonomy coloumn.
   *
   * @since    1.0.0
   */

  public function wcmlim_populate_locations_column($column_name)
  {
    if ($column_name !== 'stock_at_locations') {
      return;
    }

    $product_id = get_the_ID();

    // Render a placeholder with an edit button and unique identifier
    echo '<div class="wcmlim-locations-placeholder" data-product-id="' . esc_attr($product_id) . '">
               Loading...
             </div>';
  }


  public function wcmlim_populate_stock_column($column_name)
  {
    if ($column_name === 'is_in_stock') {
      $isExcludeLocation = get_option("wcmlim_exclude_locations_from_frontend");

      // Retrieve location terms
      $term_args = [
        'taxonomy' => 'locations',
        'hide_empty' => false,
        'parent' => 0,
      ];
      $terms = get_terms($term_args);
      
      // Filter out excluded locations while preserving array keys
      if (!empty($isExcludeLocation)) {
        foreach ($terms as $key => $term) {
          if (in_array($term->term_id, $isExcludeLocation)) {
            unset($terms[$key]);
          }
        }
      }

      // Ensure terms are available
      if (empty($terms)) {
        return;
      }

      $p_id = get_the_ID();
      $product = wc_get_product($p_id);

      if (!$product || !$product->is_type("variable")) {
        return;
      }

      $variations = $product->get_available_variations();
      $is_in_stock = false;

      // Check stock status for variations and terms
      foreach ($variations as $variation) {
        $variation_id = $variation['variation_id'];

        foreach ($terms as $term) {
          $stock_at_location = get_post_meta($variation_id, "wcmlim_stock_at_{$term->term_id}", true);
          if (!empty($stock_at_location) && (int) $stock_at_location > 0) {
            $is_in_stock = true;
            break 2; // Exit both loops as soon as stock is found
          }
        }
      }

      // Update stock status based on the result
      $new_status = $is_in_stock ? 'instock' : 'outofstock';
      $current_status = get_post_meta($p_id, '_stock_status', true);

      if ((int) $current_status !== $new_status) {
        update_post_meta($p_id, '_stock_status', $new_status);
      }
    }
  }

  /**
   * Returns new Location Price coloumn.
   *
   * @since    1.2.9
   */

  function wcmlim_populate_price_locations_column($column_name)
  {

    if ($column_name == 'price_at_locations') {
      $cuser = wp_get_current_user();
      $cuserId = $cuser->ID;
      $cuserRoles = $cuser->roles;
      $product = wc_get_product(get_the_ID());

      if (!empty($product)) {
        $variations_products = array();

        if (!empty($product) && $product->is_type('variable')) {
          $product_variations_ids = $product->get_children();
          $product_variations = array();
          foreach ($product_variations_ids as $variation_id) {
            $product_variations[] = $product->get_available_variation($variation_id);
          }
          foreach ($product_variations as $variation) {
            $variations_products[] = wc_get_product($variation['variation_id']);
          }
        }

        $args = ['taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0];
        $locations = get_terms($args);
        if ($product->is_type('simple')) {
          echo '<label>#' . $product->get_id() . ':</label><br>';
          $this->show_price_locations_in_column($product->get_id(), $locations, $cuserId, $cuserRoles);
        } elseif ($product->is_type('variable')) {
          echo '<label>#' . $product->get_id() . ':</label><br>';
          $this->show_price_locations_in_column($product->get_id(), $locations, $cuserId, $cuserRoles);
          if (!empty($variations_products)) {
            foreach ($variations_products as $variation_product) {
              foreach ($attributes = $variation_product->get_variation_attributes() as $attribute) {
                echo '<label>#' . $variation_product->get_id() . ' (' . ucfirst($attribute) . '):</label><br>';
              }
              $this->show_price_locations_variations_in_column($variation_product->get_id(), $locations, $cuserId, $cuserRoles);
            }
          }
        }
      }
    }
  }

  /**
   * Render price fields with placeholders (no actual prices loaded yet).
   */
  private function render_price_fields($product_id, $locations, $is_placeholder = false)
  {
    foreach ($locations as $location) {
      echo '<div class="wcmlim-price-location" data-location-id="' . esc_attr($location->term_id) . '" data-product-id="' . esc_attr($product_id) . '">';
      echo '<span>' . esc_html($location->name) . ':</span> ';

      // Display placeholder text for prices
      echo 'Regular Price: <span class="wcmlim-price" data-price-type="regular">Loading...</span>';
      echo ' Sale Price: <span class="wcmlim-price" data-price-type="sale">Loading...</span>';

      // Add quick edit buttons for prices
      echo '<button class="wcmlim-quick-edit-price" data-product-id="' . esc_attr($product_id) . '" data-location-id="' . esc_attr($location->term_id) . '" data-price-type="regular">Edit Regular Price</button>';
      echo '<button class="wcmlim-quick-edit-price" data-product-id="' . esc_attr($product_id) . '" data-location-id="' . esc_attr($location->term_id) . '" data-price-type="sale">Edit Sale Price</button>';
      echo '</div>';
    }
  }


  /**
   * Replaced stock column to sync and show stock qty
   *
   * @since    3.3.7
   */
  public function wcmlim_filter_woocommerce_admin_stock_html($stock_html, $product)
  {
    global $wpdb;

    $product_id = $product->get_id();
    $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    $manage_stock = $product->get_manage_stock();
    $stockQty = 0;

    // Preload all stock meta for this product and variations
    $meta_keys = array_map(function ($term) {
      return "wcmlim_stock_at_{$term->term_id}";
    }, $terms);

    // Fetch stock meta for simple and variations in one query
    $meta_data = $wpdb->get_results(
      $wpdb->prepare(
        "
            SELECT meta_key, meta_value
            FROM {$wpdb->postmeta}
            WHERE post_id = %d AND meta_key IN ('" . implode("','", $meta_keys) . "')
            ",
        $product_id
      ),
      OBJECT_K
    );

    // Calculate stock quantity for simple product
    if ($product->is_type("simple")) {
      foreach ($terms as $term) {
        $stock_at_location = isset($meta_data["wcmlim_stock_at_{$term->term_id}"])
          ? (int) $meta_data["wcmlim_stock_at_{$term->term_id}"]->meta_value
          : 0;
        $stockQty += max(0, $stock_at_location);
      }

      // Update stock meta only if there's a change
      $current_stock = get_post_meta($product_id, '_stock', true);
      if ((int) $current_stock !== $stockQty) {
        update_post_meta($product_id, '_stock', $stockQty);
        update_post_meta($product_id, '_stock_status', $stockQty > 0 ? 'instock' : 'outofstock');
      }
    }

    // Calculate stock for variable product
    elseif ($product->is_type("variable")) {
      $variations = $product->get_available_variations();
      $variation_ids = wp_list_pluck($variations, 'variation_id');

      foreach ($variation_ids as $variation_id) {
        $variation_meta_data = $wpdb->get_results(
          $wpdb->prepare(
            "
                    SELECT meta_key, meta_value
                    FROM {$wpdb->postmeta}
                    WHERE post_id = %d AND meta_key IN ('" . implode("','", $meta_keys) . "')
                    ",
            $variation_id
          ),
          OBJECT_K
        );

        $variation_stockQty = 0;
        foreach ($terms as $term) {
          $stock_at_location = isset($variation_meta_data["wcmlim_stock_at_{$term->term_id}"])
            ? (int) $variation_meta_data["wcmlim_stock_at_{$term->term_id}"]->meta_value
            : 0;
          $variation_stockQty += max(0, $stock_at_location);
        }

        // Update variation stock only if there's a change
        $current_variation_stock = get_post_meta($variation_id, '_stock', true);
        if ((int) $current_variation_stock !== $variation_stockQty) {
          update_post_meta($variation_id, '_stock', $variation_stockQty);
          update_post_meta($variation_id, '_stock_status', $variation_stockQty > 0 ? 'instock' : 'outofstock');
        }

        $stockQty += $variation_stockQty;
      }

      // Update parent product stock if needed
      $current_stock = get_post_meta($product_id, '_stock', true);
      if ((int) $current_stock !== $stockQty) {
        update_post_meta($product_id, '_stock', $stockQty);
        update_post_meta($product_id, '_stock_status', $stockQty > 0 ? 'instock' : 'outofstock');
      }
    }

    // Generate stock HTML based on updated stock
    $stock_html = $stockQty > 0
      ? '<mark class="instock">' . esc_html__("In stock", "woocommerce") . '</mark> (' . esc_html($stockQty) . ')'
      : '<mark class="outofstock">' . esc_html__("Out of stock", "woocommerce") . '</mark>';

    return $stock_html;
  }



  public function wcmlim_get_stock_label_with_check_variations_stock($variable_id)
  {
    $product = wc_get_product($variable_id);
    $variations_products = array();
    if (!empty($product) && $product->is_type('variable')) {
      $product_variations_ids = $product->get_children();
      $product_variations = array();
      foreach ($product_variations_ids as $variation_id) {
        $product_variations[] = $product->get_available_variation($variation_id);
      }
      foreach ($product_variations as $variation) {
        $variations_products[] = wc_get_product($variation['variation_id']);
      }
    }

    $at_least_stock = 0;

    if (!empty($variations_products)) {
      foreach ($variations_products as $variation_product) {
        $var_id = $variation_product->get_id();
        $var_stock_status = $variation_product->get_stock_status();

        if ($var_stock_status == "instock") {
          $at_least_stock = 1;
        }
      }
    }

    if ($at_least_stock == 1) {
      return '<mark class="instock">' . esc_html("In Stock", "woocommerce") . '</mark>';
    } else {
      return '<mark class="outofstock">' . esc_html("Out of stock", "woocommerce") . '</mark>';
    }
  }

  /**
   * Show data in new taxonomy coloumn.
   *
   * @since    1.0.0
   */

  function show_locations_in_column($product_id, $locations, $cuserId, $cuserRoles)
  {

    if (!empty($locations)) {
      $product = wc_get_product($product_id);
      $restock = 0;
      foreach ($locations as $location) {
        $prod_name = $product->get_name();
        $loc_stock = get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true);
        $shopM = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
        $restock += intval($loc_stock);

        $regM = get_term_meta($location->term_id, "wcmlim_locator", true);
        $regM2 = get_term_meta($regM, "wcmlim_shop_regmanager", true);

        if (in_array("location_shop_manager", $cuserRoles) && !empty($shopM) && in_array($cuserId, $shopM) && $loc_stock >= 0 && $loc_stock != null) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="change_' . $product_id . '_' . $location->term_id . '">(' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . ')</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-stock="' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . '" title="Change Stock" id="stock_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_stock_pro_list fa fa-pencil "></i><br>';
        } elseif (in_array("location_regional_manager", $cuserRoles) && !empty($regM2) && in_array($cuserId, $regM2) && $loc_stock >= 0 && $loc_stock != null) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="change_' . $product_id . '_' . $location->term_id . '">(' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . ')</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-stock="' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . '" title="Change Stock" id="stock_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_stock_pro_list fa fa-pencil "></i><br>';
        } elseif (current_user_can('administrator')) {
        }
      }
      if (intval($restock) > 0) {
        update_post_meta($product_id, '_stock', $restock);
      }
    }
  }
  public function show_locations_variations_in_column($product_id, $locations, $cuserId, $cuserRoles)
  {


    if (!empty($locations)) {
      $product = wc_get_product($product_id);
      $restock = 0;
      foreach ($locations as $location) {
        $prod_name = $product->get_name();
        $loc_stock = get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true);
        $shopM = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
        $regM = get_term_meta($location->term_id, "wcmlim_locator", true);
        $regM2 = get_term_meta($regM, "wcmlim_shop_regmanager", true);
        $restock += intval($loc_stock);
        if (in_array("location_shop_manager", $cuserRoles) && !empty($shopM) && in_array($cuserId, $shopM) && $loc_stock >= 0 && $loc_stock != null) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="change_' . $product_id . '_' . $location->term_id . '">(' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . ')</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-stock="' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . '" title="Change Stock" id="stock_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_stock_pro_list fa fa-pencil"></i><br>';
        } elseif (in_array("location_regional_manager", $cuserRoles) && !empty($regM2) && in_array($cuserId, $regM2) && $loc_stock >= 0 && $loc_stock != null) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="change_' . $product_id . '_' . $location->term_id . '">(' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . ')</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-stock="' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . '" title="Change Stock" id="stock_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_stock_pro_list fa fa-pencil"></i><br>';
        } elseif (current_user_can('administrator')) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="change_' . $product_id . '_' . $location->term_id . '">(' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . ')</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-stock="' . get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true) . '" title="Change Stock" id="stock_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_stock_pro_list fa fa-pencil"></i><br>';
        } else {
        }
      }
      if (intval($restock) > 0) {
        update_post_meta($product_id, '_stock', $restock);
      }
    }
  }
  /**
   * Show location price in new price coloumn.
   *
   * @since    1.2.9
   */

  function show_price_locations_in_column($product_id, $locations, $cuserId, $cuserRoles)
  {
    if (!empty($locations)) {
      $product = wc_get_product($product_id);
      foreach ($locations as $location) {
        $prod_name = $product->get_name();
        $shopM = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
        $regM = get_term_meta($location->term_id, "wcmlim_locator", true);
        $regM2 = get_term_meta($regM, "wcmlim_shop_regmanager", true);
        $wcmlim_stock_at = get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true);
        $location_regular_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$location->term_id}", true);
        $location_sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$location->term_id}", true);
        $wc_currency_symbol = get_woocommerce_currency_symbol();
        if (!empty($location_regular_price)) {
          $location_regular_price = number_format(floatval($location_regular_price), 2);
        }
        if (!empty($location_sale_price)) {
          $location_sale_price = number_format(floatval($location_sale_price), 2);
        }
        if (!empty($location_sale_price) && $location_sale_price != 0) {
          $wcmlim_price_html = '<del aria-hidden="true"><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_regular_price . '</span></del> <ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_sale_price . '</span></ins>';
        } elseif (empty($location_regular_price) && !empty($wcmlim_stock_at)) {
          $wcmlim_price_html = '';
        } else {
          $wcmlim_price_html = '<ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_regular_price . '</span></ins>';
        }

        if (in_array("location_shop_manager", $cuserRoles) && !empty($shopM) && in_array($cuserId, $shopM) && $product->is_type('simple') && !empty($wcmlim_stock_at)) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } elseif (in_array("location_regional_manager", $cuserRoles) && !empty($regM2) && in_array($cuserId, $regM2) && $product->is_type('simple') && !empty($wcmlim_stock_at)) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } elseif (current_user_can('administrator')) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } else {
        }
      }
    }
  }
  public function show_price_locations_variations_in_column($product_id, $locations, $cuserId, $cuserRoles)
  {
    if (!empty($locations)) {
      $product = wc_get_product($product_id);
      foreach ($locations as $location) {
        $prod_name = $product->get_name();
        $shopM = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
        $regM = get_term_meta($location->term_id, "wcmlim_locator", true);
        $regM2 = get_term_meta($regM, "wcmlim_shop_regmanager", true);
        $location_regular_price = get_post_meta($product_id, "wcmlim_regular_price_at_{$location->term_id}", true);
        $location_sale_price = get_post_meta($product_id, "wcmlim_sale_price_at_{$location->term_id}", true);
        $wc_currency_symbol = get_woocommerce_currency_symbol();
        if (!empty($location_regular_price)) {
          $location_regular_price = number_format(floatval($location_regular_price), 2);
        }
        if (!empty($location_sale_price)) {
          $location_sale_price = number_format(floatval($location_sale_price), 2);
        }
        if (!empty($location_sale_price) && $location_sale_price != 0) {
          $wcmlim_price_html = '<del aria-hidden="true"><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_regular_price . '</span></del> <ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_sale_price . '</span></ins>';
        } elseif (empty($location_regular_price)) {
          $wcmlim_price_html = '';
        } else {
          $wcmlim_price_html = '<ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">' . $wc_currency_symbol . '</span>' . $location_regular_price . '</span></ins>';
        }
        if (in_array("location_shop_manager", $cuserRoles) && !empty($shopM) && in_array($cuserId, $shopM)) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } elseif (in_array("location_regional_manager", $cuserRoles) && !empty($regM2) && in_array($cuserId, $regM2)) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } elseif (current_user_can('administrator')) {
          echo '<span style="margin-left: 10px;"><mark class="instock">' . $location->name . '</mark> <span class="price_change_' . $product_id . '_' . $location->term_id . '">' . $wcmlim_price_html . '</span></span><i data-productname="' . $prod_name . '" data-locationname="' . $location->name . '" data-id="' . $product_id . '" data-location="' . $location->term_id . '" data-saleprice="' . $location_sale_price . '" data-currency="' . $wc_currency_symbol . '" data-regularprice="' . $location_regular_price . '" title="Change Price" id="price_data_attr_change_' . $product_id . '_' . $location->term_id . '" class="wcmlim_edit_price_pro_list fa fa-pencil"></i><br>';
        } else {
          //Won't edit stock
        }
      }
    }
  }

  /**
   * Returns filter for taxonomy coloumn.
   *
   * @since    1.0.0
   */

  public function wcmlim_filter_by_taxonomy_locations($post_type, $which)
  {
    if (isset($_GET['post_type']) && $_GET['post_type'] !== 'shop_order') {
      // Render modals only once
      $this->render_stock_modal();
      $this->render_price_modal();
    }

    // Apply filter only for 'product' post type
    if ($post_type !== 'product') {
      return;
    }

    // Render taxonomy filter dropdowns
    $this->render_taxonomy_filter_dropdown('locations');
  }

  /**
   * Render the Stock Edit Modal.
   */
  private function render_stock_modal()
  {
    ?>
    <div id="stockModal" class="wcmlim-modal">
      <div class="wcmlim-modal-content">
        <div class="wcmlim-modal-header">
          <span class="wcmlim-close">&times;</span>
          <h2>Update Stock For <span class="wcmlim_stock_modal_product_name"></span></h2>
        </div>
        <div class="wcmlim-modal-body">
          <input type="hidden" class="wcmlim_stock_modal_product_id">
          <input type="hidden" class="wcmlim_stock_modal_location_id">
          <table class="form-table">
            <tbody>
              <tr>
                <td><label class="wcmlim_stock_modal_location_name"></label></td>
                <td><input type="number" class="wcmlim_stock_modal_location_stock"></td>
              </tr>
            </tbody>
          </table>
          <button class="button button-primary wcmlim_update_inline_stock">Update Stock</button>
          <p class="wcmlim_update_inline_stock_msg"></p>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Render the Price Edit Modal.
   */
  private function render_price_modal()
  {
    ?>
    <div id="priceModal" class="wcmlim-modal">
      <div class="wcmlim-modal-content">
        <div class="wcmlim-modal-header">
          <span class="wcmlim-close wcmlim-price-modal-close">&times;</span>
          <h2>Update Price For <span class="wcmlim_stock_modal_product_name"></span></h2>
        </div>
        <div class="wcmlim-modal-body">
          <input type="hidden" class="wcmlim_stock_modal_product_id">
          <input type="hidden" class="wcmlim_stock_modal_location_id">
          <input type="hidden" class="wcmlim_stock_modal_currency">
          <table class="form-table">
            <tbody>
              <tr>
                <td><label for="wcmlim_stock_modal_location_regular_price">Regular Price</label> (<span
                    class="wcmlim_price_currency"></span>)</td>
                <td><input type="text" class="wcmlim_stock_modal_location_regular_price"></td>
              </tr>
              <tr>
                <td><label for="wcmlim_stock_modal_location_sale_price">Sale Price</label> (<span
                    class="wcmlim_price_currency"></span>)</td>
                <td><input type="text" class="wcmlim_stock_modal_location_sale_price"></td>
              </tr>
            </tbody>
          </table>
          <button class="button button-primary wcmlim_update_inline_price">Update Price</button>
          <p class="wcmlim_update_inline_price_msg"></p>
        </div>
      </div>
    </div>
    <?php
  }

  /**
   * Render taxonomy filter dropdown for locations.
   */
  private function render_taxonomy_filter_dropdown($taxonomy_name)
  {
    // $taxonomy_name = 'locations';

    // Cache terms to reduce redundant queries
    $terms = wp_cache_get("taxonomy_terms_{$taxonomy_name}", 'wcmlim');        
    if ($terms === false) {
      $terms = get_terms(['taxonomy' => "locations", 'parent' => 0, 'hide_empty' => false]);
      wp_cache_set("taxonomy_terms_{$taxonomy_name}", $terms, 'wcmlim', 18000);
    }

    echo "<select name='{$taxonomy_name}' id='{$taxonomy_name}' class='postform'>";
    echo '<option value="">' . esc_html__("Show all {$taxonomy_name}", 'wcmlim') . '</option>';

    foreach ($terms as $term) {            
      $count = $this->get_cached_product_count_by_term($taxonomy_name, $term->term_id);
      printf(
        '<option value="%s" %s>%s (%d)</option>',
        esc_attr($term->slug),
        selected(isset($_GET[$taxonomy_name]) && $_GET[$taxonomy_name] === $term->slug, true, false),
        esc_html($term->name),
        $count
      );
    }

    echo '</select>';
  }

  /**
   * Get product count for a specific taxonomy term with caching.
   */
  private function get_cached_product_count_by_term($taxonomy, $term_id)
  {
    $cache_key = "product_count_{$taxonomy}_{$term_id}";
    $count = wp_cache_get($cache_key, 'wcmlim');
    if ($count === false) {
      $query = new WP_Query([
        'post_type' => 'product',
        'posts_per_page' => 1,
        'fields' => 'ids', // Fetch only IDs for performance
        'tax_query' => [
          [
            'taxonomy' => $taxonomy,
            'field' => 'term_id',
            'terms' => $term_id,
          ],
        ],
      ]);
      $count = $query->found_posts;
      wp_cache_set($cache_key, $count, 'wcmlim', 18000);
    }
    return $count;
  }


  public function wcmlim_filter_by_product_stock_status($post_type, $which)
  {

    global $typenow;
    if ($typenow == 'product') {
      $product_locations = isset($_GET['product_locations']) ? $_GET['product_locations'] : '';
      if (!empty($product_locations)) {
        $selected = isset($_GET['product_stock_status']) ? $_GET['product_stock_status'] : '';
        ?>
        <select name="product_stock_status" id="product_stock_status">
          <option value=""><?php _e('Location Stock Status', 'woocommerce'); ?></option>
          <option value="instock" <?php selected($selected, 'instock'); ?>><?php _e('In Stock', 'woocommerce'); ?></option>
          <option value="outofstock" <?php selected($selected, 'outofstock'); ?>><?php _e('Out of Stock', 'woocommerce'); ?>
          </option>
        </select>
        <?php
      }
    }
  }




  // Add a dropdown to filter orders by meta

  public function wcmlim_display_location_filter_on_shoppge()
  {

    global $pagenow, $typenow;
    if ('shop_order' === $typenow && 'edit.php' === $pagenow) {
      $domain = 'woocommerce';
      $filter_id = 'filter_shop_order_by_meta';
      $current = isset($_GET[$filter_id]) ? $_GET[$filter_id] : '';
      $com_function = new Wcmlim_Common_Functions();
      $com_function->wcmlim_order_page_top_location_filter($domain, $filter_id, $current);
    } ?>
    <a href="?page=wc-orders"><input type="button" class="button" id="wcmlim-order-filter-reset" value="Reset"></a>
    <?php
  }

  public function wcmlim_hpos_display_location_filter_on_shoppge($order_type, $which)
  {
    global $pagenow;
    if ('shop_order' === $order_type && 'admin.php' === $pagenow) {
      $domain = 'woocommerce';
      $filter_id = 'filter_shop_order_by_meta';
      $current = isset($_GET[$filter_id]) ? $_GET[$filter_id] : '';
      $com_function = new Wcmlim_Common_Functions();
      $com_function->wcmlim_order_page_top_location_filter($domain, $filter_id, $current);
    } ?>
    <a href="?page=wc-orders"><input type="button" class="button" id="wcmlim-order-filter-reset" value="Reset"></a>
    <?php
  }



  // Process the filter dropdown for orders by locations

  public function wcmlim_process_location_filter_on_shoppage($vars)
  {
    global $pagenow, $typenow;

    $filter_id = 'filter_shop_order_by_meta';

    if (WC_HPOS_IS_ACTIVE) {
      if (isset($_GET[$filter_id]) && !empty($_GET[$filter_id])) {
        $vars['meta_key'] = "_location";
        $vars['meta_value'] = $_GET[$filter_id];
      }
    } else {
      if ($pagenow == 'edit.php' && 'shop_order' === $typenow && isset($_GET[$filter_id]) && !empty($_GET[$filter_id])) {
        $vars['meta_key'] = "_location";
        $vars['meta_value'] = $_GET[$filter_id];
      }
    }

    return $vars;
  }

  /**
   * Restrict user to default location
   *
   * @since    1.1.2
   */

  public function wcmlim_get_all_locations()
  {
    $isLcex = get_option("wcmlim_exclude_locations_from_frontend");
    $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    
    // Filter out excluded locations while preserving array keys
    if (!empty($isLcex)) {
      foreach ($terms as $key => $term) {
        if (in_array($term->term_id, $isLcex)) {
          unset($terms[$key]);
        }
      }
    }
    $result = [];
    $i = 0;
    foreach ($terms as $k => $term) {
      $term_meta = get_option("taxonomy_$term->term_id");
      
      // Fix: Ensure $term_meta is an array before using array_map
      if (!is_array($term_meta)) {
        $term_meta = [];
      }
      
      $term_meta = array_map(function ($term) {
        if (!is_array($term)) {
          return $term;
        }
      }, $term_meta);
      $result[$i]['location_address'] = implode(" ", array_filter($term_meta));
      $result[$i]['location_name'] = $term->name;
      $result[$i]['term_id'] = $term->term_id;
      $i++;
    }

    return $result;
  }

  /**
   * Add fields to user profile screen, add new user screen
   */



  public function wcmlim_register_profile_fields($user)
  {

    if ($user != "add-new-user") {

      $userID = $user->ID;

      if (!current_user_can('administrator', $userID))

        return false;

    }



    $ui = isset($userID) ? $userID : "";



    $selected_location_user_meta = get_user_meta($ui, 'wcmlim_user_specific_location', true);



    $selected_location_term_meta = get_term_meta($ui, 'wcmlim_user_specific_location_term', true);







    $locations_list = $this->wcmlim_get_all_locations();



    if (sizeof($locations_list) > 0) {
      ?>

      <h3><?php _e('WC Multi locations Inventory', 'wcmlim'); ?></h3>

      <table class="form-table">

        <tr>

          <th>

            <label for="wcmlim_user_specific_location"><?php _e('Choose default location', 'wcmlim'); ?></label>

          </th>

          <td>

            <select name="wcmlim_user_specific_location" id="">

              <option value="-1" <?php if (!$selected_location_user_meta && !$selected_location_term_meta)
                echo "selected='selected'"; ?>>

                <?php echo __('select', 'wcmlim') ?>

              </option>

              <?php

              foreach ($locations_list as $key => $loc) {

                ?>

                <option value="<?php echo $loc['term_id']; ?>" data-lc-address="<?php echo base64_encode($loc['location_address']); ?>"
                  <?php

                  if ($selected_location_user_meta == $loc['term_id'] || $selected_location_term_meta == $loc['term_id']) {

                    echo "selected='selected'";

                  } ?>>

                  <?php echo ucfirst($loc['location_name']); ?>

                </option>

                <?php

              }

              ?>

            </select>

          </td>

        </tr>

      </table>

      <?php

    }

  }





  /**

   *  Save portal category field to user profile page, add new profile page etc

   */

  public function wcmlim_save_profile_fields($user_id)
  {
    if (!current_user_can('administrator', $user_id)) {
      return false;
    }

    $specificLocation = isset($_POST['wcmlim_user_specific_location']) ? intval($_POST['wcmlim_user_specific_location']) : "";

    $current_loc = get_user_meta($user_id, 'wcmlim_user_specific_location', true);


    if ($specificLocation == -1) {
      $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));

      foreach ($locations as $key => $value) {
        $location_id = $value->term_id;

        $linked_users_to_locations = get_term_meta($location_id, 'wcmlim_linked_users', true);

        if (is_string($linked_users_to_locations)) {
          $unserialized_users_list = unserialize($linked_users_to_locations);
          if ($unserialized_users_list === false) {
            $unserialized_users_list = array();
          }
        } elseif (is_array($linked_users_to_locations)) {
          $unserialized_users_list = $linked_users_to_locations;
        } else {
          $unserialized_users_list = array();
        }

        if (!empty($unserialized_users_list) && in_array($user_id, $unserialized_users_list)) {
          $unserialized_users_list = array_diff($unserialized_users_list, array($user_id));

          if (empty($unserialized_users_list)) {
            delete_term_meta($location_id, 'wcmlim_linked_users');
          } else {
            update_term_meta($location_id, 'wcmlim_linked_users', $unserialized_users_list);
          }
        }
      }

      delete_user_meta($user_id, 'wcmlim_user_specific_location');
      return;
    }

    update_user_meta($user_id, 'wcmlim_user_specific_location', $specificLocation);

    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));

    $location_id = null;
    foreach ($locations as $key => $value) {
      if ($key == $specificLocation) {
        $location_id = $value->term_id;
      }
    }

    if (!$location_id) {
      return;
    }

    $linked_users_to_locations = get_term_meta($location_id, 'wcmlim_linked_users', true);

    if (is_string($linked_users_to_locations)) {
      $unserialized_users_list = unserialize($linked_users_to_locations);
      if ($unserialized_users_list === false) {
        $unserialized_users_list = array();
      }
    } elseif (is_array($linked_users_to_locations)) {
      $unserialized_users_list = $linked_users_to_locations;
    } else {
      $unserialized_users_list = array();
    }

    $user_array = array();
    if (!empty($unserialized_users_list)) {
      foreach ($unserialized_users_list as $linked_user) {
        $user_array[] = $linked_user;
      }
    }

    $current_user = array($user_id);

    $final_linked_users = array_merge($user_array, $current_user);
    $final_linked_users = array_unique($final_linked_users);

    update_term_meta($location_id, 'wcmlim_linked_users', $final_linked_users);
  }


  function getShopMangersLocation($current_user_id)
  {
    $taxonomies = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    if (!empty($taxonomies)) {
      foreach ($taxonomies as $term) {
        $shopManager = get_term_meta($term->term_id, "wcmlim_shop_manager", true);
        if (!empty($shopManager)) {
          if (in_array($current_user_id, $shopManager)) {
            $locationNames = $term->term_id;
            $wordCount = explode(" ", $locationNames);
            if (count($wordCount) > 1) {
              $_location = str_replace(' ', '-', strtolower($locationNames));
            } else {
              $_location = $locationNames;
            }

            if (preg_match('/"/', $_location)) {
              $_location = str_replace('"', '', $_location);
            }

            $result[] = $_location;
          }
        }
      }

      return $result;
    }
  }


  function getShopRegional_MangersLocation($current_user_id)
  {
    $taxonomies = get_terms(array('taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0));
    if (!empty($taxonomies)) {
      foreach ($taxonomies as $term) {
        $regshopManager = get_term_meta($term->term_id, "wcmlim_shop_regmanager", true);
        if (!empty($regshopManager)) {
          if (in_array($current_user_id, $regshopManager)) {
            $locationId1 = $term->term_id;
            $terms_ID = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
            $items = array();
            foreach ($terms_ID as $k => $term2) {
              $locationgID2 = get_term_meta($term2->term_id, "wcmlim_locator", true);
              if ($locationId1 == $locationgID2) {
                $locationNames = $term2->term_id;
                $wordCount = explode(" ", $locationNames);
                if (count($wordCount) > 1) {
                  $_location = str_replace(' ', '-', strtolower($locationNames));
                } else {
                  $_location = $locationNames;
                }
                if (preg_match('/"/', $_location)) {
                  $_location = str_replace('"', '', $_location);
                }
                $items[] = $_location;
              }
            }

            $result[] = $items;

          } else {
            $url = admin_url('edit.php?post_type=shop_order');
            wp_safe_redirect($url);
            exit;
          }
        }
      }

      return $result;
    }
  }

  public function wcmlim_filter_orders_by_location($query)
  {


    $isShopManagerEnable = get_option('wcmlim_assign_location_shop_manager');

    global $pagenow;

    if (!function_exists('wp_get_current_user')) {
      include(ABSPATH . "wp-includes/pluggable.php");
    }

    $current_user = wp_get_current_user();
    $qv = $query->query_vars;
    $current_user_id = $current_user->ID;
    $currentUserRoles = $current_user->roles;

    if (isset($_GET['post_type']) && isset($qv['post_type']) && $qv['post_type'] != 'shop_order') {
      return;
    }
 
  // Legacy WooCommerce orders (non-HPOS) handling
  if (!WC_HPOS_IS_ACTIVE) {
    if (in_array('location_shop_manager', $currentUserRoles)) {
      if (in_array('location_shop_manager', $currentUserRoles) && $isShopManagerEnable == "on") {
        if ($pagenow == 'edit.php' && isset($qv['post_type']) && $qv['post_type'] == 'shop_order') {

          $places = $this->getShopMangersLocation($current_user_id);
          if (!empty($places)) {
            $meta_query = array('relation' => 'OR');
            foreach ($places as $placesvalue) {
              $meta_query[] = array(
                'key' => '_multilocation',
                'value' => $placesvalue,
                'compare' => 'LIKE',
              );

            }
            $query->set('meta_query', $meta_query);
          } else {
            $query->set('meta_key', '_multilocation');
            $query->set('meta_value', 'null');
          }

        }
      } elseif (in_array('location_shop_manager', $currentUserRoles) && empty($isShopManagerEnable)) {
        $query->set('meta_key', '_location');
        $query->set('meta_value', 'null');
      }
    }
    if (in_array('location_regional_manager', $currentUserRoles)) {
      if (in_array('location_regional_manager', $currentUserRoles) && $isShopManagerEnable == "on") {

        if ($pagenow == 'edit.php' && isset($qv['post_type']) && $qv['post_type'] == 'shop_order') {

          $places = $this->getShopRegional_MangersLocation($current_user_id);
          if (!empty($places[0])) {
            $meta_query = array('relation' => 'OR');
            foreach ($places[0] as $placesvalue) {
              $meta_query[] = array(
                'key' => '_multilocation',
                'value' => $placesvalue,
                'compare' => 'LIKE',
              );
            }
            $query->set('meta_query', $meta_query);
          } else {
            $query->set('meta_key', '_multilocation');
            $query->set('meta_value', 'null');
          }
        }

      } elseif (in_array('location_regional_manager', $currentUserRoles) && empty($isShopManagerEnable)) {
        $query->set('meta_key', '_location');
        $query->set('meta_value', 'null');
      }
      }
    }
    return $query;
  }
 
  /**
   * HPOS-compatible order filtering for location shop managers
   * This function handles order filtering when High-Performance Order Storage (HPOS) is enabled
   *
   * @since 3.0.0
   */
  public function wcmlim_filter_orders_by_location_hpos($args)
  {
    $isShopManagerEnable = get_option('wcmlim_assign_location_shop_manager');
 
    if (!function_exists('wp_get_current_user')) {
      include(ABSPATH . "wp-includes/pluggable.php");
    }
 
    $current_user = wp_get_current_user();
    $current_user_id = $current_user->ID;
    $currentUserRoles = $current_user->roles;
 
    if (in_array('location_shop_manager', $currentUserRoles)) {
      if (in_array('location_shop_manager', $currentUserRoles) && $isShopManagerEnable == "on") {
        $places = $this->getShopMangersLocation($current_user_id);
        if (!empty($places)) {
          $meta_query = array('relation' => 'OR');
          foreach ($places as $placesvalue) {
            $meta_query[] = array(
              'key' => '_multilocation',
              'value' => $placesvalue,
              'compare' => 'LIKE',
            );
          }
          $args['meta_query'] = $meta_query;
        } else {
          $args['meta_key'] = '_multilocation';
          $args['meta_value'] = 'null';
        }
      } elseif (in_array('location_shop_manager', $currentUserRoles) && empty($isShopManagerEnable)) {
        $args['meta_key'] = '_location';
        $args['meta_value'] = 'null';
      }
    }
    
    if (in_array('location_regional_manager', $currentUserRoles)) {
      if (in_array('location_regional_manager', $currentUserRoles) && $isShopManagerEnable == "on") {
        $places = $this->getShopRegional_MangersLocation($current_user_id);
        if (!empty($places[0])) {
          $meta_query = array('relation' => 'OR');
          foreach ($places[0] as $placesvalue) {
            $meta_query[] = array(
              'key' => '_multilocation',
              'value' => $placesvalue,
              'compare' => 'LIKE',
            );
          }
          $args['meta_query'] = $meta_query;
        } else {
          $args['meta_key'] = '_multilocation';
          $args['meta_value'] = 'null';
        }
      } elseif (in_array('location_regional_manager', $currentUserRoles) && empty($isShopManagerEnable)) {
        $args['meta_key'] = '_location';
        $args['meta_value'] = 'null';
      }
    }
    
    return $args;
  }
  

  function wcmlim_woocommerce_admin_html_order_item_class_filter($class, $item, $order)
  {
    $current_user = get_current_user_id();
    // get current_user roles
    $user_meta = get_userdata($current_user);

    if (!in_array('location_shop_manager', (array) $user_meta->roles)) {
      return;
    }

    if (in_array('location_shop_manager', (array) $user_meta->roles)) {
      $ord__selectedLocTermId = $item->get_meta('_selectedLocTermId', true);
      $shop_manager = get_term_meta($ord__selectedLocTermId, 'wcmlim_shop_manager', true);
      if (is_array($shop_manager)) {
        if (in_array($current_user, $shop_manager)) {
          $class = 'wcmlim_active_line-item';
        } else {
          $class = 'wcmlim_inactive_line-item';
        }

      } else {
        $class = 'wcmlim_inactive_line-item';
      }
      return $class;
    }
  }

  /**
   * Manager for view location wise order
   *
   * @since 3.0.0
   */

  public function wcmlim_order_restrict()
  {
    /** Restrict Regional and Shop Manager to view another location order */
    $cuser = wp_get_current_user();
    $cuserId = $cuser->ID;
    $cuserRoles = $cuser->roles;
    if (in_array("location_shop_manager", $cuserRoles) || in_array("location_regional_manager", $cuserRoles)) {
      if (isset($_GET['post'])) {
        $orderid = $_GET['post'];
        if (WC_HPOS_IS_ACTIVE) {
          $order_type = OrderUtil::get_order_type($orderid);
        } else {
          $order_type = get_post_type($orderid);
        }

        if ($order_type === "shop_order") {
          $order = wc_get_order($orderid);
          if ($order && !in_array("administrator", $cuserRoles)) {
            $url = admin_url('edit.php?post_type=shop_order');
            $order_data = $order->get_meta('_multilocation');
            $is_splitted = (WC_HPOS_IS_ACTIVE) ? $order->get_meta("_order_is_splitted", true) : get_post_meta($orderid, "_order_is_splitted", true);
            if ($is_splitted == 'yes')
              return;

            /** On order view restrict */
            $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
            $loc_ID = array();
            foreach ($terms as $k => $term_data) {
              $loc_name = $term_data->term_id;
              if ($order_data) {
                foreach ($order_data as $od_data) {
                  if ($od_data == $loc_name) {
                    $loc_ID[] = $loc_name;
                  }
                }
              }
            }
            $shopM_ID = array();
            $regM2_ID = array();

            if ($loc_ID) {
              foreach ($loc_ID as $l_id) {
                $shopM = get_term_meta($l_id, 'wcmlim_shop_manager', true);
                if ($shopM) {
                  foreach ($shopM as $shopM_arr) {
                    $shopM_ID[] = $shopM_arr;
                  }
                }
                $regM = get_term_meta($l_id, "wcmlim_locator", true);
                $regM2 = get_term_meta($regM, "wcmlim_shop_regmanager", true);
                if ($regM2) {
                  foreach ($regM2 as $regM2_arr) {
                    $regM2_ID[] = $regM2_arr;
                  }
                }
              }
            }
            if (in_array("location_shop_manager", $cuserRoles)) {
              if (in_array($cuserId, $shopM_ID)) {
                return;
              } else {
                wp_redirect($url);
              }
            } elseif (in_array("location_regional_manager", $cuserRoles)) {
              if (in_array($cuserId, $regM2_ID)) {
                return;
              } else {
                wp_redirect($url);
              }
            } elseif (in_array("administrator", $cuserRoles)) {
              return;
            } else {
              wp_redirect($url);
            }
          }
        }
      }
    }
  }

  /**
   * Ajax callback function for 
   * update stock inline 
   *
   * @since  2.2.1
   */

  public function wcmlim_update_stock_inline()
  {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
    }
 
    check_ajax_referer('wcmlim_locations_nonce', 'security');

    if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
        wp_send_json(array(
            'success' => false,
            'message' => 'Invalid nonce'
        ));
        return;
    }
    $location_stock = $_POST['location_stock'];
    $product_id = $_POST['product_id'];
    $location_id = $_POST['location_id'];
    // Get the backorder option for the current location
    $allow_backorder = get_post_meta($product_id, 'wcmlim_allow_backorder_at_' . $location_id, true);
    // Ensure $location_stock is not less than 0
    if ($location_stock < 0 && $allow_backorder !== 'Yes') {
      $location_stock = 0;
    }

    $product = wc_get_product($product_id);

    update_post_meta($product_id, 'wcmlim_stock_at_' . $location_id, $location_stock);

    $total = 0;
    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false));

    if ($locations) {
      foreach ($locations as $location) {
        $total += intval(get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true));
      }
    }

    if ($total > 0) {
      update_post_meta($product_id, '_stock', $total);
      update_post_meta($product_id, '_stock_status', 'instock');
    } else {
      update_post_meta($product_id, '_stock', '0');
      update_post_meta($product_id, '_stock_status', 'outofstock');
    }

    $termName = array();
    $removetermName = array();
    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    $stock = '';

    if ($locations) {
      foreach ($locations as $key => $term) {
        $stock = intval(get_post_meta($product_id, 'wcmlim_stock_at_' . $term->term_id));

        if ($term->term_id == $location_id) {
          $stock = intval($location_stock);
        }

        if ($stock == '' || $stock == 0) {
          $removetermName[] = $term->slug;
        } else {
          $termName[] = $term->slug;
        }
      }
    }

    wp_set_object_terms($product_id, $termName, 'locations');
    wp_remove_object_terms($product_id, $removetermName, 'locations');

    echo $location_stock;
    wp_die();

  }
  public function wcmlim_default_hidden_meta_boxes($hidden, $screen)
  {
    $post_type = $screen->post_type;
    if ($post_type == 'product') {
      $hidden = array(
        'price_at_locations',
      );
      return $hidden;
    }
    return $hidden;
  }
  public function wcmlim_update_price_inline()
  {
    $regular_price = $_POST['regular_price'];
    $sale_price = $_POST['sale_price'];
    if ($sale_price == 'NaN') {
      $sale_price = '';
    }

    if (isset($_POST['product_id']) && isset($_POST['location_id'])) {
      update_post_meta($_POST['product_id'], 'wcmlim_regular_price_at_' . $_POST['location_id'], $regular_price);
      update_post_meta($_POST['product_id'], 'wcmlim_sale_price_at_' . $_POST['location_id'], $sale_price);
    }

    echo $regular_price . '/' . $sale_price;
    wp_die();
  }
  /**
   * Restricted location selection
   * dropdown
   *
   * @since  1.1.4
   */
  public function wcmlim_restrict_parent_location($args, $taxonomy)
  {
    if ('locations' != $taxonomy)
      return $args; // no change
    $args['class'] = "locationsParent";
    return $args;
  }

  /**
   * Location Enablement in order view for regional manager
   */


  function wcmlim_woocommerce_admin_html_order_item_class_regional_manager_filter($class, $item, $order)
  {

    $current_user = get_current_user_id();
    // get current_user roles
    $user_meta = get_userdata($current_user);

    if (!in_array('location_regional_manager', (array) $user_meta->roles)) {
      return;
    }

    if (in_array('location_regional_manager', (array) $user_meta->roles)) {
      $selectedLocTermId = $item->get_meta('_selectedLocTermId', true);
      $wcmlim_locator = get_term_meta($selectedLocTermId, 'wcmlim_locator', true);

      $get_regional_manager_ids = get_term_meta($wcmlim_locator, 'wcmlim_shop_regmanager', true);


      if (is_array($get_regional_manager_ids)) {
        if (in_array($current_user, $get_regional_manager_ids)) {
          $class = 'wcmlim_active_line-item';
        } else {
          $class = 'wcmlim_inactive_line-item';
        }

      } else {
        $class = 'wcmlim_inactive_line-item';
      }
      return $class;
    }
  }


  /**
   * callback function for Stock Information Border
   *
   * @since    1.1.5
   */

  /**
   * callback function for Stock Information Background Color
   *
   * @since    1.1.5
   */
  public function wcmlim_preview_stock_bgcolor_cb()
  {
    $box_bgcolor = get_option($this->option_name . '_preview_stock_bgcolor');
    $box_width = get_option($this->option_name . '_preview_stock_width');
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Box Width', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(%)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="number" 
               id="<?php esc_attr_e($this->option_name . '_preview_stock_width'); ?>"
               name="<?php esc_attr_e($this->option_name . '_preview_stock_width'); ?>"
               value="<?php esc_attr_e($box_width); ?>" />
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Background Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_preview_stock_bgcolor'); ?>"
                  style="background-color: <?php esc_attr_e($box_bgcolor); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_preview_stock_bgcolor'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_preview_stock_bgcolor'); ?>"
                 value="<?php esc_attr_e($box_bgcolor); ?>" />
        </div>
      </div>
    </div>
    <style>
      .wcmlim-compact-settings { margin-bottom: 15px; }
      .wcmlim-setting-row { display: flex; align-items: center; margin-bottom: 10px;flex-wrap: wrap; }
      .wcmlim-vertical-setting { margin-bottom: 10px; }
      .wcmlim-setting-label { min-width: 180px; margin-right: 15px; }
      .wcmlim-vertical-label { display: block; margin-bottom: 5px; }
      .wcmlim-label-desc { font-size: 11px; font-weight: normal; color: #666; }
      .wcmlim-setting-input { padding: 4px 8px; border: 1px solid #ddd; border-radius: 3px; width: 100px; }
      .wcmlim-setting-input-wide { padding: 4px 8px; border: 1px solid #ddd; border-radius: 3px; width: 200px; }
      .wcmlim-wide-input { padding: 4px 8px; border: 1px solid #ddd; border-radius: 3px; width: 250px; }
      .wcmlim-color-controls { display: flex; align-items: center; gap: 8px; }
      .wcmlim-color-btn { width: 30px; height: 30px; border: 1px solid #ddd; border-radius: 3px; cursor: pointer; }
      .wcmlim-color-field { padding: 4px 8px; border: 1px solid #ddd; border-radius: 3px; width: 120px; }
      /* Keep WordPress color picker button at default color */
      .wcmlim-color-controls .wp-color-result { background-color: #ffffff; }
    </style>
    <script>
      jQuery(document).ready(function($) {
        // Initialize color picker for existing color fields
        $('.color-picker').wpColorPicker({
          change: function(event, ui) {
            var targetId = $(this).attr('id');
            var colorBtn = $('.wcmlim-color-picker[data-target="' + targetId + '"]');
            colorBtn.css('background-color', ui.color.toString());
            
            // Prevent WordPress color picker button from changing color
            var wpColorResult = $(this).closest('.wp-picker-container').find('.wp-color-result');
            wpColorResult.css('background-color', '#ffffff'); // Keep default white color
            
            // Remove red border when color is selected
            $('#' + targetId).css('border-color', '#ddd');
            
            // Real-time preview updates for all color fields
            if (targetId.includes('preview_stock_bgcolor')) {
              $('.Wcmlim_box_content').css('background-color', ui.color.toString());
            } else if (targetId.includes('txtcolor_stock_info')) {
              $('.Wcmlim_box_title').css('color', ui.color.toString());
            } else if (targetId.includes('soldout_button_color')) {
              $('.sold-out-display').css('background-color', ui.color.toString());
            } else if (targetId.includes('soldout_button_text_color')) {
              $('.sold-out-display').css('color', ui.color.toString());
            } else if (targetId.includes('instock_button_color')) {
              $('.stock-display:not(.sold-out-display):not(.backorder-display)').css('background-color', ui.color.toString());
            } else if (targetId.includes('instock_button_text_color')) {
              $('.stock-display:not(.sold-out-display):not(.backorder-display)').css('color', ui.color.toString());
            } else if (targetId.includes('onbackorder_button_color')) {
              $('.backorder-display').css('background-color', ui.color.toString());
            } else if (targetId.includes('onbackorder_button_text_color')) {
              $('.backorder-display').css('color', ui.color.toString());
            }
          },
          create: function(event, ui) {
            // When color picker is created, set WordPress button to default color
            var wpColorResult = $(this).closest('.wp-picker-container').find('.wp-color-result');
            wpColorResult.css('background-color', '#ffffff'); // Keep default white color
          }
        });
        
        // Monitor for any changes to WordPress color picker buttons and reset them
        setInterval(function() {
          $('.wcmlim-color-controls .wp-color-result').each(function() {
            if ($(this).css('background-color') !== 'rgb(255, 255, 255)') {
              $(this).css('background-color', '#fff'); // Reset to default white color
            }
          });
        }, 100);
        
        // Handle color button clicks
        $('.wcmlim-color-picker').on('click', function(e) {
          e.preventDefault();
          var targetId = $(this).data('target');
          $('#' + targetId).wpColorPicker('open');
          // Remove red border when color picker opens
          $('#' + targetId).css('border-color', '#ddd');
        });
        
        // Handle box width changes in real-time
        $('input[name*="_preview_stock_width"]').on('input change', function() {
          var value = $(this).val();
          if (value && value > 0) {
            $('.Wcmlim_box_content').css('width', value + '%');
          }
        });
        
        // Handle text field changes for real-time preview
        $('input[name*="_soldout_button_text"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.sold-out-status').text(value);
          }
        });
        
        $('input[name*="_instock_button_text"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.stock-status:not(.sold-out-status):not(.backorder-status)').text(value);
          }
        });
        
        $('input[name*="_onbackorder_button_text"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.backorder-status').text(value);
          }
        });
        
        // Handle border radius changes for real-time preview
        $('input[name*="_soldout_borderradius"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.sold-out-display').css('border-radius', value);
          }
        });
        
        $('input[name*="_instock_borderradius"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.stock-display:not(.sold-out-display):not(.backorder-display)').css('border-radius', value);
          }
        });
        
        $('input[name*="_onbackorder_borderradius"]').on('input change', function() {
          var value = $(this).val();
          if (value) {
            $('.backorder-display').css('border-radius', value);
          }
        });
        
        // Handle checkbox toggles for real-time preview
        $('input[name*="_display_stock_info"]').on('change', function() {
          if ($(this).is(':checked')) {
            $('.Wcmlim_box_title').hide();
          } else {
            $('.Wcmlim_box_title').show();
          }
        });
        
        $('input[name*="_hide_stock_count"]').on('change', function() {
          if ($(this).is(':checked')) {
            $('.stock-count').hide();
          } else {
            $('.stock-count').show();
          }
        });
      });
    </script>
    <hr>
    <?php
  }
  /**
   * callback function for Stock Information text options.
   *
   * @since    1.1.5
   */

  public function wcmlim_txt_stock_info_cb()
  {
    $h1_text = get_option($this->option_name . '_txt_stock_info');
    if ($h1_text == false) {
      update_option($this->option_name . '_txt_stock_info', 'Stock Information');
    }
    $checked = get_option($this->option_name . '_display_stock_info');
    $h1_textcolor = get_option($this->option_name . '_txtcolor_stock_info');
    if ($h1_textcolor == false) {
      update_option($this->option_name . '_txtcolor_stock_info', '#000000');
    }
    
    // Get location display heading setting for the input box
    $display_text = get_option($this->option_name . '_location_display_heading_setting');
    if ($display_text == '') {
      update_option($this->option_name . '_location_display_heading_setting', 'Stock Information');
    }
    $display_text = get_option($this->option_name . '_location_display_heading_setting');
    
    ?>
    <div class="wcmlim-compact-settings">

      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Hide Header', 'wcmlim'); ?></strong>
        </label>
        <label class="switch">
          <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_display_stock_info') ?>"
                 name="<?php esc_attr_e($this->option_name . '_display_stock_info') ?>" 
                 <?php echo ($checked == 'on') ? 'checked="checked"' : ''; ?>>
          <span class="slider round"></span>
        </label>
      </div>

      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Heading Text', 'wcmlim'); ?></strong> 
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_location_display_heading_setting'); ?>"
               id="<?php esc_attr_e($this->option_name . '_location_display_heading_setting'); ?>" 
               value="<?php esc_attr_e($display_text); ?>">
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_txtcolor_stock_info'); ?>"
                  style="background-color: <?php esc_attr_e($h1_textcolor); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_txtcolor_stock_info'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_txtcolor_stock_info'); ?>"
                 value="<?php esc_attr_e($h1_textcolor); ?>" />
        </div>
      </div>
    </div>
    <hr>
    <?php
  }

  /**
   * callback function for SoldOut button text options.
   *
   * @since    1.1.5
   */

  public function wcmlim_soldout_button_text_cb()
  {
    $soldoutbutton_text = get_option($this->option_name . '_soldout_button_text');
    if ($soldoutbutton_text == false) {
      update_option($this->option_name . '_soldout_button_text', 'Sold Out');
    }
    $button_color = get_option($this->option_name . '_soldout_button_color');
    if ($button_color == false) {
      update_option($this->option_name . '_soldout_button_color', '#fee2e2');
    }
    $button_txt_color = get_option($this->option_name . '_soldout_button_text_color');
    if ($button_txt_color == null) {
      update_option($this->option_name . '_soldout_button_text_color', '#dc2626');
    }
    $sold_radius = get_option($this->option_name . '_soldout_borderradius');
    if ($sold_radius == false) {
      update_option($this->option_name . '_soldout_borderradius', '0px');
    }
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Label', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(Sold-Out button text)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_soldout_button_text'); ?>"
               id="<?php esc_attr_e($this->option_name . '_soldout_button_text'); ?>"
               value="<?php esc_attr_e($soldoutbutton_text); ?>">
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Background Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_soldout_button_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_soldout_button_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_soldout_button_color'); ?>"
                 value="<?php esc_attr_e($button_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Text Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_soldout_button_text_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_txt_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_soldout_button_text_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_soldout_button_text_color'); ?>"
                 value="<?php esc_attr_e($button_txt_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Button Radius', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(px, em)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_soldout_borderradius'); ?>"
               id="<?php esc_attr_e($this->option_name . '_soldout_borderradius'); ?>"
               value="<?php esc_attr_e($sold_radius); ?>">
      </div>
    </div>
    <hr>
    <?php
  }

  /**
   * callback function for InStock button text options.
   *
   * @since    1.1.5
   */

  public function wcmlim_instock_button_text_cb()
  {
    $stockbutton_text = get_option($this->option_name . '_instock_button_text');
    if ($stockbutton_text == false) {
      update_option($this->option_name . '_instock_button_text', 'In Stock');
    }
    $button_color = get_option($this->option_name . '_instock_button_color');
    if ($button_color == false) {
      update_option($this->option_name . '_instock_button_color', '#dcfce7');
    }
    $button_txt_color = get_option($this->option_name . '_instock_button_text_color');
    if ($button_txt_color == false) {
      update_option($this->option_name . '_instock_button_text_color', '#16a34a');
    }
    $stock_radius = get_option($this->option_name . '_instock_borderradius');
    if ($stock_radius == false) {
      update_option($this->option_name . '_instock_borderradius', '0px');
    }
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Hide Stock Count', 'wcmlim'); ?></strong>
        </label>
        <label class="switch">
          <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_hide_stock_count') ?>"
            name="<?php esc_attr_e($this->option_name . '_hide_stock_count') ?>" <?php echo (get_option($this->option_name . '_hide_stock_count') == 'on') ? 'checked="checked"' : ''; ?>>
          <span class="slider round"></span>
        </label>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Label', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(In-Stock button text)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_instock_button_text'); ?>"
               id="<?php esc_attr_e($this->option_name . '_instock_button_text'); ?>"
               value="<?php esc_attr_e($stockbutton_text); ?>">
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Background Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_instock_button_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_instock_button_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_instock_button_color'); ?>"
                 value="<?php esc_attr_e($button_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Text Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_instock_button_text_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_txt_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_instock_button_text_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_instock_button_text_color'); ?>"
                 value="<?php esc_attr_e($button_txt_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Button Radius', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(px, em)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_instock_borderradius'); ?>"
               id="<?php esc_attr_e($this->option_name . '_instock_borderradius'); ?>"
               value="<?php esc_attr_e($stock_radius); ?>">
      </div>
    </div>
    <hr>
    <?php
  }

  public function wcmlim_onbackorder_button_text_cb()
  {
    $backorder_text = get_option($this->option_name . '_onbackorder_button_text');
    if ($backorder_text == false) {
      update_option($this->option_name . '_onbackorder_button_text', 'Available on backorder');
    }
    $button_color = get_option($this->option_name . '_onbackorder_button_color');
    if ($button_color == false) {
      update_option($this->option_name . '_onbackorder_button_color', '#ffc107');
    }
    $button_txt_color = get_option($this->option_name . '_onbackorder_button_text_color');
    if ($button_txt_color == false) {
      update_option($this->option_name . '_onbackorder_button_text_color', '#212529');
    }
    $backorder_radius = get_option($this->option_name . '_onbackorder_borderradius');
    if ($backorder_radius == false) {
      update_option($this->option_name . '_onbackorder_borderradius', '0px');
    }
    ?>
    <div class="wcmlim-compact-settings">
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Label', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(Available on backorder text)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_onbackorder_button_text'); ?>"
               id="<?php esc_attr_e($this->option_name . '_onbackorder_button_text'); ?>"
               value="<?php esc_attr_e($backorder_text); ?>">
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Background Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_onbackorder_button_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_onbackorder_button_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_onbackorder_button_color'); ?>"
                 value="<?php esc_attr_e($button_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Text Color', 'wcmlim'); ?></strong>
        </label>
        <div class="wcmlim-color-controls">
          <button type="button" class="wcmlim-color-btn wcmlim-color-picker" 
                  data-target="<?php esc_attr_e($this->option_name . '_onbackorder_button_text_color'); ?>"
                  style="background-color: <?php esc_attr_e($button_txt_color); ?>"></button>
          <input class="wcmlim-color-field color-picker" type="text"
                 id="<?php esc_attr_e($this->option_name . '_onbackorder_button_text_color'); ?>"
                 name="<?php esc_attr_e($this->option_name . '_onbackorder_button_text_color'); ?>"
                 value="<?php esc_attr_e($button_txt_color); ?>" />
        </div>
      </div>
      <div class="wcmlim-setting-row">
        <label class="wcmlim-setting-label">
          <strong><?php echo __('Button Radius', 'wcmlim'); ?></strong> <span class="wcmlim-label-desc">(px, em)</span>
        </label>
        <input class="wcmlim-setting-input-wide" type="text" 
               name="<?php esc_attr_e($this->option_name . '_onbackorder_borderradius'); ?>"
               id="<?php esc_attr_e($this->option_name . '_onbackorder_borderradius'); ?>"
               value="<?php esc_attr_e($backorder_radius); ?>">
      </div>
    </div>
    <hr>
    <?php
  }

  /**
   * Callback function for show stock count setting
   *
   * @since    1.0.0
   */
  /**
   * Ajax callback function for showing parent attributes to sub locations
   *
   * @since  1.2.2
   */

  public function wcmlim_show_parent_paremeter()
  {
    $term_id = $_POST['loc_id'];

    if ($term_id == '') {
      echo json_encode(array('error' => 'yes'));
      wp_die();
    }

    $parent_start_time = get_term_meta($term_id, 'wcmlim_start_time', true);
    (isset($parent_start_time)) ? $parent_start_time : $parent_start_time = '';
    $parent_end_time = get_term_meta($term_id, 'wcmlim_end_time', true);
    (isset($parent_end_time)) ? $parent_end_time : $parent_end_time = '';
    $parent_wcmlim_phone = get_term_meta($term_id, 'wcmlim_phone', true);
    (isset($parent_wcmlim_phone)) ? $parent_wcmlim_phone : $parent_wcmlim_phone = '';
    $parent_time = array(
      'start' => $parent_start_time,
      'end' => $parent_end_time,
      'phone' => $parent_wcmlim_phone,
    );
    echo json_encode($parent_time);
    wp_die();
  }

  /**
   * Register the widgets
   *
   * @since    1.1.6
   */
  public function wcmlim_register_wcmlim_widget()
  {
    register_widget('WCMLIM_Widget');
    register_widget('WCMLIM_Widget_Multiselect');
  }

  /**
   * Register the settings for plugin.
   *
   * @since    1.0.0
   */

  public function wcmlim_wpml_init()
  {
    load_plugin_textdomain($this->plugin_name, false, basename(dirname(__FILE__)) . '/languages');
  }

  /**
   * OpenPOS Comaptibility - Reduces Stock Levels from Locations  
   *
   * @since    1.2.3
   */

  public function wcmlim_pos_stock_levels_reduction($order, $order_data)
  {
    $order_id = $order->get_id();
    if (!$order_id) {
      return;
    }
    $order = wc_get_order($order_id);

    $wcmlim_pos_compatiblity1 = get_option('wcmlim_pos_compatiblity');
    if ($wcmlim_pos_compatiblity1 == "on" && in_array('woocommerce-openpos/woocommerce-openpos.php', apply_filters('active_plugins', get_option('active_plugins')))) {

      $pos_order_warehouse = (WC_HPOS_IS_ACTIVE) ? $order->get_meta("_pos_order_warehouse", true) : get_post_meta($order_id, "_pos_order_warehouse", true);

      if ($pos_order_warehouse == '' || $pos_order_warehouse == 0) {
        return;
      }

      $op_order = (WC_HPOS_IS_ACTIVE) ? $order->get_meta("_op_order", true) : get_post_meta($order_id, "_op_order", true);

      $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
      foreach ($terms as $term) {
        $wcmlim_pos_id = get_term_meta($term->term_id, 'wcmlim_pos_compatiblity', true);

        if ($pos_order_warehouse == $wcmlim_pos_id) {
          foreach ($op_order['items'] as $item_key => $item_values) {
            $parentTerms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => $term->term_id));
            $product = wc_get_product($item_values['product_id']);
            if (!empty($parentTerms)) {
              foreach ($parentTerms as $parentTerm) {
                $stockInParentLocation[$parentTerm->term_id] = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentTerm->term_id}", true);
              }
              $parentValue = max($stockInParentLocation);
              $parentKey = array_search($parentValue, $stockInParentLocation);
              if ($parentKey) {
                $maxStockAtSub = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentKey}", true);
                $subStock = ((int) $maxStockAtSub - (int) $item_values['qty']);
                update_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentKey}", $subStock);
              }
            }
            $location_stock = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$term->term_id}", true);
            $main_old_stock = get_post_meta($item_values['product_id'], "_stock", true);
            $location_pos_stock = $location_stock - $item_values['qty'];
            update_post_meta($item_values['product_id'], "wcmlim_stock_at_{$term->term_id}", $location_pos_stock);
            $main_new_stock = $main_old_stock - $item_values['qty'];
            update_post_meta($item_values['product_id'], "_stock", $main_new_stock);
            $product->save();
          }
        }

      }
    }
  }

  public function wcmlim_increase_stock_levels_order_status_failed_refunded($order_id, $old_status, $new_status)
  {
    if (!$order_id) {
      return;
    }

    if ($new_status == 'failed' || $new_status == 'refunded') {
      $order = wc_get_order($order_id);

      if (!get_option('woocommerce_manage_stock') == 'yes' && !sizeof($order->get_items()) > 0) {
        return;
      }

      if (!empty($order)) {
        foreach ($order->get_items() as $item) {
          $product = $item->get_product();
          $item_stock_reduced = $item->get_meta('_reduced_stock', true);

          $item_selectedLocation_key = $item->get_meta('_selectedLocationKey', true);
          $itemSelLocTermId = $item->get_meta('_selectedLocTermId', true);
          $itemSelLocName = $item->get_meta('Location', true);
          $selLocQty = get_post_meta($product->get_id(), "wcmlim_stock_at_{$itemSelLocTermId}", true);
          $newStock = 0;
          if (!$item_stock_reduced || !$product || !$product->managing_stock()) {
            continue;
          }

          $item_name = $product->get_formatted_name();
          $product_id = !empty($item->get_variation_id()) ? $item->get_variation_id() : $item->get_product_id();

          if ($item_stock_reduced > 0) {
            $newStock = intval($selLocQty) + intval($item_stock_reduced);
          }

          update_post_meta($product_id, "wcmlim_stock_at_{$itemSelLocTermId}", $newStock);
          $product->save();

          $item->delete_meta_data('_reduced_stock');
          $item->save();

          $locChanges[] = "{ Stock levels increased: {$item_name} from Location: {$itemSelLocName}  {$selLocQty} &rarr; {$newStock} }";

        }
        if ($locChanges) {
          $order->add_order_note(implode(', ', $locChanges));
          $order->save();
        }
      }
    }
  }

  /**
   * OpenPOS Comaptibility - Restores/Adds Stock Levels from Locations  
   *
   * @since    1.2.3
   */

  public function wcmlim_pos_restore_order_stock($order_id)
  {
    if (!$order_id) {
      return;
    }

    $order = wc_get_order($order_id);
    if (!get_option('woocommerce_manage_stock') == 'yes' && !sizeof($order->get_items()) > 0) {
      return;
    }
    $op_order = (WC_HPOS_IS_ACTIVE) ? $order->get_meta("_op_order", true) : get_post_meta($order_id, "_op_order", true);
    $pos_order_warehouse = (WC_HPOS_IS_ACTIVE) ? $order->get_meta("_pos_order_warehouse", true) : get_post_meta($order_id, "_pos_order_warehouse", true);
    $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    foreach ($terms as $term) {
      $wcmlim_pos_id = get_term_meta($term->term_id, 'wcmlim_pos_compatiblity', true);
      if ($pos_order_warehouse == $wcmlim_pos_id) {
        if (!empty($op_order)) {
          foreach ($op_order['items'] as $item_key => $item_values) {
            $parentTerms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => $term->term_id));
            if (!empty($parentTerms)) {
              foreach ($parentTerms as $parentTerm) {
                $stockInParentLocation[$parentTerm->term_id] = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentTerm->term_id}", true);
              }
              $parentValue = max($stockInParentLocation);
              $parentKey = array_search($parentValue, $stockInParentLocation);
              if ($parentKey) {
                $maxStockAtSub = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentKey}", true);
                $subStock = ((int) $maxStockAtSub + (int) $item_values['qty']);
                update_post_meta($item_values['product_id'], "wcmlim_stock_at_{$parentKey}", $subStock);
              }
            }
            $location_stock = get_post_meta($item_values['product_id'], "wcmlim_stock_at_{$term->term_id}", true);
            $main_old_stock = get_post_meta($item_values['product_id'], "_stock", true);
            $location_pos_stock = $location_stock + $item_values['qty'];
            update_post_meta($item_values['product_id'], "wcmlim_stock_at_{$term->term_id}", $location_pos_stock);
            $main_new_stock = $main_old_stock + $item_values['qty'];
            update_post_meta($item_values['product_id'], "_stock", $main_new_stock);
          }
        }
      }
    }
    $order->save();
  }
  /**
   * Ajax callback function for validating google distance api matrix
   *
   * @since  1.2.4
   */

  public function wcmlim_distance_matrix_validate_api()
  {
    global $wpdb;
    $google_api_key = $_POST['api'];
    if (empty($google_api_key)) {
      echo 'Please enter google api key.';
      wp_die();
    }

    $origins = WC()->countries->get_base_state() . WC()->countries->get_base_city() . WC()->countries->get_base_postcode();
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://maps.googleapis.com/maps/api/distancematrix/json?units=metrics&origins=" . $origins . "&destinations=" . $origins . "&key=" . $google_api_key,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
    ));
    $response = curl_exec($curl);
    $response_arr = json_decode($response);
    curl_close($curl);
    $validate_status = 'valid';
    if (isset($response_arr) && !empty($response_arr)) {
      if (isset($response_arr->error_message)) {
        $validate_status = $response_arr->error_message;
      }
    }
    if (isset($response_arr) && $response_arr == "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started") {
      $validate_status = $response_arr;
    }
    echo $validate_status;
    wp_die();
  }
  /**
   * Ajax callback function for validating google Geocode service
   *
   * @since  1.2.4
   */

  public function wcmlim_geocode_validate_api()
  {
    global $wpdb;
    $google_api_key = $_POST['api'];

    if (empty($google_api_key)) {
      echo 'Please enter google api key.';
      wp_die();
    }

    $origins = WC()->countries->get_base_state() . WC()->countries->get_base_city() . WC()->countries->get_base_postcode();
    $address = str_replace(' ', '+', $origins);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=false&key=' . $google_api_key,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
    ));
    $geocode = curl_exec($curl);
    $output = json_decode($geocode);
    curl_close($curl);
    $geocode_validate_status = 'valid';
    if (isset($output) && !empty($output)) {
      if (isset($output->error_message)) {
        $geocode_validate_status = $output->error_message;
      }
    }
    if (isset($output) && $output == "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started") {
      $geocode_validate_status = $output;
    }
    echo $geocode_validate_status;
    wp_die();
  }
  /**
   * Ajax callback function for validating google Geocode service
   *
   * @since  1.2.4
   */

  public function wcmlim_place_validate_api()
  {
    global $wpdb;
    $google_api_key = $_POST['api'];

    if (empty($google_api_key)) {
      echo 'Please enter google api key.';
      wp_die();
    }

    $origins = WC()->countries->get_base_state() . WC()->countries->get_base_city() . WC()->countries->get_base_postcode();
    $address = str_replace(' ', '+', $origins);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' . urlencode($address) . '&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry&key=' . $google_api_key,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
    ));
    $placeapi = curl_exec($curl);
    $output = json_decode($placeapi);
    curl_close($curl);
    $geocode_validate_status = 'valid';
    if (isset($output) && !empty($output)) {
      if (isset($output->error_message)) {
        $geocode_validate_status = $output->error_message;
      }
    }
    if (isset($output) && $output == "You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started") {
      $geocode_validate_status = $output;
    }
    echo $geocode_validate_status;
    wp_die();
  }

  public function wcmlim_locations_bulk_dropdown()
  {
    global $pagenow;
    $current_page = isset($_GET['post_type']) ? $_GET['post_type'] : '';
    if (
      is_admin() &&
      'product' == $current_page &&
      'edit.php' == $pagenow
    ) {

      $locations_list = $this->wcmlim_get_all_locations();
      ?>
      <select name="bulk_default_selection" id="bulk_default_selection" style="float:none;max-width:fit-content;display:<?php
      $default_location = get_option('wcmlim_enable_default_location ');
      if ($default_location == 'on') {
        echo '';
      } else {
        echo 'none';
      }
      ?>">
        <option value="-1"><?php _e('Change default location to...', 'wcmlim'); ?></option>
        <?php
        if (sizeof($locations_list) > 0) {
          foreach ($locations_list as $key => $loc) {
            $__locName = ucfirst($loc['location_name']);
            $__locTermID = $loc['term_id'];
            ?>
            <option value="<?= $key ?>" data-termid="<?= $__locTermID ?>"><?= $__locName ?></option>
            <?php
          }
        }
        ?>
      </select>
      <input type="button" name="assignitloc" id="assignitloc" class="button" value="Change">
      <?php
    }
  }

  public function wcmlim_bulk_assign_default_location()
  {
    $user_id = get_current_user_id();
    if (!current_user_can('administrator', $user_id))
      return false;
    if (!is_admin()) {
        echo "Unauthorized access.";
        wp_die();
    }
    if ($_POST['type'] == "users") {
      $user_ids = isset($_POST['userids']) ? intval($_POST['userids']) : "";
      $new_value = isset($_POST['selected']) ? intval($_POST['selected']) : "";

      // Will return false if the previous value is the same as $new_value.
      $updated = update_user_meta($user_ids, 'wcmlim_user_specific_location', $new_value);

      // So check and make sure the stored value matches $new_value.
      if ($new_value != get_user_meta($user_ids, 'wcmlim_user_specific_location', true)) {
        echo "fail";
      } else {
        echo "success";
      }
    }

    if ($_POST['type'] == "product") {
      $product_ids = isset($_POST['productids']) ? intval($_POST['productids']) : "";
      $new_pvalue = isset($_POST['selected']) ? intval($_POST['selected']) : "";
      $prepare_val = '';
      $isExcLoc = get_option("wcmlim_exclude_locations_from_frontend");
      $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
      
      // Filter out excluded locations while preserving array keys
      if (!empty($isExcLoc)) {
        foreach ($terms as $key => $term) {
          if (in_array($term->term_id, $isExcLoc)) {
            unset($terms[$key]);
          }
        }
      }
      foreach ($terms as $in => $term) {
        $termid = $term->term_id;
        if ($termid == $new_pvalue) {
          $prepare_val = "loc_$in";

        }
      }
      $new_pvalue = $prepare_val;
      $product = wc_get_product($product_ids);
      if ($product->is_type("simple")) {
        update_post_meta($product_ids, "wcmlim_default_location", $new_pvalue);
        if ($new_pvalue != get_post_meta($product_ids, 'wcmlim_default_location', true)) {
          echo "fail";
        } else {
          echo "success";
        }
      } elseif ($product->is_type("variable")) {
        update_post_meta($product_ids, "wcmlim_default_location", $new_pvalue);
        $variations = $product->get_available_variations();
        $variations_id = wp_list_pluck($variations, 'variation_id');
        foreach ($variations_id as $vid) {
          update_post_meta($vid, "wcmlim_default_location", $new_pvalue);
          if ($new_pvalue != get_post_meta($vid, 'wcmlim_default_location', true)) {
            $smg = "fail";
          } else {
            $smg = "success";
          }
        }
        echo $smg;
      } else {
        update_post_meta($product_ids, "wcmlim_default_location", $new_pvalue);
        if ($new_pvalue != get_post_meta($product_ids, 'wcmlim_default_location', true)) {
          echo "fail";
        } else {
          echo "success";
        }
      }
    }

    wp_die();
  }
  /**
   * On single page List View or Dropdown Select
   *
   * @since  1.2.8
   */

  public function wcmlim_select_or_dropdown_callback()
  {
    $locchecked = get_option($this->option_name . '_select_or_dropdown');
    ?>
    <div class="wcmlim-setting-option-des">
      <label class="switch">
        <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_select_or_dropdown') ?>"
          name="<?php esc_attr_e($this->option_name . '_select_or_dropdown') ?>" <?php echo ($locchecked == 'on') ? 'checked="checked"' : ''; ?>>
        <span class="slider round"></span>
      </label>
    </div>
    <?php echo '<label>' . __('Enable this feature to display a radio listing for locations.', 'wcmlim') . '</label>'; ?>
  <?php
  }
  /**
   * On Radio List Show detail address or not
   *
   * @since  1.2.8
   */
  public function wcmlim_radio_loc_fulladdress_callback()
  {
    $showdetailladd = get_option($this->option_name . '_radio_loc_fulladdress');
    ?>
    <div class="wcmlim-setting-option-des">
      <label class="switch">
        <input type="checkbox" id="<?php esc_attr_e($this->option_name . '_radio_loc_fulladdress') ?>"
          name="<?php esc_attr_e($this->option_name . '_radio_loc_fulladdress') ?>" <?php echo ($showdetailladd == 'on') ? 'checked="checked"' : ''; ?>>
        <span class="slider round"></span>
      </label>
    </div>
    <?php echo '<label>' . __('Enable this feature to display detailed address information within the listing options.', 'wcmlim') . '</label>'; ?>
  <?php
  }
  /**
   * On Radio List Show detail address or not
   * 
   * @since  1.2.8
   */
  public function wcmlim_radio_loc_format_callback()
  {
    $showformat = get_option($this->option_name . '_radio_loc_format');
    $radion_location = array('half' => 'Two Column', 'third' => 'Three Column', 'scroll' => 'Scroll View', 'advanced_list_view' => 'Adv. List View');
    ?>
    <div class="wcmlim-setting-option-des">
      <select name="<?php esc_attr_e($this->option_name . '_radio_loc_format') ?>"
        id="<?php esc_attr_e($this->option_name . '_radio_loc_format') ?>">
        <option value="full"><?php _e('One Column', 'wcmlim'); ?></option>
        <?php
        foreach ($radion_location as $value => $text) {
          echo '<option value="' . $value . '" ' . selected($showformat, $value, false) . '>' . esc_html($text) . '</option>';
        } ?>
      </select>
    </div>
    <?php echo '<label>' . __('Choose between grid or scroll view for the location listing format.', 'wcmlim') . '</label>'; ?>
    <?php echo '<span class="locationshow_note">' . __('<strong>Note:-</strong> The default setting is <b>One column</b> selected.', 'wcmlim') . '</span>'; ?>
    <hr>
    <?php
  }

  /**
   * On Product Central
   *
   * @since  1.2.9
   */
  public function wcmlim_update_product_central()
  {
      if ( ! current_user_can( 'manage_options' ) ) {
          wp_send_json_error([
              'message' => 'Unauthorized access',
          ], 403);
          return;
      }
  
      check_ajax_referer('wcmlim_locations_nonce', 'security');
      
      if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
          wp_send_json(array(
              'success' => false,
              'message' => 'Invalid nonce'
          ));
          return;
      }
    
      if (!empty($_POST) && isset($_POST['arr']) && is_array($_POST['arr'])) {
          // Define allowed keys for security
          $allowed_keys = ['cb', 'id', 'thumbnail', 'name', 'sku', 'type', 'regular_price', 'sale_price', 'stock_status', 'manage_stock', 'stock_at_location', 'stock_quantity', 'short_description', 'description', 'status', 'backorders', 'weight', 'length', 'width', 'height']; // example allowed keys
          $arr = [];

          foreach ($_POST['arr'] as $key => $value) {
              $arrVal = explode("=", $value, 2); // Limit to 2 parts to avoid issues with '=' in value
              if (count($arrVal) !== 2) {
                  continue; // Skip malformed input
              }

              $field = trim($arrVal[0]);
              $val = trim($arrVal[1]);

              // Only process allowed keys
              if (in_array($field, $allowed_keys, true)) {
                  // Default checkbox behavior
                  if ($field === 'cb') {
                      $arr[$field] = 'Show';
                  } else {
                      $arr[$field] = sanitize_text_field($val); // Sanitize input
                  }
              }
          }

          update_option('ProductCentralControlOptions', $arr);
          echo json_encode($arr);
      } else {
          http_response_code(400);
          echo json_encode(['error' => 'Invalid input']);
      }
  }


  // function to update product stock in inventory management of product central
  function update_wcmlim_inventory_management() {

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
    }
 
    check_ajax_referer('wcmlim_locations_nonce', 'security');

    if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
      wp_send_json(array(
        'success' => false,
        'message' => 'Invalid nonce'
      ));
      return;
    }

    $product_id = intval($_POST['product_id']);
    $term_id = intval($_POST['term_id']);
    $stock = max(0, intval($_POST['stock'])); 

    if (!$product_id || !$term_id) {
        wp_send_json_error('Missing product or term ID');
    }

    // Update location stock
    update_post_meta($product_id, "wcmlim_stock_at_$term_id", $stock);

    // Recalculate total stock across all locations
    $locations = get_terms([
        'taxonomy' => 'locations',
        'hide_empty' => false,
        'parent' => 0
    ]);

    $total_stock = 0;
    foreach ($locations as $location) {
        $loc_stock = intval(get_post_meta($product_id, "wcmlim_stock_at_{$location->term_id}", true));
        $total_stock += $loc_stock;
    }

    // Update total stock
    update_post_meta($product_id, '_stock', $total_stock);

    // Optionally update WooCommerce stock status
    update_post_meta($product_id, '_stock_status', $total_stock > 0 ? 'instock' : 'outofstock');

    wp_send_json_success('Stock updated');
  }

  function save_inventory_selected_locations() {

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
    }
 
    check_ajax_referer('wcmlim_locations_nonce', 'security');

    if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_locations_nonce')) {
      wp_send_json(array(
        'success' => false,
        'message' => 'Invalid nonce'
      ));
      return;
    }

    $locations = $_POST['selected_locations'] ?? [];

    if (!is_array($locations)) {
        wp_send_json_error(['message' => 'Invalid data.']);
    }

    update_option('wcmlim_inventory_selected_locations', $locations);

    wp_send_json_success(['message' => 'Locations saved successfully.']);
  }

  /**
   * Product Update Function
   *
   * @since    1.0.0
   */
  public function wcmlim_product_updated()
  {

    if (!empty($_POST)) {
      $inp_value = $_POST['inp_value'];
      $data_id = absint($_POST['data-id']);
      $data_name = sanitize_text_field($_POST['data-name']);

      if ($data_name == "stckup_product_name") {
        wp_update_post([
          'ID' => $data_id,
          'post_title' => $inp_value
        ]);
      }

      if ($data_name == "stckup_product_stock_at_location") {
        $data_location = intval($_POST['data-location']);
        $inp_value = trim($inp_value);

        // Get product type (simple or variation)
        $product = wc_get_product($data_id);
        $product_type = $product->get_type();
        $parent_id = false;
        if ($product_type == 'variation') {
          $parent_id = wp_get_post_parent_id($data_id);
        }
      
        // Get current linked locations
        $current_terms = wp_get_object_terms( ($parent_id != false)? $parent_id : $data_id, 'locations', array('fields' => 'ids'));
        $current_term_ids = is_array($current_terms) ? $current_terms : [];
      
        if ($inp_value !== '' && is_numeric($inp_value) && intval($inp_value) >= 0) {
          // Link location if not already linked
          if (!in_array($data_location, $current_term_ids)) {
            $current_term_ids[] = $data_location;
            wp_set_object_terms(($parent_id != false)? $parent_id : $data_id, $current_term_ids, 'locations', false);
          }
      
          // Update stock metadata
          update_post_meta( $data_id, 'wcmlim_stock_at_' . $data_location, intval($inp_value));
        }
      
        // Recalculate total stock
        $updated_terms = wp_get_object_terms( ($parent_id != false)? $parent_id : $data_id, 'locations', array('fields' => 'ids'));
        $arr_stock = [];
        foreach ($updated_terms as $term_id) {
          $loc_stock_val = intval(get_post_meta($data_id, "wcmlim_stock_at_{$term_id}", true));
          array_push($arr_stock, $loc_stock_val);
        }
      
        $total_stock_qty = array_sum($arr_stock);
        update_post_meta($data_id, "_stock", $total_stock_qty);
      
        wp_update_post([
          'ID' => $data_id,
        ]);
      
        echo $data_name;
        wp_die();
      }
      
      if ($data_name == "stckup_product_sku") {
        update_post_meta($data_id, '_sku', $inp_value);
      }
      if ($data_name == "stckup_product_regular_price") {
        update_post_meta($data_id, '_regular_price', $inp_value);
        $chk_val = get_post_meta($data_id, '_sale_price', true);
        if (!isset($chk_val)) {
          update_post_meta($data_id, '_price', $inp_value);
        }
        wc_delete_product_transients($data_id);
      }
      if ($data_name == "stckup_product_sale_price") {
        $chk_val = get_post_meta($data_id, '_regular_price', true);
        $u_status = 1;

        if ($chk_val > $inp_value) {
          if ($inp_value != null || $inp_value != false) {
            update_post_meta($data_id, '_price', $inp_value);
            update_post_meta($data_id, '_sale_price', $inp_value);
          } else {
            $chk_v = get_post_meta($data_id, '_regular_price', true);
            update_post_meta($data_id, '_price', $chk_v);
            $u_status = 0;
          }
        } else {
          update_post_meta($data_id, '_sale_price', '--');
          $u_status = 0;
        }

        wc_delete_product_transients($data_id);
        if ($u_status == 0) {
          $updatestatus = 'false';
        } else {
          $updatestatus = 'true';
        }
        echo json_encode($updatestatus);
        wp_die();
      }
      if ($data_name == "stckup_product_stock_status") {
        update_post_meta($data_id, '_stock_status', $inp_value);
        $data_pid = isset($_POST['data-pid']) ? $_POST['data-pid'] : '';
        if ($data_pid) {
          $product = wc_get_product($data_pid);
          if (!empty($product) && $product->is_type('variable')) {
            $stock_status = array();
            $variations = $product->get_available_variations();
            $variations_id = wp_list_pluck($variations, 'variation_id');
            if (!empty($variations_id)) {
              foreach ($variations_id as $varid) {
                $stock_status[] = get_post_meta($varid, '_stock_status', true);
              }
            }
            if (in_array("instock", $stock_status)) {
              update_post_meta($data_pid, '_stock_status', 'instock');
            } else {
              update_post_meta($data_pid, '_stock_status', 'outofstock');
            }
          }
        }
      }
      if ($data_name == "product_stock_manage") {
        update_post_meta($data_id, '_manage_stock', $inp_value);
        wp_update_post([
          'ID' => $data_id,
        ]);
      }
      if ($data_name == "stckup_product_short_description") {
        wp_update_post([
          'ID' => $data_id,
          'post_excerpt' => $inp_value
        ]);
      }
      if ($data_name == "stckup_product_description") {
        wp_update_post([
          'ID' => $data_id,
          'post_content' => $inp_value
        ]);
      }
      if ($data_name == "stckup_product_status") {
        wp_update_post([
          'ID' => $data_id,
          'post_status' => $inp_value
        ]);
      }

      if ($data_name == "stckup_product_backorders") {
        update_post_meta($data_id, '_backorders', $inp_value);
      }
      if ($data_name == "stckup_product_tax_status") {
        global $wpdb;
        update_post_meta($data_id, '_tax_status', $inp_value);
        $table_name = $wpdb->prefix . 'wc_product_meta_lookup';
        $wpdb->query(
          $wpdb->prepare(
              "UPDATE `$table_name` SET `tax_status` = %s WHERE `product_id` = %d",
              $inp_value,
              $data_id
          )
      );      }
      if ($data_name == "stckup_product_length") {
        update_post_meta($data_id, '_length', $inp_value);
      }
      if ($data_name == "stckup_product_width") {
        update_post_meta($data_id, '_width', $inp_value);
      }
      if ($data_name == "stckup_product_height") {
        update_post_meta($data_id, '_height', $inp_value);
      }
      if ($data_name == "stckup_product_weight") {
        update_post_meta($data_id, '_weight', $inp_value);
      }
      if ($data_name == "stckup_product_category") {
        wp_set_object_terms($data_id, $inp_value, 'product_cat');
      }
      if ($data_name == "stckup_product_tag") {
        wp_set_object_terms($data_id, $inp_value, 'product_tag');
      }
      if ($data_name == "stckup_product_catalog_visibility") {
        update_post_meta($data_id, '_visibility', $inp_value);
        if ($inp_value == 'Hidden') {
          $terms = array('exclude-from-catalog', 'exclude-from-search');
        } else if ($inp_value == 'Catalog') {
          $terms = 'exclude-from-catalog';
        } else {
          $terms = 'exclude-from-search';
        }
        echo $terms;
        wp_set_object_terms($data_id, $terms, 'product_visibility');
      }
    }
    echo json_encode('success');
    wp_die();
  }

  /**
   * Callback function for populate shipping methods
   * 
   * @since 1.2.14
   */
  public function wcmlim_dynamic_shipping_methods()
  {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error([
            'message' => 'Unauthorized access',
        ], 403);
        return;
    }


    $allShippingMethodIds = isset($_POST['shippingMethods']) ? array_map('intval', $_POST['shippingMethods']) : array();

    if (!empty($allShippingMethodIds)) {
      $methods = array();

      foreach ($allShippingMethodIds as $zone_id) {
        // Get the shipping Zone object
        $shipping_zone = new WC_Shipping_Zone($zone_id);

        // Get all shipping method values for the shipping zone
        $shipping_methods = $shipping_zone->get_shipping_methods(true, 'values');

        foreach ($shipping_methods as $i => $value) {
          $methods[] = array(
            "key" => esc_html($i),
            "value" => esc_html($value->title),
          );
        }
      }
      echo json_encode($methods);
    }
    wp_die();

  }

  public function support_validator_admin_notice()
  {
    $wcmlim_validte = get_option('wcmlim_license', true);
    $wcmlim_support = get_option(WCMLIM_SVALIDATOR, true);
    $last_time = (is_object($wcmlim_support)) ? $wcmlim_support->time : null;

    if ($last_time == null) {
      // if last time is null then
      return;
    }
    $now = time();
    $datediff = $now - $last_time;
    if ($datediff < 5) { //604800 seconds means 1 week
      return;
    }
    if ($wcmlim_validte != 'invalid') {
      $user = wp_get_current_user();
      $buyer_email = $user->user_email;
      $purchase_code = get_option('purchase_code');
      $purchase_username = get_option('purchase_username');
      $url = get_site_url();
      $domain_str = parse_url($url, PHP_URL_HOST);
      $domain = str_replace('www.', '', $domain_str);
      if (!function_exists('wp_get_current_user')) {
        include(ABSPATH . "wp-includes/pluggable.php");
      }
      $json_array = array(
        "purchase_code" => $purchase_code,
        "purchase_username" => $purchase_username,
        "domain" => $domain,
        "email" => $purchase_username
      );
      $json_format = json_encode($json_array);

      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => "https://verify.techspawn.com/wp-json/my-route/support/",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $json_format,
        CURLOPT_HTTPHEADER => array(
          "accept: application/json",
          "content-type: application/json"
        ),
      ));

      $response = curl_exec($curl);
      $err = curl_error($curl);
      curl_close($curl);

      if ($err) {
      } else {
        $response;
      }
      $response_arr = json_decode($response);
      if (isset($response_arr->result) && $response_arr->result == 1) {
        $result = $response_arr->message;
        $supported_until = $response_arr->supported_until;
        $supported_until = date("d-m-Y", strtotime($supported_until));
        $now = time(); // or your date as well
        $support_date = strtotime($response_arr->supported_until);
        $datediff = $support_date - $now;
        $difffound = round($datediff / (60 * 60 * 24));
        if (strpos($difffound, '-') !== false) {
          ?>
          <div class="notice notice-error is-dismissible">
            <p>
              Your support for <b><?php echo $response_arr->product; ?></b> has been expired, please <a
                href="<?php echo $response_arr->url; ?>">Click here to renew your support</a>
            </p>
          </div>
          <?php
        } else {
          if ($difffound < 8) {
            ?>
            <div class="notice notice-warning is-dismissible">
              <p>
                Your support for <b><?php echo $response_arr->product; ?></b> expires in <b><?php echo $difffound; ?>Days</b>,
                please <a href="<?php echo $response_arr->url; ?>">Click here to renew your support</a>
              </p>
            </div>
            <?php
          } else {
            $response_arr->time = time();
            update_option(WCMLIM_SVALIDATOR, $response_arr);
          }
        }
        update_option('wcmlim_license', "valid");
      } else {
        ?>
        <div class="notice notice-error is-dismissible">
          <p><?php
          if (isset($response_arr->error_message)) {
            echo $response_arr->message;
          }
          ?></p>
        </div>
        <?php
        update_option('wcmlim_license', "invalid");
      }
    }
  }


  /**
   * Callback function for getting lat lng once
   * 
   * @since 1.2.14
   */


  public function wcmlim_get_lcpriority()
  {
    $lcpriority = isset($_POST['lcpriority']) ? intval($_POST['lcpriority']) : 0;
    $skip_location = isset($_POST['skip_location']) ? intval($_POST['skip_location']) : 0;

    if ($lcpriority === 0 || $skip_location === 0) {
      echo 'fail';
      wp_die();
    }

    $terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    $return_status = 0;

    foreach ($terms as $term) {
      $term_id = $term->term_id;

      if ($skip_location !== $term_id) {
        $cvalterm = get_term_meta($term_id, 'wcmlim_location_priority', true);

        if (intval($lcpriority) === intval($cvalterm)) {
          $return_status = 1;
          break; 
        }
      }
    }

    echo $return_status;
    wp_die();
  }

  function exclude_other_location_products($query)
  {
      $isShopManagerEnable = get_option('wcmlim_assign_location_shop_manager');
      global $pagenow;
      $current_user = wp_get_current_user();
      $qv = &$query->query_vars;
      $current_user_id = $current_user->ID;
  
      $currentUserRoles = $current_user->roles;
      if (in_array('location_shop_manager', $currentUserRoles) && $isShopManagerEnable === "on") {
          if ($pagenow === 'edit.php' && isset($qv['post_type']) && $qv['post_type'] === 'product') {
              $locations = get_terms(array(
                  'taxonomy' => 'locations',
                  'hide_empty' => false,
                  'parent' => 0
              ));
  
              $assigned_term_ids = [];
              foreach ($locations as $term) {
                  $shopManagers = get_term_meta($term->term_id, 'wcmlim_shop_manager', true);
                  if (is_array($shopManagers) && in_array($current_user_id, $shopManagers)) {
                      $assigned_term_ids[] = $term->term_id;
                  }
              }
  
              if (empty($assigned_term_ids)) {
                  $query->set('post__in', [0]);
                  return;
              }
  
              $meta_queries = ['relation' => 'OR'];
              foreach ($assigned_term_ids as $term_id) {
                  $meta_queries[] = [
                      'key' => "wcmlim_stock_at_{$term_id}",
                      'value' => 0,
                      'compare' => '='
                  ];
                  $meta_queries[] = [
                      'key' => "wcmlim_stock_at_{$term_id}",
                      'value' => '',
                      'compare' => '='
                  ];
                  $meta_queries[] = [
                      'key' => "wcmlim_stock_at_{$term_id}",
                      'value' => 0,
                      'compare' => '>',
                      'type' => 'NUMERIC'
                  ];
              }
  
              $limit = -1;
  
              $products_ids = get_posts(array(
                  'post_type' => ['product'],
                  'numberposts' => $limit,
                  'fields' => 'ids',
                  'tax_query' => array(
                      array(
                          'taxonomy' => 'locations',
                          'field' => 'id',
                          'terms' => $assigned_term_ids,
                          'include_children' => false
                      )
                  ),
                  'meta_query' => $meta_queries
              ));
  
              $variation_products_ids = get_posts(array(
                  'post_type' => ['product_variation'],
                  'numberposts' => $limit,
                  'fields' => 'ids',
                  'tax_query' => array(
                      array(
                          'taxonomy' => 'locations',
                          'field' => 'id',
                          'terms' => $assigned_term_ids,
                          'include_children' => false
                      )
                  ),
                  'meta_query' => $meta_queries
              ));
  
              $all_ids = array_merge($products_ids, $variation_products_ids);
              error_log(print_r($all_ids, true)); // Debug log
              $query->set('post__in', $all_ids);
          }
      }
  }
  

  public function wcmlim_get_lat_lng()
  {

    global $latlngarr;
    $nonce = isset($_POST['security']) ? sanitize_text_field($_POST['security']) : '';
    if (!wp_verify_nonce($nonce, 'wcmlim_locations_nonce')) {
      wp_die(__('Security check', 'wcmlim'));
    } else {
      $wcmlim_autocomplete_address = isset($_POST['wcmlim_autocomplete_address']) ? sanitize_text_field($_POST['wcmlim_autocomplete_address']) : '';

      if (empty($wcmlim_autocomplete_address)) {
        echo 'Please enter address.';
        wp_die();
      }

      // URL-encode the address and use a more structured way to build the URL
      $address = urlencode(str_replace(',', '+', str_replace(' ', '+', $wcmlim_autocomplete_address)));
      $api_key = get_option('wcmlim_google_api_key');
      $api_url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&sensor=false&key=$api_key";

      // Initialize cURL and set options
      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
      ));

      // Execute the cURL request
      $geocode = curl_exec($curl);
      curl_close($curl);

      // Decode the JSON response
      $output = json_decode($geocode);

      // Extract latitude and longitude
      $latitude = 0;
      $longitude = 0;

      if (isset($output->results[0]->geometry->location->lat)) {
        $latitude = $output->results[0]->geometry->location->lat;
        $longitude = $output->results[0]->geometry->location->lng;
      }

      // Create the response array
      $latlngarr = array(
        'latitude' => $latitude,
        'longitude' => $longitude
      );

      // Return JSON response and terminate the script
      echo json_encode($latlngarr);
      wp_die();
    }
  }

  public function wcmlim_manage_product_fields()
  {
    global $pagenow;

    $current_user = wp_get_current_user();
    $currentUserRoles = $current_user->roles;

    if (in_array('location_shop_manager', $currentUserRoles) || in_array("location_regional_manager", $currentUserRoles)) {
      $isShopManagerEnable = get_option('wcmlim_assign_location_shop_manager');

     if ( $pagenow === 'post.php' && isset($_GET['post']) ) {
        $post_id = intval($_GET['post']);
        $post_type = get_post_type($post_id);

    // Check if it's the edit product page
      if ($isShopManagerEnable) {
        if ( $post_type === 'product' ) {

        ?>
        <style>
          .general_options {
            display: none !important;
          }

          .advanced_options {
            display: none !important;
          }

          .linked_product_options {
            display: none !important;
          }

          .notManager {
            display: none !important;
          }

          #wp-content-editor-container {
            pointer-events: none;
            opacity: 0.6;
            cursor: not-allowed;
            background-color: #f7f7f7;
          }

          #titlewrap {
            pointer-events: none;
            opacity: 0.6;
            cursor: not-allowed;
          }

          .wp-editor-area {
            background-color: #eee !important;
            color: #888 !important;
            border: 1px solid #ddd !important;
          }
        </style>

        <?php

      }
    }
    }
  }
  }
}
