<?php
// use \Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
use \Automattic\WooCommerce\Utilities\OrderUtil;
update_option('wcmlim_license', "valid");
/**
 * Copyright: (c)  [2020] - Techspawn Solutions Private Limited ( contact@techspawn.com  ) 
 *  All Rights Reserved.
 * 
 * NOTICE:  All information contained herein is, and remains
 * the property of Techspawn Solutions Private Limited,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Techspawn Solutions Private Limited,
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Techspawn Solutions Private Limited
 *
 * @link              http://www.techspawn.com
 * @since             1.0.0
 * @package           Wcmlim
 *
 * @wordpress-plugin
 * Plugin Name:       MULTILOCA - WooCommerce Multi Locations Inventory Management
 * Plugin URI:        http://www.techspawn.com
 * Description:       This plugin will help you manage WooCommerce Products stocks through locations.
 * Version:           4.2.14
 * Requires at least: 5.0
 * Author:            Techspawn Solutions
 * Author URI:        http://www.techspawn.com
 * License:           GNU General Public License v3.0
 * License URI:       http://www.gnu.org/licenses/gpl-3.0.html
 * Text Domain:       wcmlim
 * Domain Path:       /languages
 * WC requires at least:	5.0
 * WC tested up to: 	5.8.0
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
	die;
}



/**
 * Currently plugin version.
 * Start at version 1.0.0 and use SemVer - https://semver.org
 * Rename this for your plugin and update it as you release new versions.
 */
define('WCMLIM_VERSION', '4.2.0');
/**
 * Define default path and url for plugin.
 * 
 * @since    1.1.5
 */
define('WCMLIM_DIR_PATH', plugin_dir_path(__FILE__));
define('WCMLIM_URL_PATH', plugins_url('/', __FILE__));
define('WCMLIM_BASE', plugin_basename(__FILE__));
define('WCMLIM_SVALIDATOR', 'wcmlim_support_validater');

add_action("enqueue_block_editor_assets", "wcmlim_blocks_enqueue");

function wcmlim_blocks_enqueue()
{
	wp_enqueue_script('wcmlim-switch-block', plugin_dir_url(__FILE__) . 'admin/blocks/switch-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_script('wcmlim-popup-block', plugin_dir_url(__FILE__) . 'admin/blocks/popup-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_script('wcmlim-location-finder-block', plugin_dir_url(__FILE__) . 'admin/blocks/loc-finder-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_script('wcmlim-lflv-block', plugin_dir_url(__FILE__) . 'admin/blocks/lflv-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_script('wcmlim-locinfo-block', plugin_dir_url(__FILE__) . 'admin/blocks/locinfo-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_script('wcmlim-prod-by-id-block', plugin_dir_url(__FILE__) . 'admin/blocks/prod-by-id-block.js', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, true);

	wp_enqueue_style('wcmlim-popup-block', plugin_dir_url(__FILE__) . 'admin/css/wcmlim-popup-block.css', array('wp-blocks', 'wp-i18n', 'wp-editor'), true, false);

	wp_enqueue_script('jquery', 'ajaxurl', admin_url('admin-ajax.php')); // Localize ajaxurl for front-end AJAX requests

	wp_enqueue_script('multiloca-sweet-js', plugins_url('', __FILE__) . '/js/sweetalert.js', array('jquery'), '1.0', true);

    wp_enqueue_script('wcmlim-async-locations', plugin_dir_url(__FILE__) . 'js/wcmlim-async-locations.js', array('jquery'), '1.0', true);


}



//----------------for choosen function ----------------//

add_action('admin_enqueue_scripts', 'enqueue_chosen_scripts');

function enqueue_chosen_scripts() {
    // Enqueue Chosen CSS
    wp_enqueue_style('chosen-css', 'https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css', [], '1.8.7');
    
    // Enqueue Chosen JS
    wp_enqueue_script('chosen-js', 'https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js', ['jquery'], '1.8.7', true);

	wp_enqueue_script('select2-js', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), null, true);
    wp_enqueue_style('select2-css', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');
}




function wcmlim_block_category($categories)
{
	$custom_block = array(
		'slug' => 'amultilocation',
		'title' => 'Multilocations For WooCommerce'
	);
	$categories_sorted = array();
	$categories_sorted[0] = $custom_block;
	foreach ($categories as $category) {
		$categories_sorted[] = $category;
	}
	return $categories_sorted;
}
add_filter('block_categories', 'wcmlim_block_category', 10, 2);

/**
 * The code that runs during plugin activation.
 * This action is documented in includes/class-wcmlim-activator.php
 */
function wcmlim_activate()
{
	$active_plugins = get_option('active_plugins');
	$wooactive_plugins = is_woocommerce_activated();
	/**
	 * Check if WooCommerce is active
	 **/
	
	$locationCookieTime = get_option('wcmlim_set_location_cookie_time');
	if ($locationCookieTime == '') {
		update_option('wcmlim_set_location_cookie_time', '30');
	}

	if ( is_multisite() ) { 
		require_once plugin_dir_path(__FILE__) . 'includes/class-wcmlim-activator.php';
		Wcmlim_Activator::activate();
	} else {    
		if ($wooactive_plugins == 0) {
			deactivate_plugins(__FILE__);
			$error_message = esc_html_e('WooCommerce has not yet been installed or activated. MULTILOCA - WooCommerce Multi Locations Inventory Management is a WooCommerce Extension that will only function if WooCommerce is installed. Please first install and activate the WooCommerce Plugin.', 'wcmlim');
			wp_die($error_message, 'Plugin dependency check', array('back_link' => true));
		} else {
			
			$soldoutbutton_text = get_option('wcmlim' . '_soldout_button_text');
			if ($soldoutbutton_text  == false) {
				update_option('wcmlim' . '_soldout_button_text', 'Sold Out');
			}
			
		  $stockbutton_text = get_option('wcmlim' . '_instock_button_text');
		  if ($stockbutton_text  == false) {
			update_option('wcmlim' . '_instock_button_text', 'In Stock');
		  }
	
		  $backorder_text = get_option('wcmlim' . '_onbackorder_button_text');
		  if ($backorder_text  == false) {
			update_option('wcmlim' . '_onbackorder_button_text', 'Available on backorder');
		  }
	
			require_once plugin_dir_path(__FILE__) . 'includes/class-wcmlim-activator.php';
			Wcmlim_Activator::activate();
		} }
	
}
add_action('admin_init', 'wcmlim_deactivate_self');
function wcmlim_deactivate_self()
{		
	$plugins_dir = basename(dirname(__FILE__));
	$woocommerce_active_plugins = is_woocommerce_activated();
	if ($woocommerce_active_plugins == 0) {
		if (is_plugin_active($plugins_dir.'/wcmlim.php')) {
			
			deactivate_plugins($plugins_dir.'/wcmlim.php');
		}
	}
}
if (!function_exists('is_woocommerce_activated')) {
    function is_woocommerce_activated()
    {
        $active_plugins = get_option('active_plugins');
        $wooactive_plugins = 0;
        foreach ($active_plugins as $key => $value) {
            if (strpos($value, 'woocommerce.php') !== false) {
				
				$wooactive_plugins = 1;
			}
        }
        update_option('woocommerce_active_plugins', $wooactive_plugins);
        return $wooactive_plugins;
    }
}

/**
 * The code that runs during plugin deactivation.
 * This action is documented in includes/class-wcmlim-deactivator.php
 */
function wcmlim_deactivate()
{
	require_once plugin_dir_path(__FILE__) . 'includes/class-wcmlim-deactivator.php';
	Wcmlim_Deactivator::deactivate();
}

register_activation_hook(__FILE__, 'wcmlim_activate');
register_deactivation_hook(__FILE__, 'wcmlim_deactivate');

$open_pos_compatiblity = get_option('wcmlim_pos_compatiblity');
$open_pos_dynamic_pricing = get_option('wcmlim_pos_dynamic_pricing');

/**
 * The core plugin class that is used to define internationalization,
 * admin-specific hooks, and public-facing site hooks.
 */
require plugin_dir_path(__FILE__) . 'includes/class-wcmlim.php';
require plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-sync-locations-to-product.php';

include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-order-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/generic/wcmlim-generic-add-to-cart-button-helper.php';	
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-proximity-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/location-assignment/wcmlim-location-assignment-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim_location-discount.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim_google-reviews.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-woo-beta-helper.php';
include plugin_dir_path(__FILE__) . 'compatiblity/Xstore/replace-xstore-theme-file.php';
include plugin_dir_path(__FILE__) . 'includes/class-wcmlim-rest-api.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-location-count-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-product-location-selector.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-cache-helper.php';
include plugin_dir_path(__FILE__) . 'admin/wcmlim-async-load-helper.php';
include plugin_dir_path(__FILE__) . 'admin/wcmlim-multiloca-menu-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-woo-product-csv-importer-helper.php';
include plugin_dir_path(__FILE__) . 'includes/helper/openpos/wcmlim-openpos-helper.php';

// CTX Feed Manager Integration
$ctx_feed_enabled = get_option('wcmlim_enable_ctx_feed');
if (!empty($ctx_feed_enabled) && $ctx_feed_enabled == 'on') {
        include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim-ctx-feed-integration.php';
        
        // Initialize CTX Feed Integration using singleton pattern
        // Note: No separate feed generator needed - we extend CTX Feed directly
        add_action('plugins_loaded', function() {
                WCMLIM_CTX_Feed_Integration::get_instance();
        }, 20);
}


// Flush rewrite rules only when CTX Feed setting is updated in admin
function wcmlim_maybe_flush_rewrite_rules($option, $old_value, $value) {
    if ($option === 'wcmlim_enable_ctx_feed' && $old_value !== $value) {
        flush_rewrite_rules();
    }
}
add_action('updated_option', 'wcmlim_maybe_flush_rewrite_rules', 10, 3);

if(!empty($open_pos_compatiblity) && $open_pos_compatiblity == 'on' && !empty($open_pos_dynamic_pricing) && $open_pos_dynamic_pricing == 'on') {

	include plugin_dir_path(__FILE__) . 'includes/helper/openpos/wcmlim-openpos-dynamic-pricing.php';

}


register_activation_hook(__FILE__, 'wcmlim_run_sync_location_count_once');

function wcmlim_is_checkout_block()
{
    $post_id = get_option('woocommerce_checkout_page_id'); 
    $post = get_post($post_id);
    if ($post && isset($post->post_content)) {
        
        return false !== strpos($post->post_content, '<!-- wp:woocommerce/checkout');
    }

	return false;
}

$is_checkout_block_enabled = wcmlim_is_checkout_block();


if(!empty($is_checkout_block_enabled)){
include plugin_dir_path(__FILE__) . 'includes/helper/wcmlim_cart_checkout_block_helper.php';
}

/**
 * Begins execution of the plugin.
 *
 * Since everything within the plugin is registered via hooks,
 * then kicking off the plugin from this point in the file does
 * not affect the page life cycle.
 *
 * @since    1.0.0
 */
function wcmlim_run()
{
	$plugin = new Wcmlim();
	$plugin->run();

	// Declare compatibility with WooCommerce HPOS feature
	add_action(
		'before_woocommerce_init',
		function() {
			if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
				\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
			}
			if ( class_exists( '\Automattic\WooCommerce\Utilities\OrderUtil' ) && 
				 method_exists( '\Automattic\WooCommerce\Utilities\OrderUtil', 'custom_orders_table_usage_is_enabled' ) &&
				 function_exists( 'wc_get_container' ) ) {
				try {
					if ( OrderUtil::custom_orders_table_usage_is_enabled() ) {
						update_option('wcmlim_hpos_enabled', 'on');
					} else {
						update_option('wcmlim_hpos_enabled', 'off');
					}
				} catch (Exception $e) {
					// Fallback if there's an error
					$hpos_enabled = get_option('woocommerce_custom_orders_table_enabled') === 'yes';
					update_option('wcmlim_hpos_enabled', $hpos_enabled ? 'on' : 'off');
				}
			} else {
				// Fallback for older WooCommerce versions
				$hpos_enabled = get_option('woocommerce_custom_orders_table_enabled') === 'yes';
				update_option('wcmlim_hpos_enabled', $hpos_enabled ? 'on' : 'off');
			}
		}
	);
}
wcmlim_run();

// Include location archive pricing functionality
if (!is_admin()) {
    include_once plugin_dir_path(__FILE__) . 'public/controller/shop/wcmlim-location-archive-pricing.php';
}

//write shortcode for wocommerce related products
function wcmlim_related_products_shortcode()
{
    ob_start();
	$product_id = get_the_ID();
	$terms = get_the_terms( $product_id, 'product_cat' );
	$term_names = array();
	if ( $terms && ! is_wp_error( $terms ) ) {
		foreach ( $terms as $term ) {
			if ( $term->name !== 'Uncategorized' ) {
				$term_names[] = $term->name;
			}
		}
	}
	
	// Replace the direct cookie access with getLocation()
    $selected_loc_id = (int)( getLocation('wcmlim_selected_location') ?: 0 );
    
	$locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
	//get hide out of stock settings
	foreach($locations as $key => $term){     
		if($key == $selected_loc_id){
			$term_slug = $term->slug;
			$term_id = $term->term_id;
			break;
		}
	}
    $q = new WP_Query(array(
        'post_type'      => 'product',
        'posts_per_page' => '4',
		'tax_query' => array(
			'relation' => "AND",
			array(
				'taxonomy' => 'product_cat',
				'field'    => 'name',
				'terms'    => $term_names,
				'operator' => 'IN'
			),

			array(
			'taxonomy' => 'product_visibility',
			'field'    => 'name',
			'terms'    => array('outofstock'),
			'operator' => 'NOT IN'
			),
			array(
				'taxonomy' => 'locations',
				'field'    => 'slug',
				'terms'    => array($term_slug),
				'operator' => 'IN'	
			),

	),
	'meta_query'    => array(
		'relation' => 'AND',
		array(
			'key'       => 'wcmlim_stock_at_'.$term_id,
			'value'     => 0,
			'compare'   => '!=',
		),
		array(
			'key'       => 'wcmlim_stock_at_'.$term_id,
			'value'     => '',
			'compare'   => '!=',
		),

	),
    ));

    if ($q->have_posts()) {
        echo '<div class="related-products-grid">'; 

        $counter = 0;
        while ($q->have_posts()) {
            $q->the_post();

            echo '<div class="related-product-item">';
            wc_get_template_part('content', 'product');
            echo '</div>';

            $counter++;
            if ($counter % 3 === 0) {
                echo '<div class="related-products-grid"></div>'; 
            }
        }

        echo '</div>'; 

        wp_reset_postdata();
    } else {
        echo 'No related products found.';
    }

    return ob_get_clean();
}

add_shortcode('wcmlim_related_products_shortcode', 'wcmlim_related_products_shortcode');
function wcmlim_locations_storeview_shortcode() {
	$shortcode_view = get_option("wcmlim_header_shortcode_view");
	ob_start();
    ?>
    <style>
        .wcmlim-storeshrtsearch_container {
            display: flex ;
            align-items: center ;
			border: 1px solid #e2dcdc ;
            padding: 0px 10px ;
            max-width: 100% ;
            cursor: pointer ;
			width: 85%;
        }

        .wcmlim-storeshrtsearch_input {
            border: none ;
            outline: none ;
            flex: 1 ;
            padding: 10px ;
            font-size: 16px ;
            color: #333;
            background-color: transparent ;
            box-shadow: none ;
        }

        .wcmlim-storeshrtsearch_icons {
            display: flex;
            gap: 15px;
        }

        .wcmlim-storeshrtsearch_icons, .wcmlim-storeshrtlocation_icon {
            font-size: 20px;
            color: #333;
        }

		#wcmlim-storeshrtsearchlocation_btn {
			padding: 10px 20px;
            font-size: 16px;
            background-color: #333;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
		}
		.wcmlim-storeshrtpopup_content {
			color: #6d6d6d;
			font-size: 18px;
			text-align: left;
			width: 400px;
			height: 100%;
		}
		.wcmlim-storeshrtclosePopupBtn {
			font-size: 36px;
			color: #000000;
			border: none;
			background: none;
			cursor: pointer;
			padding: 0;
		}
		.wcmlim-storeshrtheader {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-right: 20px;
			padding-left: 20px;
			border-bottom: 1px solid #dadada;
		}
		.wcmlim-storeshrttitle {
			margin: 0;
		}
		.wcmlim-storeshrtsearch {
			padding-top: 30px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.wcmlim-storeshrtshowlocations {
			height: 100%;
			margin-top: 30px;
		}
		.wcmlim-storeshrtlocationlist {
			display: flex;
			flex-direction: column;
			gap: 15px;
			width: 100%;
			align-items: center;
			justify-content: center;
			cursor: pointer;
		}
		.wcmlim-storeshrtlocation_item {
			background-color: #fff;
			padding: 10px;
			transition: box-shadow 0.3s ease-in-out;
			width: 85%;
			text-align: center;
			border: 1px solid #e2dcdc;
		}
		#wcmlim-storeshrtspinner {
			display: none;
			text-align: center;
			margin-top: 10px;
		}
		.wcmlim-storeshrtlocation_item.highlighted {
			background-color: #f2f2f2;
    	}
		#wcmlim-storeshrtclosePopupBtn:hover {
			background-color: unset;
			border-color: unset;
			color: unset;
		}
		#wcmlim-storeshrtclosePopupBtn:focus {
			outline: unset;
		}
		#wcmlim-storeshrtsearch_apply,
		#wcmlim-storeshrtsearch_remove {
			display: none;
		}
		#wcmlim-storeshrtsearch_remove {
			margin-right: 16px;
			border-right: 1px solid #959494;
			padding-right: 15px;
		}
		#wcmlim-storeautodetectbrowser_apply {
			font-size: 20px;
		}
		#wcmlim_storeshrtsearch_input {
			background-color: unset;
			box-shadow: unset;
		}
		#wcmlim_storeshrtsearch_input:focus {
			outline: unset;
		}
		.wcmlim-storeshrtmodal {
			visibility: hidden;
			opacity: 0;
			position: fixed;
			z-index: 1;
			padding-top: 100px;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
			background-color: rgba(0, 0, 0, 0.4);
			z-index: 10000000;
		}
		#wcmlim-storeshrtsidePopup {
			width: 400px;
			transition: transform 0.3s ease-in-out;
			transform: translateX(100%);
			height: 100%;
			position: fixed;
			top: 0;
			right: 0;
			background-color: #ffffff;
			overflow-x: hidden;
			z-index: 9999;
			box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
		}
		.wcmlim-storeshrtmodal.active {
			visibility: visible;
			opacity: 1;
		}
		#wcmlim-storeshrtsidePopup.active {
			transform: translateX(0);
		}
    </style>

	<?php
		$isLcex = get_option("wcmlim_exclude_locations_from_frontend");
		if (!empty($isLcex)) {
			$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0, 'exclude' => $isLcex));
		} else {
			$terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
		}
		$locations_list = [];
		$i = 0;
		foreach ($terms as $term) {
			$term_meta = get_option("taxonomy_$term->term_id");
			$term_meta = array_map(function ($term) {
				if (!is_array($term)) {
					return $term;
				}
			}, $term_meta);
			$locations_list[$i]['location_address'] = implode(" ", array_filter($term_meta));
			$locations_list[$i]['location_name'] = $term->name;
			$locations_list[$i]['term_id'] = $term->term_id;
			$i++;
		}
		$selected_location_termid = isset($_COOKIE['wcmlim_selected_location_termid']) ? intval($_COOKIE['wcmlim_selected_location_termid']) : null;
	?>

	<div id="wcmlim-storeshrtsearchlocation_sec">
		<button type="button" id="wcmlim-storeshrtsearchlocation_btn">
			<i class="dashicons-location dashicons" aria-hidden="true"></i>
			<span>&nbsp;&nbsp;
			<?php
				if( !empty($selected_location_termid) ){
					foreach($locations_list as $k => $location) {
						if($selected_location_termid === $location['term_id']) {
							?>
							<span id="wcmlim-storeshrtselected" data-view="<?php echo $shortcode_view; ?>">
								<?php echo $location['location_name']; ?>
							</span>
							<?php
						}
					}
				} else {
					?>
					<span id="wcmlim-storeshrtselected" data-view="<?php echo $shortcode_view; ?>">
						<?php echo 'Select Store'; ?>
					</span>
					<?php
				}
			?>	
			</span>
		</button>
	</div>
	<?php 
	if($shortcode_view == 'drawer') {
		?>
		<div id="wcmlim-storeshrtmodal" class="wcmlim-storeshrtmodal">
			<div id="wcmlim-storeshrtsidePopup" class="wcmlim-storeshrtside_popup">
				<div class="wcmlim-storeshrtpopup_content">
					<div class="wcmlim-storeshrtheader">
						<h4 class="wcmlim-storeshrttitle">Select store</h4>
						<button type="button" id="wcmlim-storeshrtclosePopupBtn" class="wcmlim-storeshrtclosePopupBtn">&times;</button>
					</div>
					<div class="wcmlim-storeshrtcontent">
						<div class="wcmlim-storeshrtsearch ">
							<div class="wcmlim-storeshrtsearch_container">
								<div id="wcmlim-storeshrtsearch_icons">
									<i class="fa fa-search" aria-hidden="true" id=""></i>
								</div>
								<input type="text" class="wcmlim-storeshrtsearch_input" placeholder="Search by location" id="wcmlim_storeshrtsearch_input" name="wcmlim_storeshrtsearch_input" />
								<div id="wcmlim-storeshrtsearch_remove">
									<i class="fa fa-times" aria-hidden="true" id="wcmlim-search_remove"></i>
								</div>
								<div id="wcmlim-storeshrtsearch_apply">
									<i class="fa fa-search" aria-hidden="true" id="wcmlim-search_apply"></i>
								</div>
								<div id="wcmlim-storeshrtdetect_icons">
									<i class="fas fa-crosshairs" aria-hidden="true" id="wcmlim-storeautodetectbrowser_apply"></i>
								</div>
							</div>
						</div>
						<div id="wcmlim-storeshrtspinner">
							<i class="fas fa-spinner fa-spin"></i>
						</div>
						<div class="wcmlim-storeshrtshowlocations">
							<div class="wcmlim-storeshrtlocationlist">
								<?php
									foreach($locations_list as $k => $location) {
										?>
											<div class="wcmlim-storeshrtlocation_item <?php echo ($selected_location_termid === $location['term_id']) ? 'highlighted' : ''; ?>" id="<?php echo $location['term_id']; ?>">
												<div style="display: none;">
															<input type="radio" name="select_location" id="select_location_<?php echo $k; ?>" value="<?php echo $k; ?>" data-locationname = "<?php echo $location['location_name']; ?>" data-locationid = "<?php echo $location['term_id']; ?>" data-locationaddress = "<?php echo $location['location_address']; ?>" class="wcmlim-storeshrtlocation_item_input"
																class="wclimloc_<?php echo $term->slug; ?>"
																onchange="handleStoreChange(this)"
															style="margin-right: 10px;"
															<?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
												</div>
												<?php
												// Initialize address variables
												$street_no = '';
												$route = '';
												$locality = '';
												$city = '';
												$state = '';
												$postal_code = '';
												$country = '';
												
												// Get address components based on settings
												if(get_option('wcmlim_show_street_in_shortcode') == "on") {
													$street_no = get_term_meta($location['term_id'], 'wcmlim_street_number', true);
												}
												if(get_option('wcmlim_show_route_in_shortcode') == "on") {
													$route = get_term_meta($location['term_id'], 'wcmlim_route', true);
												}
												if(get_option('wcmlim_show_city_in_shortcode') == "on") {
													$city = get_term_meta($location['term_id'], 'wcmlim_city', true);
												}
												if(get_option('wcmlim_show_state_in_shortcode') == "on") {
													$state = get_term_meta($location['term_id'], 'wcmlim_administrative_area_level_1', true);
												}
												if(get_option('wcmlim_show_postcode_in_shortcode') == "on") {
													$postal_code = get_term_meta($location['term_id'], 'wcmlim_postal_code', true);
												}
												if(get_option('wcmlim_show_country_in_shortcode') == "on") {
													$country = get_term_meta($location['term_id'], 'wcmlim_country', true);
												}
												
												// Build address array with non-empty components
												$address_components = array_filter(array(
													$route,
													$locality,
													$street_no,
													$city,
													$state,
													$postal_code,
													$country
												));
												
												// Join with commas and spaces
												$formatted_address = implode(', ', $address_components);
												?>
												<div>
													<p class="wcmlim-storeshrttitle"><?php echo $location['location_name']; ?></p>
													<p style="margin-bottom: 0;">
														<?php echo $formatted_address; ?>
													</p>
												</div>
											</div>
										<?php
									}
								?>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	} else if($shortcode_view == 'popup') {
		?>
		<style>
			.wcmlim-storeshrtpopupmodal {
				display: none; 
				position: fixed; 
				z-index: 9999;
				padding-top: 100px;
				left: 0;
				top: 0;
				width: 100%;
				height: 100%;
				overflow: auto; 
				background-color: rgb(0,0,0); 
				background-color: rgba(0,0,0,0.4); 
			}

			.wcmlim-storeshrtpopupmodal_content {
				background-color: #fefefe;
				margin: auto;
				padding: 0;
				border: 1px solid #888;
				width: 25%;
			}

			.wcmlim-storeshrtpopupmodal_close {
				color: #aaaaaa;
				float: right;
				font-size: 28px;
				font-weight: bold;
			}

			.wcmlim-storeshrtpopupmodal_close:hover,
			.wcmlim-storeshrtpopupmodal_close:focus {
				color: #000;
				text-decoration: none;
				cursor: pointer;
			}
			.wcmlim-storeshrtcontent {
				padding: 0 0 30px 0;
			}
		</style>
		<div id="wcmlim-storeshrtpopupmodal" class="wcmlim-storeshrtpopupmodal">
			<div class="wcmlim-storeshrtpopupmodal_content">
				<div class="wcmlim-storeshrtheader">
					<h4 class="wcmlim-storeshrttitle">Select store</h4>
					<button type="button" id="wcmlim-storeshrtclosePopupBtn" class="wcmlim-storeshrtclosePopupBtn">&times;</button>
				</div>
				<div class="wcmlim-storeshrtcontent">
					<div class="wcmlim-storeshrtsearch ">
						<div class="wcmlim-storeshrtsearch_container">
							<div id="wcmlim-storeshrtsearch_icons">
								<i class="fa fa-search" aria-hidden="true" id=""></i>
							</div>
							<input type="text" class="wcmlim-storeshrtsearch_input" placeholder="Search by location" id="wcmlim_storeshrtsearch_input" name="wcmlim_storeshrtsearch_input" />
							<div id="wcmlim-storeshrtsearch_remove">
								<i class="fa fa-times" aria-hidden="true" id="wcmlim-search_remove"></i>
							</div>
							<div id="wcmlim-storeshrtsearch_apply">
								<i class="fa fa-search" aria-hidden="true" id="wcmlim-search_apply"></i>
							</div>
							<div id="wcmlim-storeshrtdetect_icons">
								<i class="fas fa-crosshairs" aria-hidden="true" id="wcmlim-storeautodetectbrowser_apply"></i>
							</div>
						</div>
					</div>
					<div id="wcmlim-storeshrtspinner">
						<i class="fas fa-spinner fa-spin"></i>
					</div>
					<div class="wcmlim-storeshrtshowlocations">
						<div class="wcmlim-storeshrtlocationlist">
							<?php
							foreach($locations_list as $k => $location) { 
							?>
								<div class="wcmlim-storeshrtlocation_item <?php echo ($selected_location_termid === $location['term_id']) ? 'highlighted' : ''; ?>" id="<?php echo $location['term_id']; ?>">
									<div style="display: none;">
										<input type="radio" name="select_location" id="select_location_<?php echo $k; ?>" value="<?php echo $k; ?>" data-locationname = "<?php echo $location['location_name']; ?>" data-locationid = "<?php echo $location['term_id']; ?>" data-locationaddress = "<?php echo $location['location_address']; ?>" class="wcmlim-storeshrtlocation_item_input"
											class="wclimloc_<?php echo $term->slug; ?>"
											onchange="handleStoreChange(this)"
											style="margin-right: 10px;"
											<?php echo ($selected_location_termid === $term->term_id) ? 'checked' : ''; ?>>
									</div>
									<?php
												// Initialize address variables
												$street_no = '';
												$route = '';
												$locality = '';
												$city = '';
												$state = '';
												$postal_code = '';
												$country = '';
												
												// Get address components based on settings
												if(get_option('wcmlim_show_street_in_shortcode') == "on") {
													$street_no = get_term_meta($location['term_id'], 'wcmlim_street_number', true);
												}
												if(get_option('wcmlim_show_route_in_shortcode') == "on") {
													$route = get_term_meta($location['term_id'], 'wcmlim_route', true);
												}
												if(get_option('wcmlim_show_city_in_shortcode') == "on") {
													$city = get_term_meta($location['term_id'], 'wcmlim_city', true);
												}
												if(get_option('wcmlim_show_state_in_shortcode') == "on") {
													$state = get_term_meta($location['term_id'], 'wcmlim_administrative_area_level_1', true);
												}
												if(get_option('wcmlim_show_postcode_in_shortcode') == "on") {
													$postal_code = get_term_meta($location['term_id'], 'wcmlim_postal_code', true);
												}
												if(get_option('wcmlim_show_country_in_shortcode') == "on") {
													$country = get_term_meta($location['term_id'], 'wcmlim_country', true);
												}
												
												// Build address array with non-empty components
												$address_components = array_filter(array(
													$route,
													$locality,
													$street_no,
													$city,
													$state,
													$postal_code,
													$country
												));
												
												// Join with commas and spaces
												$formatted_address = implode(', ', $address_components);
												?>
									<div>
										<p class="wcmlim-storeshrttitle"><?php echo $location['location_name']; ?></p>
										<p style="margin-bottom: 0;">
											<?php echo $formatted_address; ?>
										</p>
									</div>
								</div>
							<?php
							}
							?>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
	?>

	<script>
		let openPopupBtn = document.getElementById('wcmlim-storeshrtsearchlocation_btn');
		let sidePopup = document.getElementById('wcmlim-storeshrtsidePopup');
		let closePopupBtn = document.getElementById('wcmlim-storeshrtclosePopupBtn');
		let modalOverlay = document.getElementById('wcmlim-storeshrtmodal');
		let view = jQuery('#wcmlim-storeshrtselected').attr('data-view');
		let popupmodal = document.getElementById("wcmlim-storeshrtpopupmodal");

		openPopupBtn.onclick = function() {
			if(view == 'drawer' || view == 'Drawer') {
				modalOverlay.classList.add('active');
				sidePopup.classList.add('active');
			} else if(view == 'popup' || view == 'Popup') {
				popupmodal.style.display = "block";
			}
		};

		if(jQuery('#wcmlim-storeshrtclosePopupBtn').length > 0) {
			closePopupBtn.onclick = function() {
				if(view == 'drawer' || view == 'Drawer') {
					sidePopup.classList.remove('active');
					modalOverlay.classList.remove('active');
				} else if(view == 'popup' || view == 'Popup') {
					popupmodal.style.display = "none";
				}
			};
		}
		
		window.onclick = function(event) {
			if(view == 'drawer' || view == 'Drawer') {
				if (event.target === modalOverlay) {
					sidePopup.classList.remove('active');
					modalOverlay.classList.remove('active');
				} 
			} else if(view == 'popup' || view == 'Popup') {
				if (event.target === popupmodal) {
					popupmodal.style.display = "none";
				}
			}
		};
	</script>

    <?php
    return ob_get_clean();
}

// Register the shortcode
add_shortcode('wcmlim_locations_storeview', 'wcmlim_locations_storeview_shortcode');

function wcmlim_load_font_awesome() {
    wp_enqueue_style( 'font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css' );
}
add_action( 'wp_enqueue_scripts', 'wcmlim_load_font_awesome' );

add_filter('wp_terms_checklist_args', 'disable_checkboxes_for_location_manager');

// Handle AJAX operations for settings
function wcmlim_settings_ajax_handler() {	

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

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

	// Ensure settings are present
    if ( empty( $_POST['settings'] ) ) {
        wp_send_json_error([
            'message' => 'No settings data received',
        ]);
    }
    
    // Track old values of settings that require page reload when changed
    $old_location_group_value = get_option('wcmlim_enable_location_group', '');
    $old_shop_manager_value = get_option('wcmlim_assign_location_shop_manager', '');
    $reload_required = false;

	// Add a 5-second delay before sending response	
	// Check if settings data exists in the POST request
	if (isset($_POST['settings'])) {
		// Get the settings from POST and decode the JSON string
		$settings = json_decode(stripslashes($_POST['settings']), true);
		// Optionally validate key against a whitelist
        $allowed_keys = array(
			"wcmlim_distance_calculator_by_coordinates", 
			"wcmlim_distance_calculator_by_cloudfare",   
			"wcmlim_enable_autodetect_location_by_maxmind",
			"wcmlim_enable_autodetect_location",
			"wcmlim_google_api_key",
			"wcmlim_enable_autodetect_location_with_ipinfo",
			"wcmlim_ipinfo_api_token",
			"wcmlim_enable_user_address_management",
			"wcmlim_google_maps_api_key_address",
			"wcmlim_clear_cart",
			"wcmlim_purchase_one_location",
			"wcmlim_geo_location",
			"wcmlim_suggestion_off",
			"wcmlim_hide_show_location_dropdown",
			"wcmlim_exclude_locations_from_frontend",
			"wcmlim_hide_out_of_stock_location",
			"wcmlim_restore_location_stock_for_failed",
			"wcmlim_restore_location_stock_for_refund",
			"wcmlim_set_location_cookie_time",
			"wcmlim_enable_default_location",
			"wcmlim_enable_userspecific_location",
			"wcmlim_enable_restrict_guestuser_location",
			"wcmlim_restrict_guest_user_location",
			"wcmlim_enable_location_group",
			"wcmlim_exclude_locations_group_frontend[]",
			"wcmlim_assign_location_shop_manager",
			"wcmlim_enable_filter_by_proximity",
			"wcmlim_enable_sorting_by_proximity",
			"wcmlim_location_priority_order",
			"wcmlim_enable_location_thresholds",
			"wcmlim_location_thresholds",
			// general settings tab keys
			"wcmlim_auto_billing_address",
			"wcmlim_pos_compatiblity",
			"wcmlim_pos_dynamic_pricing",
			"wcmlim_wc_pos_compatiblity",
			"wcmlim_enable_ctx_feed",
			// shop page settings tab keys
			"wcmlim_enable_location_onshop",
			"wcmlim_enable_location_onshop_variable",
			"wcmlim_enable_location_price_onshop",
			"wcmlim_hide_outofstock_products",
			// shipping and payment method tab keys
			"wcmlim_enable_shipping_zones",
			"wcmlim_enable_shipping_methods",
			"wcmlim_enable_split_packages",
			"wcmlim_assign_payment_methods_to_locations",
			"wcmlim_allow_tax_to_locations",
			"wcmlim_allow_local_pickup",
			// order fulfilment tab keys
			"wcmlim_allow_only_backend",
			"wcmlim_order_fulfilment_rules",
			"wcmlim_backend_display_stock",
			// notice messages tab keys
			"wcmlim_select_loc_val",
			"wcmlim_prod_instock_valid",
			"wcmlim_pickup_valid",
			"wcmlim_two_diff_loc_addtocart",
			"wcmlim_valid_cart_message",
			"wcmlim_btn_cartclear",
			"wcmlim_cart_popup_heading",
			"wcmlim_cart_popup_message",
			"wcmlim_purchase_change_location_text",
			"wcmlim_purchase_change_location_notavailtext",
			"wcmlim_var_message2",
			"wcmlim_var_message3",
			"wcmlim_var_message4",
			// shortcodes and documentation tab keys
			"wcmlim_view_location_finder_and_list_view",
			"wcmlim_show_location_distance",
			"wcmlim_show_in_popup[]",
			"wcmlim_show_in_popup",
			"wcmlim_listing_inline_location",
			"wcmlim_force_to_select_location",
			"wcmlim_txt_inline_location",
			"wcmlim_popup_icon_position",
			// header shortcode tab keys
			"wcmlim_show_street_in_shortcode",
			"wcmlim_show_route_in_shortcode",
			"wcmlim_show_city_in_shortcode",
			"wcmlim_show_state_in_shortcode",
			"wcmlim_show_postcode_in_shortcode",
			"wcmlim_show_country_in_shortcode",
			"wcmlim_header_shortcode_view",
		);

		// Loop through settings and save each option
		if (is_array($settings)) {
			foreach ($settings as $key => $value) {	
				
				if ( ! in_array( $key, $allowed_keys, true ) ) {
					continue;
				} else {
					// Check if option exists already
					$option_exists = get_option($key, null) !== null;
					
					if ($option_exists) {
						// Update existing option
						$updated = update_option($key, $value, false);
					} else {
						// Create new option
						$added = add_option($key, $value, false);
					}
					
					// Check if settings that require page reload have changed
					if ($key === 'wcmlim_enable_location_group') {
						$new_location_group_value = get_option('wcmlim_enable_location_group', '');
						if ($old_location_group_value !== $new_location_group_value) {
							$reload_required = true;
						}
					}
					
					// Check if location shop manager setting has changed
					if ($key === 'wcmlim_assign_location_shop_manager') {
						$new_shop_manager_value = get_option('wcmlim_assign_location_shop_manager', '');
						if ($old_shop_manager_value !== $new_shop_manager_value) {
							$reload_required = true;
						}
					}
					
					// Flush rewrite rules when CTX Feed setting is enabled
					if ($key === 'wcmlim_enable_ctx_feed' && $value === 'on') {
						// Schedule flush rewrite rules
						set_transient('wcmlim_flush_rewrite_rules', 1, 60);
					}
				}
				
			}
		}		

		
		// You can process the settings here if needed
		
		// Send back the decoded settings in the response with reload flag
		wp_send_json(array(
			'success' => true, 
			'message' => 'Settings received successfully',
			'settings' => $settings,
			'reload_required' => $reload_required
		));
	} else {
		wp_send_json(array(
			'success' => false,
			'message' => 'No settings data received'
		));
	}

	wp_die();

}

// Register AJAX actions
add_action('wp_ajax_wcmlim_settings_operations', 'wcmlim_settings_ajax_handler');


/**
 * Disables the Location linking option for users with the roles 
 * 'location_shop_manager' and 'location_regional_manager'.
 * These users can view the location but are restricted from editing it.
 */
function disable_checkboxes_for_location_manager($args) {
    $cuser = wp_get_current_user();
    $cuserRoles = !empty($cuser->roles) ? $cuser->roles : [];

	if (in_array('location_shop_manager', $cuserRoles) || in_array('location_regional_manager', $cuserRoles)) {
        // Enqueue JavaScript to make Location Linkingcheckboxes readonly
        add_action('admin_footer', function () {
            echo '<script type="text/javascript">
                document.addEventListener("DOMContentLoaded", function () {
                    const checkboxes = document.querySelectorAll("#taxonomy-locations input[type=\'checkbox\']");
                    checkboxes.forEach((checkbox) => {
                        checkbox.addEventListener("click", function(e) {
                            e.preventDefault(); // Prevent checkbox toggling
                        });
                        checkbox.style.pointerEvents = "none"; // Disable interaction
                        checkbox.style.opacity = "0.5"; // Optional: Visual cue
                    });
                });
            </script>';
        });
    }

    return $args;
}

function wcmlim_inline_admin_scripts($hook) {
    
    // Enqueue jQuery UI (sortable) and CSS
    wp_enqueue_script('jquery-ui-sortable');
    wp_enqueue_style('jquery-ui-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');

    // Inline JavaScript for drag-and-drop functionality
    echo '<script type="text/javascript">
    jQuery(document).ready(function($) {
        // Make the fields sortable
        $("#sortable-fields").sortable({
            update: function(event, ui) {
                var order = $(this).sortable("toArray");
                var sortedArray = [];
                $.each(order, function(index, value) {
                    sortedArray.push(value); // Save the order
                });

                // Update the input with the new order
                $("input[name=\'wcmlim_backend_display_feilds_settings[]\']").val(sortedArray);
            }
        });
    });
    </script>';

    // Inline CSS for the sortable fields
    echo '<style type="text/css">
    #sortable-fields {
        list-style-type: none;
        padding-left: 0;
    }

    .sortable-item {
        margin: 10px 0;
        padding: 10px;
        background-color: #f9f9f9;
        border: 1px solid #ddd;
        cursor: move;
    }

    .sortable-item input[type="checkbox"] {
        margin-right: 20px;
    }
    </style>';
}
add_action('admin_head', 'wcmlim_inline_admin_scripts');


add_action('wp_ajax_wcmlim_rulesget_products', 'wcmlim_rulesget_products_callback');

function wcmlim_rulesget_products_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

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

    $products = wc_get_products(array(
        'limit' => -1,
        'status' => 'publish',
        'return' => 'ids',
    ));

    $options = array();
    foreach ($products as $product_id) {
        $product = wc_get_product($product_id);
        $options[] = array(
            'id' => $product_id,
            'text' => $product->get_name(),
        );
    }

    wp_send_json($options);
}

add_action('wp_ajax_wcmlim_rulesget_categories', 'wcmlim_rulesget_categories_callback');

function wcmlim_rulesget_categories_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

	if(isset($_POST['security']) && !wp_verify_nonce($_POST['security'], 'wcmlim_settings_nonce')) {
		wp_send_json(array(
			'success' => false,
			'message' => 'Invalid nonce'
		));
		return;
	} 
	
    $terms = get_terms(array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
    ));

    $options = array();

    if (!is_wp_error($terms)) {
        foreach ($terms as $term) {
            $options[] = array(
                'id' => $term->term_id,
                'text' => $term->name,
            );
        }
    }

    wp_send_json($options);
}

add_action('wp_ajax_wcmlim_rulesget_tags', 'wcmlim_rulesget_tags_callback');

function wcmlim_rulesget_tags_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

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

    $tags = get_terms(array(
        'taxonomy' => 'product_tag',
        'hide_empty' => false,
    ));

    $options = array();

    if (!is_wp_error($tags)) {
        foreach ($tags as $tag) {
            $options[] = array(
                'id' => $tag->term_id,
                'text' => $tag->name,
            );
        }
    }

    wp_send_json($options);
}

add_action('wp_ajax_wcmlim_rulesget_attributes', 'wcmlim_rulesget_attributes_callback');

function wcmlim_rulesget_attributes_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

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

    $attribute_taxonomies = wc_get_attribute_taxonomies();
    $results = [];

    if ($attribute_taxonomies) {
        foreach ($attribute_taxonomies as $attribute) {
            $taxonomy = wc_attribute_taxonomy_name($attribute->attribute_name);
            $terms = get_terms(array(
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
            ));

            if (!is_wp_error($terms)) {
                foreach ($terms as $term) {
                    $results[] = array(
                        'id' => $taxonomy . ':' . $term->term_id,
                        'text' => $attribute->attribute_label . ' – ' . $term->name,
                    );
                }
            }
        }
    }

    wp_send_json($results);
}

add_action('wp_ajax_wcmlim_rulesget_brands', 'wcmlim_rulesget_brands_callback');

function wcmlim_rulesget_brands_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

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

    $terms = get_terms(array(
        'taxonomy' => 'product_brand',
        'hide_empty' => false,
    ));

    $options = array();

    if (!is_wp_error($terms)) {
        foreach ($terms as $term) {
            $options[] = array(
                'id' => $term->term_id,
                'text' => $term->name,
            );
        }
    }

    wp_send_json($options);
}

add_action('wp_ajax_save_wcmlim_rules', 'save_wcmlim_rules_callback');

function save_wcmlim_rules_callback() {

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

	check_ajax_referer('wcmlim_settings_nonce', 'security');

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

    $rules_json = stripslashes($_POST['rules']);
    $rules_array = json_decode($rules_json, true);

    update_option('wcmlim_saved_rules', $rules_array);
    update_option('wcmlim_enable_rules', $_POST['enable_rules']);

    wp_send_json_success('Rules saved');
}


/**
   * Check if MultiLoca Premium plugin is active
   *
   * @since     4.2.9
   * @return    bool    True if MultiLoca Premium is active, false otherwise.
   */
  function is_multiloca_premium_active() {
    if (!function_exists('is_plugin_active')) {
      include_once(ABSPATH . 'wp-admin/includes/plugin.php');
    }
    
    // Check if MultLoca Premium is active
    $active_plugins = get_option('active_plugins', array());
    foreach ($active_plugins as $plugin_path) {
      if (strpos($plugin_path, 'multiloca-premium') !== false) {
        return true;
      }
    }
    
    // Also check for the specific plugin class
    return class_exists('Multiloca_Premium_Plugin');
  }

// AJAX handler to get user data for editing
add_action('wp_ajax_wcmlim_get_user_data', 'wcmlim_get_user_data_handler');
function wcmlim_get_user_data_handler() {
    // Security check
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized access'], 403);
        return;
    }

    check_ajax_referer('wcmlim_user_management_nonce', 'security');

    $user_id = intval($_POST['user_id']);
    
    if (!$user_id) {
        wp_send_json_error(['message' => 'Invalid user ID']);
        return;
    }

    $user = get_user_by('id', $user_id);
    
    if (!$user) {
        wp_send_json_error(['message' => 'User not found']);
        return;
    }

    // Get user meta
    $first_name = get_user_meta($user_id, 'first_name', true);
    $last_name = get_user_meta($user_id, 'last_name', true);

    // Debug: Log retrieved data (remove in production)
    error_log("WCMLIM Get User Data - Retrieved: first_name='" . $first_name . "', last_name='" . $last_name . "'");

    $user_data = [
        'ID' => $user->ID,
        'user_email' => $user->user_email,
        'display_name' => $user->display_name,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'roles' => $user->roles
    ];

    // Debug: Log full user data being sent (remove in production)
    error_log("WCMLIM Get User Data - Sending: " . json_encode($user_data));

    wp_send_json_success($user_data);
}

// AJAX handler to update user data
add_action('wp_ajax_wcmlim_update_user_data', 'wcmlim_update_user_data_handler');
function wcmlim_update_user_data_handler() {
    // Security check
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized access'], 403);
        return;
    }

    check_ajax_referer('wcmlim_user_management_nonce', 'security');

    // Get and sanitize input data
    $user_id = intval($_POST['user_id']);
    $first_name = sanitize_text_field($_POST['first_name']);
    $last_name = sanitize_text_field($_POST['last_name']);
    $user_email = sanitize_email($_POST['user_email']);
    $display_name = sanitize_text_field($_POST['display_name']);
    $new_role = sanitize_text_field($_POST['user_role_select']);
    $old_role = sanitize_text_field($_POST['old_role']);

    // Debug: Log received data (remove in production)
    error_log("WCMLIM User Update - Received data: " . json_encode([
        'user_id' => $user_id,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'user_email' => $user_email,
        'display_name' => $display_name,
        'new_role' => $new_role,
        'old_role' => $old_role
    ]));

    if (!$user_id) {
        wp_send_json_error(['message' => 'Invalid user ID']);
        return;
    }

    $user = get_user_by('id', $user_id);
    if (!$user) {
        wp_send_json_error(['message' => 'User not found']);
        return;
    }

    // Validate email
    if (!is_email($user_email)) {
        wp_send_json_error(['message' => 'Invalid email address']);
        return;
    }

    // Check if email is unique (exclude current user)
    if (email_exists($user_email) && email_exists($user_email) !== $user_id) {
        wp_send_json_error(['message' => 'Email address already exists']);
        return;
    }

    // Validate required fields
    if (empty($first_name) || empty($last_name) || empty($user_email)) {
        wp_send_json_error(['message' => 'First name, last name, and email are required']);
        return;
    }

    // Validate role
    if (!in_array($new_role, ['location_shop_manager', 'location_regional_manager'])) {
        wp_send_json_error(['message' => 'Invalid user role']);
        return;
    }

    // Always generate display name from first name and last name
    $display_name = trim($first_name . ' ' . $last_name);
    
    // If user provided a custom display name, we'll still use the generated one
    // to maintain consistency (first name + last name format)

    // First update the main user fields (email and display name)
    $user_data = [
        'ID' => $user_id,
        'user_email' => $user_email,
        'display_name' => $display_name
    ];

    $result = wp_update_user($user_data);

    if (is_wp_error($result)) {
        error_log("WCMLIM User Update - wp_update_user failed: " . $result->get_error_message());
        wp_send_json_error(['message' => 'Failed to update user: ' . $result->get_error_message()]);
        return;
    }

    // Update user meta fields explicitly
    $first_name_result = update_user_meta($user_id, 'first_name', $first_name);
    $last_name_result = update_user_meta($user_id, 'last_name', $last_name);

    // Debug: Check if meta update returned false (indicating no change) or true/meta_id (indicating success)
    error_log("WCMLIM User Update - Meta update results: first_name=" . 
              ($first_name_result === false ? 'FAILED' : 'SUCCESS') . 
              ", last_name=" . ($last_name_result === false ? 'FAILED' : 'SUCCESS'));

    // Force refresh user data from database
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_id, 'user_meta');
    clean_user_cache($user_id);

    // Verify the data was actually saved by reading it back
    $verification_first_name = get_user_meta($user_id, 'first_name', true);
    $verification_last_name = get_user_meta($user_id, 'last_name', true);
    
    error_log("WCMLIM User Update - Post-save verification: " . 
              "first_name='" . $verification_first_name . "' (expected: '" . $first_name . "'), " .
              "last_name='" . $verification_last_name . "' (expected: '" . $last_name . "')");

    // If verification fails, try alternative method
    if ($verification_first_name !== $first_name || $verification_last_name !== $last_name) {
        error_log("WCMLIM User Update - Verification failed, trying alternative method");
        
        // Try direct database update as fallback
        global $wpdb;
        
        $first_name_db_result = $wpdb->replace(
            $wpdb->usermeta,
            [
                'user_id' => $user_id,
                'meta_key' => 'first_name',
                'meta_value' => $first_name
            ]
        );
        
        $last_name_db_result = $wpdb->replace(
            $wpdb->usermeta,
            [
                'user_id' => $user_id,
                'meta_key' => 'last_name',
                'meta_value' => $last_name
            ]
        );
        
        error_log("WCMLIM User Update - Direct DB update results: first_name=" . 
                  ($first_name_db_result !== false ? 'SUCCESS' : 'FAILED') . 
                  ", last_name=" . ($last_name_db_result !== false ? 'SUCCESS' : 'FAILED'));
        
        // Clear cache again after direct DB update
        wp_cache_delete($user_id, 'users');
        wp_cache_delete($user_id, 'user_meta');
        clean_user_cache($user_id);
    }

    // Update user role if changed
    if ($new_role !== $old_role) {
        $user = new WP_User($user_id);
        $user->remove_role($old_role);
        $user->add_role($new_role);
    }

    // Handle location assignments
    $assignment_message = '';
    if (isset($_POST['location_assignments'])) {
        $new_assignments = json_decode(stripslashes($_POST['location_assignments']), true);
        $assignment_result = wcmlim_update_user_assignments($user_id, $new_role, $old_role, $new_assignments);
        $assignment_message = $assignment_result['message'];
    }

    $success_message = 'User updated successfully!';
    if (!empty($assignment_message)) {
        $success_message .= ' ' . $assignment_message;
    }

    wp_send_json_success([
        'message' => $success_message,
        'user_data' => [
            'ID' => $user_id,
            'first_name' => $first_name,
            'last_name' => $last_name,
            'user_email' => $user_email,
            'display_name' => $display_name,
            'role' => $new_role
        ]
    ]);
}

// AJAX handler to remove user assignments
add_action('wp_ajax_wcmlim_remove_user_assignments', 'wcmlim_remove_user_assignments_handler');
function wcmlim_remove_user_assignments_handler() {
    // Security check
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized access'], 403);
        return;
    }

    check_ajax_referer('wcmlim_user_management_nonce', 'security');

    $user_id = intval($_POST['user_id']);
    $user_role = sanitize_text_field($_POST['user_role']);

    if (!$user_id) {
        wp_send_json_error(['message' => 'Invalid user ID']);
        return;
    }

    $user = get_user_by('id', $user_id);
    if (!$user) {
        wp_send_json_error(['message' => 'User not found']);
        return;
    }

    $removed_assignments = [];

    if ($user_role === 'location_shop_manager') {
        // Remove from individual locations
        $locations = get_terms(['taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0]);
        
        foreach ($locations as $location) {
            $shop_managers = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
            
            if (is_array($shop_managers)) {
                $key = array_search($user_id, $shop_managers);
                if ($key !== false) {
                    unset($shop_managers[$key]);
                    $shop_managers = array_values($shop_managers); // Reindex array
                    update_term_meta($location->term_id, 'wcmlim_shop_manager', $shop_managers);
                    $removed_assignments[] = $location->name;
                }
            } elseif ($shop_managers == $user_id) {
                delete_term_meta($location->term_id, 'wcmlim_shop_manager');
                $removed_assignments[] = $location->name;
            }
        }
    } elseif ($user_role === 'location_regional_manager') {
        // Remove from location groups
        $location_groups = get_terms(['taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0]);
        
        foreach ($location_groups as $group) {
            $regional_managers = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
            
            if (is_array($regional_managers)) {
                $key = array_search($user_id, $regional_managers);
                if ($key !== false) {
                    unset($regional_managers[$key]);
                    $regional_managers = array_values($regional_managers); // Reindex array
                    update_term_meta($group->term_id, 'wcmlim_shop_regmanager', $regional_managers);
                    $removed_assignments[] = $group->name;
                }
            } elseif ($regional_managers == $user_id) {
                delete_term_meta($group->term_id, 'wcmlim_shop_regmanager');
                $removed_assignments[] = $group->name;
            }
        }
    }

    // Remove the role from user
    $wp_user = new WP_User($user_id);
    $wp_user->remove_role($user_role);

	wp_delete_user($user_id);

    $message = 'User assignments removed successfully.';
    if (!empty($removed_assignments)) {
        $message .= ' Removed from: ' . implode(', ', $removed_assignments);
    }

    wp_send_json_success([
        'message' => $message,
        'removed_assignments' => $removed_assignments
    ]);
}

// AJAX handler to get location assignments
add_action('wp_ajax_wcmlim_get_location_assignments', 'wcmlim_get_location_assignments_handler');
function wcmlim_get_location_assignments_handler() {
    
    $user_id = intval($_POST['user_id']);
    $user_role = sanitize_text_field($_POST['user_role']);

    // Allow user_id = 0 for new users (just getting available locations)
    if (!$user_role) {
        wp_send_json_error(['message' => 'User role is required']);
        return;
    }

    $available = [];
    $assigned = [];

    if ($user_role === 'location_shop_manager') {
        // Get all locations and current assignments for shop manager
        $locations = get_terms([
            'taxonomy' => 'locations', 
            'hide_empty' => false, 
            'parent' => 0
        ]);
        
        foreach ($locations as $location) {
            $available[] = [
                'id' => $location->term_id,
                'name' => $location->name
            ];
            
            // Check if user is assigned to this location (only if user_id > 0)
            if ($user_id > 0) {
                $shop_managers = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
                if (is_array($shop_managers) && in_array($user_id, $shop_managers)) {
                    $assigned[] = (string)$location->term_id;
                } elseif ($shop_managers == $user_id) {
                    $assigned[] = (string)$location->term_id;
                }
            }
        }
        
    } elseif ($user_role === 'location_regional_manager') {
        // Get all location groups and current assignments for regional manager
        $location_groups = get_terms([
            'taxonomy' => 'location_group', 
            'hide_empty' => false, 
            'parent' => 0
        ]);
        
        foreach ($location_groups as $group) {
            $available[] = [
                'id' => $group->term_id,
                'name' => $group->name
            ];
            
            // Check if user is assigned to this group (only if user_id > 0)
            if ($user_id > 0) {
                $regional_managers = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
                if (is_array($regional_managers) && in_array($user_id, $regional_managers)) {
                    $assigned[] = (string)$group->term_id;
                } elseif ($regional_managers == $user_id) {
                    $assigned[] = (string)$group->term_id;
                }
            }
        }
    } else {
        wp_send_json_error(['message' => 'Invalid user role']);
        return;
    }

    wp_send_json_success([
        'available' => $available,
        'assigned' => $assigned
    ]);
}

// Function to update user location assignments
function wcmlim_update_user_assignments($user_id, $new_role, $old_role, $new_assignments) {
    $assigned_items = [];
    $removed_items = [];
    
    // Ensure new_assignments is always an array
    if (!is_array($new_assignments)) {
        if (is_string($new_assignments) && !empty($new_assignments)) {
            // Handle comma-separated string
            $new_assignments = array_map('trim', explode(',', $new_assignments));
            $new_assignments = array_filter($new_assignments); // Remove empty values
        } else {
            $new_assignments = [];
        }
    }
    
    // Debug: Log what we're working with
    error_log("WCMLIM Update Assignments - User ID: $user_id, New Role: $new_role, Old Role: $old_role, Assignments: " . json_encode($new_assignments));
    
    // Remove user from old role assignments first
    if ($new_role !== $old_role) {
        if ($old_role === 'location_shop_manager') {
            // Remove from all locations
            $locations = get_terms(['taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0]);
            foreach ($locations as $location) {
                $shop_managers = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
                if (is_array($shop_managers)) {
                    $key = array_search($user_id, $shop_managers);
                    if ($key !== false) {
                        unset($shop_managers[$key]);
                        $shop_managers = array_values($shop_managers);
                        update_term_meta($location->term_id, 'wcmlim_shop_manager', $shop_managers);
                    }
                } elseif ($shop_managers == $user_id) {
                    delete_term_meta($location->term_id, 'wcmlim_shop_manager');
                }
            }
        } elseif ($old_role === 'location_regional_manager') {
            // Remove from all location groups
            $location_groups = get_terms(['taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0]);
            foreach ($location_groups as $group) {
                $regional_managers = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
                if (is_array($regional_managers)) {
                    $key = array_search($user_id, $regional_managers);
                    if ($key !== false) {
                        unset($regional_managers[$key]);
                        $regional_managers = array_values($regional_managers);
                        update_term_meta($group->term_id, 'wcmlim_shop_regmanager', $regional_managers);
                    }
                } elseif ($regional_managers == $user_id) {
                    delete_term_meta($group->term_id, 'wcmlim_shop_regmanager');
                }
            }
        }
    }
    
    // Apply new assignments for current role
    if ($new_role === 'location_shop_manager') {
        // Get all locations to process assignments and removals
        $locations = get_terms(['taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0]);
        
        foreach ($locations as $location) {
            $location_id = (string)$location->term_id;
            $shop_managers = get_term_meta($location->term_id, 'wcmlim_shop_manager', true);
            $current_managers = is_array($shop_managers) ? $shop_managers : ($shop_managers ? [$shop_managers] : []);
            $is_currently_assigned = in_array($user_id, $current_managers);
            $should_be_assigned = in_array($location_id, $new_assignments);
            
            if ($should_be_assigned && !$is_currently_assigned) {
                // Add user to location
                $current_managers[] = $user_id;
                update_term_meta($location->term_id, 'wcmlim_shop_manager', $current_managers);
                $assigned_items[] = $location->name;
                
            } elseif (!$should_be_assigned && $is_currently_assigned) {
                // Remove user from location
                $key = array_search($user_id, $current_managers);
                if ($key !== false) {
                    unset($current_managers[$key]);
                    $current_managers = array_values($current_managers);
                    if (empty($current_managers)) {
                        delete_term_meta($location->term_id, 'wcmlim_shop_manager');
                    } else {
                        update_term_meta($location->term_id, 'wcmlim_shop_manager', $current_managers);
                    }
                    $removed_items[] = $location->name;
                }
            }
        }
        
    } elseif ($new_role === 'location_regional_manager') {
        // Get all location groups to process assignments and removals
        $location_groups = get_terms(['taxonomy' => 'location_group', 'hide_empty' => false, 'parent' => 0]);
        
        foreach ($location_groups as $group) {
            $group_id = (string)$group->term_id;
            $regional_managers = get_term_meta($group->term_id, 'wcmlim_shop_regmanager', true);
            $current_managers = is_array($regional_managers) ? $regional_managers : ($regional_managers ? [$regional_managers] : []);
            $is_currently_assigned = in_array($user_id, $current_managers);
            $should_be_assigned = in_array($group_id, $new_assignments);
            
            if ($should_be_assigned && !$is_currently_assigned) {
                // Add user to group
                $current_managers[] = $user_id;
                update_term_meta($group->term_id, 'wcmlim_shop_regmanager', $current_managers);
                $assigned_items[] = $group->name;
                
            } elseif (!$should_be_assigned && $is_currently_assigned) {
                // Remove user from group
                $key = array_search($user_id, $current_managers);
                if ($key !== false) {
                    unset($current_managers[$key]);
                    $current_managers = array_values($current_managers);
                    if (empty($current_managers)) {
                        delete_term_meta($group->term_id, 'wcmlim_shop_regmanager');
                    } else {
                        update_term_meta($group->term_id, 'wcmlim_shop_regmanager', $current_managers);
                    }
                    $removed_items[] = $group->name;
                }
            }
        }
    }
    
    // Build result message
    $messages = [];
    if (!empty($assigned_items)) {
        $item_type = $new_role === 'location_shop_manager' ? 'locations' : 'groups';
        $messages[] = 'Assigned to: ' . implode(', ', $assigned_items);
    }
    if (!empty($removed_items)) {
        $item_type = $new_role === 'location_shop_manager' ? 'locations' : 'groups';
        $messages[] = 'Removed from: ' . implode(', ', $removed_items);
    }
    
    return [
        'success' => true,
        'message' => !empty($messages) ? implode('. ', $messages) . '.' : 'No assignment changes made.',
        'assigned' => $assigned_items,
        'removed' => $removed_items
    ];
}

// AJAX handler to create new user
add_action('wp_ajax_wcmlim_create_user', 'wcmlim_create_user_handler');
function wcmlim_create_user_handler() {

    // Get and sanitize input data
    $username = sanitize_text_field($_POST['username']);
    $user_email = sanitize_email($_POST['user_email']);
    $first_name = sanitize_text_field($_POST['first_name']);
    $last_name = sanitize_text_field($_POST['last_name']);
    $user_password = $_POST['user_password']; // Don't sanitize password
    $user_role = sanitize_text_field($_POST['user_role']);
    
    // Handle locations - can be array from FormData
    $locations = $_POST['locations'];
    
    // Debug: Log received locations
    error_log("WCMLIM Create User - Received locations: " . json_encode($_POST['locations'] ?? 'not set'));

    // Validate required fields
    if (empty($username) || empty($user_email) || empty($first_name) || empty($last_name) || empty($user_password) || empty($user_role)) {
        wp_send_json_error('All required fields must be filled');
        return;
    }

    // Validate email
    if (!is_email($user_email)) {
        wp_send_json_error('Invalid email address');
        return;
    }

    // Check if username already exists
    if (username_exists($username)) {
        wp_send_json_error('Username already exists');
        return;
    }

    // Check if email already exists
    if (email_exists($user_email)) {
        wp_send_json_error('Email address already exists');
        return;
    }

    // Validate user role
    if (!in_array($user_role, ['location_shop_manager', 'location_regional_manager'])) {
        wp_send_json_error('Invalid user role');
        return;
    }

    // Validate password length
    if (strlen($user_password) < 6) {
        wp_send_json_error('Password must be at least 6 characters long');
        return;
    }

    // Create the user
    $userdata = [
        'user_login' => $username,
        'user_email' => $user_email,
        'user_pass' => $user_password,
        'first_name' => $first_name,
        'last_name' => $last_name,
        'display_name' => $first_name . ' ' . $last_name,
        'role' => $user_role
    ];

    $user_id = wp_insert_user($userdata);

    if (is_wp_error($user_id)) {
        wp_send_json_error('Error creating user: ' . $user_id->get_error_message());
        return;
    }

    // Assign locations if provided
    if (!empty($locations)) {
        $assignment_result = wcmlim_update_user_assignments($user_id, $user_role, '', $locations);
        
        if (!$assignment_result['success']) {
            // User was created but assignment failed - log the error but don't fail the request
            error_log("WCMLIM: Failed to assign locations to new user $user_id: " . $assignment_result['message']);
        }
    }

    // Log the successful creation
    error_log("WCMLIM: New user created - ID: $user_id, Username: $username, Role: $user_role");

    wp_send_json_success([
        'user_id' => $user_id,
        'username' => $username,
        'message' => 'User created successfully'
    ]);
}
