<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Register a custom REST API endpoint at /wp-json/dsas/v1/items
function doosearchas_search_rest(){
    register_rest_route('dsas/v1','items', array(
        'methods' => WP_REST_SERVER::READABLE,
        'callback' => 'doosearchas_rest_callback',
        'permission_callback' => '__return_true'
    ));
}
add_action('rest_api_init', 'doosearchas_search_rest');

// Callback function to handle REST API request and return filtered product data
function doosearchas_rest_callback($para){
    $page = isset($para['page']) ? intval($para['page']) : 1;
    $per_page = isset($para['per_page']) ? intval($para['per_page']) : 40;
    $args = array(
        'post_type' =>array('product'),
        'posts_per_page' => $per_page,
        'paged' => $page,
    );
    if (!empty($para['id'])) {
        $args['p'] = intval($para['id']);
    } 
    if (!empty($para['search'])) {
        $args['s'] = sanitize_text_field($para['search']);
        if (!empty($para['search_field'])) {
            $args['search_field'] = sanitize_text_field($para['search_field']);
        }
    }
    $tax_query = array('relation' => 'AND');
    if (!empty($para['category'])) {
        $categories = explode('~', sanitize_text_field($para['category']));
        $tax_query[] = array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => $categories,
            'operator' => 'IN',
        );
    }
    if (!empty($para['brand'])) {
        $brands = explode('~', sanitize_text_field($para['brand']));
        $tax_query[] = array(
            'taxonomy' => 'product_brand',
            'field' => 'slug',
            'terms' => $brands,
            'operator' => 'IN',
        );
    }
    if (!empty($para['category']) || !empty($para['brand'])) {
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Required tax_query for filtering by category/brand
        $args['tax_query'] = $tax_query;
    }
    if (!empty($para['min_price']) || !empty($para['max_price'])) {
        $meta_query = isset($args['meta_query']) ? $args['meta_query'] : array();
        $price_filter = array(
            'key' => '_price',
            'value' => array(),
            'compare' => 'BETWEEN',
            'type' => 'NUMERIC'
        );
        if (!empty($para['min_price'])) {
            $price_filter['value'][0] = floatval($para['min_price']);
        } else {
            $price_filter['value'][0] = 0;
        }
        if (!empty($para['max_price'])) {
            $price_filter['value'][1] = floatval($para['max_price']);
        } else {
            $price_filter['value'][1] = PHP_INT_MAX;
        }
        $meta_query[] = $price_filter;
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for price range filtering
        $args['meta_query'] = $meta_query;
    }  
    $obj = new WP_Query($args);
    $emptyArray = array(
        'postsPages' => array(),
        'products' => array(),
        'other' => array()
    );
    while($obj->have_posts()){
        $obj->the_post();
        if(get_post_type() == 'post' || get_post_type() == 'page'){
            $description = null;
            if(has_excerpt()){
                $description = get_the_excerpt();
            }else{
                $description = wp_trim_words(get_the_content(),18);
            }
            array_push($emptyArray['postsPages'], array(
                'postType' => get_post_type(),
                'authorName' => get_the_author(),
                'title' => get_the_title(),
                'permalink'=>get_the_permalink(),
                'description' => $description,
            ));
        }else if(get_post_type() == 'product'){
            $product = wc_get_product(get_the_ID());
            $short_description = $product ? $product->get_short_description() : '';
            $image_id = $product ? $product->get_image_id() : '';
            if($image_id){
                $image_url = $image_id ? wp_get_attachment_image_src($image_id, 'medium')[0] : ''; 
            }else{
                $image_url = wc_placeholder_img_src('medium') ? wc_placeholder_img_src('medium') : '';
            }
            $post_id = get_the_ID();
            $sku = $product ? $product->get_sku() : '';
            $status = get_post_status();
            $stock_quantity = $product ? $product->get_stock_quantity() : '';
            $stock_management_enabled = $product ? $product->get_manage_stock() : false;
            $attributes = array();
            if ($product) {
                $product_attributes = $product->get_attributes();
                foreach ($product_attributes as $attribute) {
                $attr_name = wc_attribute_label($attribute->get_name());
                $attr_values = wc_get_product_terms($product->get_id(), $attribute->get_name(), array('fields' => 'names'));
                $attributes[$attr_name] = implode(', ', $attr_values);
                }
            }
            array_push($emptyArray['products'], array(
                'id' => $post_id,
                'sku' => $sku,
                'title' => get_the_title(),
                'image' => $image_url,
                'price' => $product ? $product->get_price_html() : 'N/A',
                'status' => $status,
                'stock_quantity' => $stock_quantity,
                'stock_management_enabled' => $stock_management_enabled,
                'rating' => $product ? wc_get_rating_html($product->get_average_rating()) : 'No rating', 
                'permalink'=>get_the_permalink(),
                'short_description' => $short_description,
                'attributes' => $attributes,
            ));
        }else{
            array_push($emptyArray['other'], array(
                'postType' => get_post_type(),
                'authorName' => get_the_author(),
                'title' => get_the_title(),
            ));
        }
    }
    $args_all = $args;
    $args_all['posts_per_page'] = -1;
    $args_all['fields'] = 'ids';
    $all_posts_query = new WP_Query($args_all);
    $matched_post_ids = $all_posts_query->posts;
    $category_counts = array();
    $options = get_option('doosearchas_search_filter_options');
    $myCondition = isset($options['doosearchas_search_category_filter_select_db']) ? esc_attr($options['doosearchas_search_category_filter_select_db']) : 'all'; // or 'parent', 'sub', 'last'
    if (!empty($matched_post_ids)) {
        foreach ($matched_post_ids as $post_id) {
            $categories = wp_get_post_terms($post_id, 'product_cat');
            foreach ($categories as $cat) {
                $count_this = false;
                if ($myCondition === 'all') {
                    $count_this = true;
                } elseif ($myCondition === 'parent') {
                    if ($cat->parent == 0) {
                        $count_this = true;
                    }
                } elseif ($myCondition === 'sub') {
                    if ($cat->parent != 0) {
                        $count_this = true;
                    }
                } elseif ($myCondition === 'last') {
                    $child_categories = get_terms(array(
                        'taxonomy'   => 'product_cat',
                        'parent'     => $cat->term_id,
                        'hide_empty' => false,
                        'fields'     => 'ids',
                    ));
                    if (empty($child_categories)) {
                        $count_this = true;
                    }
                }
                if ($count_this) {
                    if (!isset($category_counts[$cat->term_id])) {
                        $category_counts[$cat->term_id] = array(
                            'name' => $cat->name,
                            'slug' => $cat->slug,
                            'count' => 1,
                        );
                    } else {
                        $category_counts[$cat->term_id]['count']++;
                    }
                }
            }
        }
    }
    $brand_counts = array();
    if (!empty($matched_post_ids)) {
        foreach ($matched_post_ids as $post_id) {
            $terms = wp_get_post_terms($post_id, 'product_brand');
            foreach ($terms as $term) {
                if (!isset($brand_counts[$term->term_id])) {
                    $brand_counts[$term->term_id] = array(
                        'name' => $term->name,
                        'slug' => $term->slug,
                        'count' => 1,
                    );
                } else {
                    $brand_counts[$term->term_id]['count']++;
                }
            }
        }
    }


$min_price = 0;
$max_price = 0;

if ( ! empty( $matched_post_ids ) ) {
    global $wpdb;

    // Build dynamic placeholders like: %d, %d, %d
    $placeholder_string = implode( ', ', array_fill( 0, count( $matched_post_ids ), '%d' ) );

    // Build the full SQL query string WITH placeholders inserted already
    $sql = "
        SELECT MIN(CAST(meta_value AS UNSIGNED)) as min_price,
               MAX(CAST(meta_value AS UNSIGNED)) as max_price
        FROM {$wpdb->prefix}postmeta
        WHERE meta_key = %s
        AND post_id IN ($placeholder_string)
    ";

    // Merge the meta_key and IDs
    $args = array_merge( [ '_price' ], $matched_post_ids );

    // Now prepare and run it (WPCS safe)
    
    // This is a custom SQL query required for dynamic price range filtering. (DirectQuery)
    // Real-time accuracy of price data is necessary, so caching is intentionally avoided. (NoCaching)
    // The query is securely prepared using $wpdb->prepare() with dynamic placeholders, so this is a false positive. (NotPrepared)
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $result = $wpdb->get_row( $wpdb->prepare( $sql, ...$args ) );

    if ( $result ) {
        $min_price = floatval( $result->min_price );
        $max_price = floatval( $result->max_price );
    }
}


    $formatted_category_counts = ["checkbox"];
    foreach ($category_counts as $cat) {
        $formatted_category_counts[] = [$cat['name'], $cat['count']];
    }
    $formatted_brand_counts = ["checkbox"];
    foreach ($brand_counts as $brand) {
        $formatted_brand_counts[] = [$brand['name'], $brand['count']];
    }
    return array(
        'data' => $emptyArray,
        'pagination' => array(
            'total_items'  => $obj->found_posts,
            'total_pages'  => $obj->max_num_pages,
            'current_page' => $page?$page:0,
            'per_page'     => $per_page,
        ),
        'category_counts' => array_values($formatted_category_counts),
        'brand_counts'    => array_values($formatted_brand_counts),
        'price_range' => array(
            'min' => $min_price,
            'max' => $max_price,
        ),
    );
}