<?php
class KavehRestRules {

    public function __construct() {
        add_action('rest_api_init', [$this, 'kaveh_rest_posts']);

        if (class_exists('woocommerce')) {
            add_action('rest_api_init', [$this, 'kaveh_rest_products']);
            add_filter('rest_product_collection_params', [$this, 'kaveh_rest_price_orderby_param']);
            add_filter('rest_product_query', [$this, 'kaveh_rest_price_order_price'], 10, 2);
            add_filter('rest_product_collection_params', [$this, 'kaveh_rest_wc_average_rating_orderby_param']);
            add_filter('rest_product_query', [$this, 'kaveh_rest_order_wc_average_rating'], 10, 2);
            add_filter('rest_product_collection_params', [$this, 'kaveh_rest_total_sales_orderby_param']);
            add_filter('rest_product_query', [$this, 'kaveh_rest_order_total_sales'], 10, 2);
        }

        add_action('delete_post', [$this, 'invalidate_cache']);
        add_action('transition_post_status', [$this, 'kaveh_rest_flush_cache'], 10, 3);
    }

    public function kaveh_rest_price_orderby_param($params) {
        $params['orderby']['enum'][] = '_price';
        return $params;
    }
    
    public function kaveh_rest_price_order_price($args, $request) {
        if (isset($request['orderby']) && $request['orderby'] === '_price') {
            $args['meta_key'] = '_price';
            $args['orderby'] = 'meta_value_num';
        }
        return $args;
    }

    public function kaveh_rest_wc_average_rating_orderby_param($params) {
        $params['orderby']['enum'][] = '_wc_average_rating';
        return $params;
    }
    
    public function kaveh_rest_order_wc_average_rating($args, $request) {
        if (isset($request['orderby']) && $request['orderby'] === '_wc_average_rating') {
            $args['meta_key'] = '_wc_average_rating';
            $args['orderby'] = 'meta_value_num';
            $args['order'] = isset($request['order']) ? $request['order'] : 'desc'; // Default to descending order
        }
        return $args;
    }

    public function kaveh_rest_total_sales_orderby_param($params) {
        $params['orderby']['enum'][] = 'total_sales';
        return $params;
    }
    
    public function kaveh_rest_order_total_sales($args, $request) {
        if (isset($request['orderby']) && $request['orderby'] === 'total_sales') {
            $args['meta_key'] = 'total_sales';
            $args['orderby'] = 'meta_value_num';
            $args['order'] = isset($request['order']) ? $request['order'] : 'desc'; // Default to descending order
        }
        return $args;
    }

    public function kaveh_rest_posts() {
        register_rest_field('post', 'kaveh_custom', [
            'get_callback' => [$this, 'get_rest_kaveh_data'],
            'update_callback' => null,
            'schema' => null,
        ]);
    }

    public function kaveh_rest_products() {
        register_rest_field('product', 'kaveh_custom', [
            'get_callback' => [$this, 'get_woo_rest_kaveh_data'],
            'update_callback' => null,
            'schema' => null,
        ]);
    }

    public function get_rest_kaveh_data($object, $field_name, $request) {
        if ($object['id']) {
            return [
                'thumbnail_url' => get_the_post_thumbnail_url($object['id'], 'full'),
                'excerpt' => get_the_excerpt($object['id']),
                'date' => get_the_date('', $object['id']),
            ];
        }
        return false;
    }

    public function get_woo_rest_kaveh_data($object, $field_name, $request) {
        if ($object['id']) {
            $product = wc_get_product($object['id']);
            $offer_percentage = kavehWoo::showofferpercentage($product);
            $array = [
                'thumbnail_url' => get_the_post_thumbnail_url($object['id']),
                'excerpt' => get_the_excerpt($object['id']),
                'date' => get_the_date('', $object['id']),
                'sale_percentage' => $offer_percentage ?: 0,
                '_wc_average_rating' => $product->get_average_rating() ?: 0,
                'total_sales' => $product->get_total_sales() ?: 0,
                'product_type' => $product->get_type(),
                'product_stock_status' => $product->get_stock_status(),
                'gallery_image_ids' => $product->get_gallery_image_ids(),
            ];

            if ($product->is_type('variable')) {
                $variation_ids = $product->get_visible_children();
                foreach ($variation_ids as $variation_id) {
                    $variation = wc_get_product($variation_id);
                    if ($variation->is_on_sale() && $variation->get_date_on_sale_to()) {
                        $array['_sale_price_dates_to'] = $variation->get_date_on_sale_to();
                        break;
                    }
                }
                $array['_price'] = $product->get_variation_regular_price('min') ?: null;
                $array['is_on_sale'] = $product->is_on_sale();
                $array['min_regular_price'] = $product->get_variation_regular_price('min') ?: null;
                $array['max_regular_price'] = $product->get_variation_regular_price('max') ?: null;
                $array['min_sale_price'] = $product->get_variation_sale_price('min') ?: null;
                $array['max_sale_price'] = $product->get_variation_sale_price('max') ?: null;
            } elseif ($product->is_type('simple')) {
                $array['_price'] = $product->get_regular_price() ?: null;
                $array['is_on_sale'] = $product->is_on_sale();
                $array['sale_price'] = $product->get_sale_price() ?: null;
                $array['normal_price'] = $product->get_regular_price() ?: null;
                $array['_sale_price_dates_to'] = $product->get_date_on_sale_to() ?: null;
            }

            return $array;
        }
        return false;
    }

    public static function kaveh_get_rest_posts($args = []) {
        $defaults = [
            'post_type' => 'posts',
            'per_page' => 10,
            'orderby' => 'date',
            'order' => 'desc'
        ];

        $args = wp_parse_args($args, $defaults);
        $post_type = isset($args['post_type']) ? $args['post_type'] : 'posts';
        unset($args['post_type']);

        $cache_key = 'kaveh_rest_posts_' . md5(serialize($args));
        $cached_response = get_transient($cache_key);

        if ($cached_response !== false) {
            return $cached_response;
        }

        $request = new WP_REST_Request('GET', '/wp/v2/' . $post_type);
        $request->set_query_params($args);

    
        $response = rest_do_request($request);

        if (!$response->is_error()) {
            $data = $response->get_data();
            set_transient($cache_key, $data, 15 * MINUTE_IN_SECONDS);
            return $data;
        }

        return null;
    }

    public function invalidate_cache() {
        global $wpdb;
        // Prefix to search for in the options table
        $transient_prefix = '_transient_timeout_kaveh_rest_posts';
        // Delete options directly from the database that match the transient prefix
        $deleted_count = $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                $wpdb->esc_like($transient_prefix) . '%'
            )
        );
    }

    public function kaveh_rest_flush_cache($new_status, $old_status, $post) {
        $this->invalidate_cache();
    }
}

    // Example Usage:
    // Example 1: Default parameters
    // $posts = KavehRestRules::kaveh_get_rest_posts();

    // Example 2: Custom per_page and post_type
    // $posts = KavehRestRules::kaveh_get_rest_posts(array(
    //     'post_type' => 'custom_post_type',
    //     'per_page' => 5,
    // ));

    // Example 3: Custom parameters including author and category
    // $posts = KavehRestRules::kaveh_get_rest_posts(array(
    //     'post_type' => 'custom_post_type',
    //     'per_page' => 5,
    //     'author' => 1,
    //     'categories' => array(3, 7)
    // ));
