<?php
if (!defined('ABSPATH')) {
    exit;
}

add_action('rest_api_init', function () {
    register_rest_route('kaz/v1', '/live-prices', array(
        'methods' => 'GET',
        'callback' => 'kaz_live_prices_endpoint',
        'permission_callback' => '__return_true',
        'args' => array(
            'ids' => array(
                'required' => false,
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
            ),
            'tag' => array(
                'required' => false,
                'type' => 'string',
                'sanitize_callback' => 'sanitize_text_field',
            ),
        ),
    ));
});

function kaz_live_prices_endpoint($request)
{
    $ids_param = $request->get_param('ids');
    $tag_param = $request->get_param('tag');

    $response = [];

    // Existing logic for IDs
    if (!empty($ids_param)) {
        $ids = array_filter(array_map('intval', explode(',', $ids_param)));
        foreach ($ids as $id) {
            $product = wc_get_product($id);
            if ($product) {
                $response[$id] = $product->get_price_html();
            }
        }
    }

    // New logic for tag (e.g. chart-ref-1g or SKU like AHG001)
    if (!empty($tag_param)) {
        // Split by comma in case multiple tags are sent at once
        $tags = array_filter(array_map('trim', explode(',', $tag_param)));

        foreach ($tags as $single_tag) {
            $lowest_price_html = null;

            // 1. Try to find product by SKU first
            $product_id_by_sku = wc_get_product_id_by_sku($single_tag);
            if ($product_id_by_sku) {
                $product = wc_get_product($product_id_by_sku);
                if ($product) {
                    $lowest_price_html = $product->get_price_html();
                }
            }

            // 2. If not found by SKU, treat it as a product_tag (chart-ref-...)
            if (!$lowest_price_html) {
                $args = array(
                    'post_type' => 'product',
                    'post_status' => 'publish',
                    'posts_per_page' => -1,
                    'product_tag' => $single_tag,
                    'meta_query' => array(
                        array(
                            'key' => '_stock_status',
                            'value' => 'instock',
                            'compare' => '='
                        )
                    )
                );

                $query = new WP_Query($args);
                $lowest_price = null;

                if ($query->have_posts()) {
                    foreach ($query->posts as $post) {
                        $product = wc_get_product($post->ID);
                        if ($product) {
                            $price = (float) $product->get_price();
                            if ($lowest_price === null || $price < $lowest_price) {
                                $lowest_price = $price;
                                $lowest_price_html = $product->get_price_html();
                            }
                        }
                    }
                }
            }

            if ($lowest_price_html) {
                $response['tag_' . $single_tag] = $lowest_price_html;
            }
        }
    }

    return rest_ensure_response($response);
}

// Bypass LiteSpeed Cache for custom REST endpoints
add_filter('litespeed_cache_api_bypass', 'kaz_litespeed_bypass_api', 10, 1);
function kaz_litespeed_bypass_api($bypass)
{
    if (isset($_SERVER['REQUEST_URI'])) {
        if (
            strpos($_SERVER['REQUEST_URI'], '/kaz/v1/live-prices') !== false ||
            strpos($_SERVER['REQUEST_URI'], '/kaz/v1/chart-data') !== false ||
            strpos($_SERVER['REQUEST_URI'], '/kaz/v1/cron-sync') !== false
        ) {
            return true;
        }
    }
    return $bypass;
}
