<?php

function wcmlim_run_sync_location_count_once() {
    // Check if the function has already been run
    if (get_option('wcmlim_sync_location_count_has_run') !== false) {
        return; // Stop if the function has already run
    }

    // Run the sync_location_count function
    sync_location_count();
}

function sync_location_count() {
    if (!is_admin()) {
        return; // Stop if not in the admin area
    }

    global $wpdb;

    // Get all products and product variations in one go
    $products_sql = $wpdb->prepare(
        "SELECT ID, post_type, post_parent FROM {$wpdb->posts} WHERE post_type IN (%s, %s) AND post_status = %s",
        'product',
        'product_variation',
        'publish'
    );
    $products = $wpdb->get_results($products_sql);
    
    if (empty($products)) {
        update_option('wcmlim_sync_location_count_has_run', true);
        return;
    }

    // Get all locations once
    $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false));
    $location_ids = wp_list_pluck($locations, 'term_id');

    // Organize products by type for batch processing
    $simple_products = array();
    $variation_products = array();
    $parent_ids = array();
    
    foreach ($products as $product) {
        if ($product->post_type === 'product_variation') {
            $variation_products[$product->ID] = $product->post_parent;
            $parent_ids[$product->post_parent] = $product->post_parent;
        } else {
            $simple_products[] = $product->ID;
        }
        
        // Assign the locations to the product - keep this per product as it's a taxonomy operation
        wp_set_object_terms($product->ID, $location_ids, 'locations', true);
    }
    
    // Process simple products
    if (!empty($simple_products)) {
        foreach ($simple_products as $product_id) {
            $availability_meta = array();
            
            foreach ($location_ids as $location_id) {
                $location_stock_qty_key = 'wcmlim_stock_at_' . $location_id;
                $stock = (int) get_post_meta($product_id, $location_stock_qty_key, true);
                
                // Update availability to "yes" if stock is available at this location
                if ($stock > 0) {
                    update_post_meta($product_id, 'wcmlim_product_availability_at_' . $location_id, 'yes');
                }
            }
        }
    }
    
    // Process variable products
    if (!empty($parent_ids)) {
        // Get all variation stock data in a single query
        $variation_meta_keys = array();
        foreach ($location_ids as $location_id) {
            $variation_meta_keys[] = 'wcmlim_stock_at_' . $location_id;
        }
        
        $placeholders = implode(',', array_fill(0, count($variation_products), '%d'));
        $meta_key_placeholders = implode(',', array_fill(0, count($variation_meta_keys), '%s'));
        
        $variation_stock_query = $wpdb->prepare(
            "SELECT post_id, meta_key, meta_value FROM {$wpdb->postmeta} 
             WHERE post_id IN ($placeholders) AND meta_key IN ($meta_key_placeholders)",
            array_merge(array_keys($variation_products), $variation_meta_keys)
        );
        $variation_stocks = $wpdb->get_results($variation_stock_query);
        
        // Organize stock data by parent product and location
        $parent_location_totals = array();
        
        foreach ($variation_stocks as $stock_data) {
            $variation_id = $stock_data->post_id;
            $parent_id = $variation_products[$variation_id];
            $meta_key = $stock_data->meta_key;
            $stock_qty = (int)$stock_data->meta_value;
            
            if (preg_match('/wcmlim_stock_at_(\d+)/', $meta_key, $matches)) {
                $location_id = $matches[1];
                
                if (!isset($parent_location_totals[$parent_id][$location_id])) {
                    $parent_location_totals[$parent_id][$location_id] = 0;
                }
                
                $parent_location_totals[$parent_id][$location_id] += $stock_qty;
            }
        }
        
        // Update parent product availability based on total stock
        foreach ($parent_location_totals as $parent_id => $location_totals) {
            foreach ($location_totals as $location_id => $total_stock) {
                if ($total_stock > 0) {
                    update_post_meta($parent_id, 'wcmlim_product_availability_at_' . $location_id, 'yes');
                }
            }
        }
    }

    update_option('wcmlim_sync_location_count_has_run', true);
}
?>