<?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'] = ['kaveh_custom']['_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'] = ['kaveh_custom']['_wc_average_rating'];
            $args['orderby'] = 'meta_value_num';
        }
        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'] = ['kaveh_custom']['total_sales'];
            $args['orderby'] = 'meta_value_num';
        }
        return $args;
    }

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

    public function kaveh_rest_products() {
        register_rest_field(
            'product',
            'kaveh_custom',
            array(
                '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 array(
                'thumbnail_url' => get_the_post_thumbnail_url($object['id']),
                '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']); // Get the WooCommerce product object

            // Initialize the array with existing data
            $array = array(
                'thumbnail_url' => get_the_post_thumbnail_url($object['id']),
                'excerpt'       => get_the_excerpt($object['id']),
                'date'          => get_the_date('', $object['id']),
            );

            $_wc_average_rating = $product->get_average_rating();
            $total_sales = $product->get_total_sales();

            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() ) {
                        $_sale_price_dates_to   = $variation->get_date_on_sale_to();
                        if( !empty($_sale_price_dates_to) ) {
                            $array['_sale_price_dates_to'] = $_sale_price_dates_to;
                            break;
                        }
                    }
                }
            }elseif($product->is_type('simple')){
                $_sale_price_dates_to = $product->get_date_on_sale_to();

                if(!empty($_sale_price_dates_to)):
                    $array['_sale_price_dates_to'] = $_sale_price_dates_to;
                endif;  
            }


            if(!empty($_wc_average_rating)):
                $array['_wc_average_rating'] = $_wc_average_rating;
            else:
                $array['_wc_average_rating'] = 0;
            endif;  
            if(!empty($_wc_average_rating)):
                $array['total_sales'] = $total_sales;
            else:
                $array['total_sales'] = 0;
            endif;   

            $array['product_type'] = $product->get_type();
            $array['product_stock_status'] = $product->get_stock_status();
            $array['gallery_image_ids'] = $product->get_gallery_image_ids();

            if ( $product->is_type( 'variable' ) ) {

                if(!empty($product->get_variation_regular_price('min'))){
                    $array['_price'] = $product->get_variation_regular_price('min');
                }

                if ( $product->is_on_sale() ){
                    $array['is_on_sale'] = true;
                    $array['min_regular_price'] = $product->get_variation_regular_price('min');
                    $array['max_regular_price'] = $product->get_variation_regular_price('max');
                    $array['min_sale_price'] = $product->get_variation_sale_price('min');
                    $array['max_sale_price'] = $product->get_variation_sale_price('max');

                }else{
                    $array['is_on_sale'] = false;
                    $array['min_regular_price'] = $product->get_variation_regular_price('min');
                    $array['max_regular_price'] = $product->get_variation_regular_price('max');
                }

            }elseif( $product->is_type( 'simple' ) ){

                if(!empty($product->get_regular_price())){
                    $array['_price'] = $product->get_regular_price();
                }

                if ( $product->is_on_sale() ){
                    $array['is_on_sale'] = true;
                    $array['sale_price'] = $product->get_sale_price();
                    $array['normal_price'] = $product->get_regular_price();
                }else{
                    $array['is_on_sale'] = false;
                    $array['normal_price'] = $product->get_regular_price();
                }

            }

           

            return $array;
        }
        return false;
    }

    public static function kaveh_get_rest_posts($args = array()) {
        $defaults = array(
            '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 based on arguments
        $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, WEEK_IN_SECONDS); // Cache for 15 minutes
            return $data;
        }

        return null;
    }

    public function invalidate_cache() {
        global $wpdb;
        $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_kaveh_rest_posts_%'");
    }

    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)

// ));
?>
