<?php

add_filter('manage_edit-locations_columns', 'wcmlim_add_location_coumns', 10, 1);

add_action('manage_locations_custom_column', 'wcmlim_product_location_column_content', 10, 3);


function wcmlim_add_location_coumns(array $columns): array
{
    $columns['product_count'] = __('Linked Products');
    $columns['product_stock_status'] = __('Product Count (In Stock)');
    return $columns;
}



function wcmlim_product_location_column_content(string $content, string $column_name, int $term_id): void
{
    switch ($column_name) {

        case 'product_count':

    $product_count = get_product_count_by_taxonomy_term('locations', $term_id);

    $term_object = get_term($term_id);
    $term_slug = $term_object->slug;

    $site_url = get_option('siteurl');

    $url = $site_url . '/wp-admin/edit.php?product_locations=' . $term_slug . '&post_type=product';

    // Skip if term or field does not exist
    if (!$product_count) {
        return;
    }

    echo "<a href='" . $url . "'>" . $product_count . "</a>";

    break;

    case 'product_stock_status':

        $product_count = wcmlim_get_location_wise_instock_product_count($term_id);
    
        $term_object = get_term($term_id);
        $term_slug = $term_object->slug;
    
        $site_url = get_option('siteurl');
    
        $url = $site_url . '/wp-admin/edit.php?product_locations=' . $term_slug . '&post_type=product&product_stock_status=instock';
    
        // Skip if term or field does not exist
        if (!$product_count) {
            return;
        }
    
        echo "<a href='" . $url . "'>" . $product_count . "</a>";
    
        break;

}
}


function wcmlim_get_location_wise_instock_product_count($term_id){

    global $wpdb;

    $term_id = absint($term_id); 


    $product_ids = wcmlim_get_total_product_ids();

    $formatted_product_ids = implode(',', $product_ids);

    $SQL = $wpdb->prepare(
        "
        SELECT COUNT(*) as total 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = %s 
        AND meta_value = %s 
        AND post_id IN ($formatted_product_ids)
        ",
        'wcmlim_product_availability_at_' . $term_id,
        'yes'
    );
    $results = $wpdb->get_results($SQL);

    return $results[0]->total;



}

function wcmlim_get_total_product_ids(){

    global $wpdb;

    $SQL = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_type IN ('product', 'product_variation') AND post_status = %s", 'publish');

   foreach($wpdb->get_results($SQL) as $product){

    $product_ids[] = $product->ID;

   }

    return $product_ids;

}




add_action('after-locations-table', 'sync_location_count_button');

function sync_location_count_button($taxonomy) {

    if (get_option('wcmlim_sync_location_count_has_run') !== false) {
        return; 
    }

    ?>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="sync_location_count">
        <?php wp_nonce_field('sync_location_count_action', 'sync_location_count_nonce'); ?>
        <input type="submit" class="sync-location-count button-primary" value="Sync All Locations" />
    </form>
    <?php
}

add_action('admin_post_sync_location_count', 'handle_sync_location_count');

function handle_sync_location_count() {
    // Verify nonce and ensure the user has permission
    if (!isset($_POST['sync_location_count_nonce']) || 
        !wp_verify_nonce($_POST['sync_location_count_nonce'], 'sync_location_count_action') || 
        !current_user_can('manage_options')) {
        wp_die(__('You are not allowed to perform this action.', 'textdomain'));
    }

    // Run the sync function
    sync_location_count();

    // Redirect back to the Locations page with a success message
    $redirect_url = add_query_arg('sync_location_count_success', '1', wp_get_referer());
    wp_safe_redirect($redirect_url);
    exit;
}

add_action('admin_notices', 'sync_location_count_success_notice');

function sync_location_count_success_notice() {
    if (isset($_GET['sync_location_count_success'])) {
        echo '<div class="notice notice-success is-dismissible"><p>Location successfully relinked to products.</p></div>';
    }
}
  



function wcmlim_check_stock_meta_key($product_id, $meta_key)
{

    global $wpdb;

    $check_stock_key = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta where post_id = %d AND meta_key = %s", $product_id, $meta_key);

    $results = $wpdb->get_results($check_stock_key);

    if (empty($results)) {
        update_post_meta($product_id, $meta_key, '0');

    }
}

function wcmlim_apply_product_location_filter($query)
{

    global $pagenow;

    // Ensure it is an edit.php admin page, the filter exists and has a value, and that it's the products page
    if ($query->is_admin && $pagenow == 'edit.php' && isset($_GET['product_locations']) && $_GET['product_locations'] != '' && $_GET['post_type'] == 'product') {

        $term_slug = $_GET['product_locations'];



        $term_object = get_term_by('slug', $term_slug, 'locations');
        $term_id = $term_object->term_id;

        $meta_key = 'wcmlim_stock_at_' . $term_id;



        $tax_query = array(

           

           
            array(
                'taxonomy'  => 'locations',
                'field'     => 'term_id',
                'terms'     => array($term_id),
            )



        );
        $query->set('tax_query', $tax_query);

    }

}

add_action('pre_get_posts', 'wcmlim_apply_product_location_filter');

function get_product_count_by_taxonomy_term($taxonomy, $term_id) {
    // Ensure the taxonomy and term ID are valid
    if (empty($taxonomy) || empty($term_id)) {
        return 0;
    }

    // Use WP_Query to count products associated with the taxonomy term
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => -1, // Retrieve all products
        'tax_query'      => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'term_id',
                'terms'    => $term_id,
            ),
        ),
        'fields' => 'ids', // Only retrieve post IDs to improve performance
    );

    $query = new WP_Query($args);
    
    // Return the count of found products
    return $query->found_posts;
}


add_filter('request', 'wcmlim_filter_products_by_location_status');
function wcmlim_filter_products_by_location_status($query_vars) {
    global $typenow;
    if ($typenow == 'product' && isset($_GET['product_stock_status']) && $_GET['product_stock_status'] != '') {
        $location_name = $_GET['product_locations'];

        $location = get_term_by('slug', $location_name, 'locations'); 
    
    if ( $location && ! is_wp_error( $location ) ) {

        $location_id = $location->term_id;
        
    }

    $meta_key = 'wcmlim_product_availability_at_' . $location_id;

        $meta_query = isset($query_vars['meta_query']) ? $query_vars['meta_query'] : [];
        $stock_status = $_GET['product_stock_status'];

        if($stock_status == 'instock'){
            
            $compare_value = '=';
        }else if($stock_status == 'outofstock'){
            $compare_value = '!=';
        }

        $meta_query[] = [
            'key' => $meta_key,
            'value' => 'yes',
            'compare' => $compare_value
        ];

        $query_vars['meta_query'] = $meta_query;
    }
    return $query_vars;
}









?>