<?php
class WC_Products_Widget extends WP_Widget {
    function __construct()
    {
        parent::__construct(
            'nbcore_wcproducts',
            esc_html__('NB - WC Products', 'core-wp'),
            array( 'description' => esc_html__( 'Simple widget to display products', 'core-wp' ), )
        );
    }

    public function widget($args, $instance)
    {
        extract($args);

        $title = apply_filters('widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base);
        $posts_per_page = empty( $instance['posts_per_page'] ) ? 5 : ( int ) $instance['posts_per_page'];
        if($instance['product_category']){ $product_category =  $instance['product_category']; }else{$product_category ='';}
        if($instance['product_type']){ $product_type =  $instance['product_type']; }else{ $product_type=''; }

        echo wp_kses_post( $before_widget );

        if ( ! empty( $title ) ) {
            echo wp_kses_post( $before_title . $title . $after_title );
        }

        $meta_query = WC()->query->get_meta_query();

        /*$atts = array(
            'orderby' => 'title',
            'order'   => 'asc'
        );*/

        $atts = array(
            'orderby' => 'date',
            'order'   => 'desc'
        );

        $args = array(
            'post_type'           => 'product',
            'post_status'         => 'publish',
            'ignore_sticky_posts' => 1,
            'posts_per_page'      => $posts_per_page,            
            'meta_query'          => $meta_query
        );
        $this->args_product_by_product_type($args, $product_type, $product_category);

        //$products = new WP_Query( $args );

        $products = new WP_Query(apply_filters('woocommerce_shortcode_products_query', $args, $atts));

        if ( $products->have_posts() ) {
            echo apply_filters( 'woocommerce_before_widget_product_list', '<ul class="product_list_widget">' );

            while ( $products->have_posts() ) {
                $products->the_post();
                //wc_get_template( 'content-widget-product.php', array( 'show_rating' => true ) );
                global $product;
                ?>
                <li class="product">
                    <a href="<?php echo esc_url( $product->get_permalink() ); ?>">
                        <?php print($product->get_image()); ?>
                    </a>
                    <div class="widget-product-meta">
                        <h5 class="product-title">
                            <a href="<?php echo esc_url( $product->get_permalink() ); ?>">
                                <?php echo esc_html($product->get_name()); ?>
                            </a>
                        </h5>
                        <?php //if ( ! empty( $show_rating ) ) {
                            echo wc_get_rating_html( $product->get_average_rating() );
                        //} ?>
                        <?php print($product->get_price_html()); ?>
                    </div>
                </li>

                <?php
            }

            echo apply_filters( 'woocommerce_after_widget_product_list', '</ul>' );
        }

        wp_reset_postdata();

        echo wp_kses_post( $after_widget );
    }

    public function form($instance)
    {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
        $posts_per_page = ! empty( $instance['posts_per_page'] ) ? $instance['posts_per_page'] : 5;
        $product_category = isset( $instance['product_category'] ) ? $instance['product_category'] : '';
        $product_type = isset( $instance['product_type'] ) ? $instance['product_type'] : '';

        $prod_cat_args = array(
          'taxonomy'     => 'product_cat', 
          'orderby'      => 'name',
          'empty'        => 0
        );

        $woo_categories = get_categories( $prod_cat_args );
        ?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'core-wp' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'posts_per_page' ) ); ?>"><?php esc_attr_e( 'Posts per page:', 'core-wp' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'posts_per_page' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'posts_per_page' ) ); ?>" type="text" value="<?php echo esc_attr( $posts_per_page ); ?>">
        </p>

        <p>
            <label for="<?php echo $this->get_field_id('product_type'); ?>"><?php echo esc_html__( 'Product type', 'nb-fw' ); ?></label>
            <select name="<?php echo $this->get_field_name('product_type'); ?>" id="<?php echo $this->get_field_id('product_type'); ?>" >
                <option value='recent' <?php selected( $product_type, 'recent'); ?> ><?php echo esc_html__('Recent', 'nb-fw'); ?></option>
                <option value='featured' <?php selected( $product_type, 'featured'); ?> ><?php echo esc_html__('Featured', 'nb-fw'); ?></option>
                <option value='best_selling' <?php selected( $product_type, 'best_selling'); ?> ><?php echo esc_html__('Best Selling', 'nb-fw'); ?></option>
                <option value='top_rated' <?php selected( $product_type, 'top_rated'); ?> ><?php echo esc_html__('Top Rated', 'nb-fw'); ?></option>
                <option value='mixed_order' <?php selected( $product_type, 'mixed_order'); ?> ><?php echo esc_html__('Mixed Order', 'nb-fw'); ?></option>
                <option value='category' <?php selected( $product_type, 'category'); ?> ><?php echo esc_html__('Product by Category', 'nb-fw'); ?></option>
            </select>
        
        </p>

        <p class="default-form">
            <label for="<?php echo esc_attr($this->get_field_id( 'product_category' )); ?>"><?php _e( 'Product Category:' ); ?></label> 
            <select class="widefat product_category" name="<?php echo $this->get_field_name( 'product_category' ); ?>" id="<?php echo $this->get_field_id( 'product_category' ); ?>">
            <?php
            foreach($woo_categories as $cat)
            {
                ?>
                    <option value="<?php echo $cat->slug; ?>" <?php if($product_category==$cat->slug){echo 'selected';}?>><?php echo $cat->name; ?></option>
                <?php       
            
            }
            ?>
            </select>
        </p>
        <?php
    }

    public function update($new_instance, $old_instance)
    {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['posts_per_page'] = strip_tags($new_instance['posts_per_page']);
        $instance['product_category'] = ( ! empty( $new_instance['product_category'] ) ) ? strip_tags( $new_instance['product_category'] ) : '';
        $instance['product_type'] = ( ! empty( $new_instance['product_type'] ) ) ? strip_tags( $new_instance['product_type'] ) : '';

        return $instance;
    }
    public function args_product_by_product_type( &$args = array(), $product_type = 'recent', $product_category ){
            switch( $product_type ){
                case 'sale':
                    $args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
                break;
                case 'featured':
                    $args['tax_query'][] = array(
                        'taxonomy' => 'product_visibility',
                        'field'    => 'name',
                        'terms'    => 'featured',
                        'operator' => 'IN',
                    );
                break;
                case 'best_selling':
                    $args['meta_key']   = 'total_sales';
                    $args['orderby']    = 'meta_value_num';
                    $args['order']      = 'desc';
                break;
                case 'top_rated':
                    $args['meta_key']   = '_wc_average_rating';
                    $args['orderby']    = 'meta_value_num';
                    $args['order']      = 'desc';
                break;
                case 'mixed_order':
                    $args['orderby']    = 'rand';
                break;
                case 'category':
                    $args['product_cat']    = $product_category;
                break;
                default: /* Recent */
                    $args['orderby']    = 'date';
                    $args['order']      = 'desc';
                break;
            }
    }
}