<?php

add_action('woocommerce_product_import_inserted_product_object', function($product) {
    $product_id = $product->get_id();

    // Retrieve all meta data for the product
    $meta_data = get_post_meta($product_id);

    // Loop through meta data to check for specific meta keys
    foreach ($meta_data as $meta_key => $meta_values) {
        // Match meta keys in the format 'wcmlim_stock_at_{taxonomy_id}'
        if (preg_match('/^wcmlim_stock_at_(\d+)$/', $meta_key, $matches)) {
            $taxonomy_id = $matches[1]; // Extract the taxonomy ID (e.g., 29)

            // Get the meta value
            $meta_value = $meta_values[0] ?? '';

            // Get the taxonomy term associated with the ID
            $taxonomy_name = 'locations'; // Replace with the actual taxonomy name
            $term = get_term_by('id', $taxonomy_id, $taxonomy_name);

            if ($term) {
                if (!empty($meta_value) && intval($meta_value) > 0) {
                    // Meta value is positive, link the product to the taxonomy term
                    wp_set_object_terms($product_id, (int) $taxonomy_id, $taxonomy_name, true);
                } else {
                   
                    // Do nothing if the meta value is zero or empty
                }
            } else {
            }
        }
    }
});
