<?php
/*
Theme Designed By: Meysam Hosseinkhani
Email: Meysam98@Gmail.com
Author Website: Hosseinkhani.ir
*/
   // Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
class Dina_Product_widget extends WP_Widget {

public function __construct() {
   $widget_ops = array('classname' => 'dina-product_widget', 'description' => __('Products widget (DinaKala)', 'dina-kala') );
   parent::__construct('dina-product', __('Products widget (DinaKala)', 'dina-kala'), $widget_ops);
   $this->alt_option_name = 'dina-product_widget';
}

function widget($args, $instance) {
   global $di_data;
   extract( $args );
   $title = apply_filters( 'widget_title', empty($instance['title']) ? __('Products widget (DinaKala)', 'dina-kala') : $instance['title'], $instance, $this->id_base);
   $number  = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
   $prod_sort = isset( $instance['prod_sort'] ) ? esc_attr( $instance['prod_sort'] ) : 'latest';
   $prod_cat = isset( $instance['prod_cat'] ) ? absint( $instance['prod_cat'] ) : '';
   $stock_status = isset( $instance['stock-status'] ) ? $instance['stock-status'] : '';
      
      if($prod_sort != 'special') {
			switch ($prod_sort) {
				case 'latest':
					$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'order' => 'DESC'  );
					break;
				case 'saled':
					$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'meta_key' => 'total_sales',
                    'orderby' => 'meta_value_num',
                    'order' => 'DESC'  );
					break;
				case 'discounted':
					$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'post__in'          => array_merge( array( 0 ), wc_get_product_ids_on_sale() ),
                    'order' => 'DESC'  );
					break;
				case 'viewed':
					$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'meta_key' => 'post_views_count',
                    'orderby' => 'meta_value_num',
                    'order' => 'DESC'  );
					break;
				case 'random':
					$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'orderby'        => 'rand'  );
					break;
				default:
				$args = array(
					'posts_per_page' => $number,
					'post_type' => 'product',
					'post_status' => 'publish',
					'order' => 'DESC'  );
				}
				if ( $prod_cat ) {
					$args['tax_query'] = array(
						array(
						'taxonomy' => 'product_cat',
						'field' => 'term_id',
						'terms' => $prod_cat
						)
					);
				}
      } elseif ($prod_sort == 'special') {
         $args = array(
         'posts_per_page' => $number,
         'post_type' => 'product',
         'post_status' => 'publish',
         'tax_query' => array(
            'relation' => 'OR',
            array(
               'taxonomy' => 'product_visibility',
               'field'    => 'name',
               'terms'    => 'featured',
            ),
            array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => $prod_cat
            )
         ),
         'order' => 'DESC'  );
      }  

      if('in-stock' === $stock_status){
         $args['meta_query'] = array(
               'relation' => 'AND',
               array(
                  'key' => '_stock_status',
                  'value' => 'instock'
               )
            );
      }
         
      $products = get_posts($args);				

      global $post;
      if( !is_object($post) ) 
        return;
      //save the current post
      $temp=$post;
      echo $before_widget;
      // Widget title
      echo $before_title;
      echo $instance["title"];
      echo $after_title; ?>

      <ul class="latest-posts">
      <?php if( $products ) {
      foreach($products as $post ) {
         setup_postdata($post );
      ?>
         <li>
            <?php $link_target = ($di_data['open_prod_new_tab'] ? '_blank' : '_self'); ?> 
            <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>" target="<?php echo $link_target; ?>">
            <span class="post-image">
               <?php if ( has_post_thumbnail()) :  ?>
               <?php the_post_thumbnail( 'thumbnail' ); ?>
               <?php else: ?>
               <img width="64" height="64" src="<?php echo esc_url( get_template_directory_uri() ); ?>/images/mtumb.png" alt="<?php the_title_attribute(); ?>"/>
               <?php endif; ?>
            </span>
            <span class="w-post-title">
               <?php the_title();?>
            </span>
            <?php
            //$product = new WC_Product(get_the_ID());
            global $product;
            $in_stock = $product->is_in_stock(); ?>
            <?php if($in_stock) {
               ?>
               <span class="w-prod-desc">
                  <?php echo $product->get_price_html(); ?>
               </span>
            <?php } else { ?>
               <span class="w-prod-desc nstock">
                  <?php _e( 'Out of stock', 'dina-kala' ); ?>
               </span>
            <?php } ?>
            
            </a>
         </li>
      <?php }
      }
      else
      {
         echo __('No products found!', 'dina-kala');
      }
      wp_reset_query();
      ?>

      </ul>

      <?php echo $after_widget;
}

//Update widget to DB
public function update( $new_instance, $old_instance ) {
   $instance = $old_instance;
   $instance['title'] = sanitize_text_field( $new_instance['title'] );
   $instance['prod_sort'] = sanitize_text_field( $new_instance['prod_sort'] );
   $instance['number'] = (int) $new_instance['number'];
   $instance['stock-status'] = sanitize_text_field( $new_instance['stock-status']) ;
   $instance['prod_cat'] = (int) $new_instance['prod_cat'];
   return $instance;
}

//Display Widget Backend
public function form( $instance ) {
   $title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : '';
   $number    = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5;
   $prod_sort = isset( $instance['prod_sort'] ) ? esc_attr( $instance['prod_sort'] ) : '';
   $stock_status = isset( $instance['stock-status'] ) ? $instance['stock-status'] : '';
   $prod_cat  = isset( $instance['prod_cat'] ) ? absint( $instance['prod_cat'] ) : 0;
?>
   <p>
      <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'dina-kala'); ?></label>
      <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
   </p>

   <p>
      <label for="<?php echo $this->get_field_id( 'number' ); ?>"><?php _e('Number of products to show:', 'dina-kala'); ?></label>
      <input class="tiny-text" id="<?php echo $this->get_field_id( 'number' ); ?>" name="<?php echo $this->get_field_name( 'number' ); ?>" type="number" step="1" min="1" value="<?php echo $number; ?>" size="3" />
   </p>

   <p>
      <label for="<?php echo $this->get_field_id( 'stock-status' ); ?>">
      <input type="checkbox" id="<?php echo $this->get_field_id( 'stock-status' ); ?>" value="in-stock" name="<?php echo $this->get_field_name( 'stock-status' ); ?>" <?php checked( $stock_status, 'in-stock' ); ?> />
      <?php _e('Show in stock products','dina-kala') ?>
      </label>
   </p>

   <label for="<?php echo $this->get_field_id('prod_sort'); ?>"><?php _e('Products sorting','dina-kala') ?></label><br />
   <select class="widefat" name="<?php echo $this->get_field_name('prod_sort'); ?>" id="<?php echo $this->get_field_id('prod_sort'); ?>">
   <option value="latest" <?php selected( $prod_sort, 'latest' ); ?>><?php _e('Latest products', 'dina-kala') ?></option>
   <option value="random" <?php selected( $prod_sort, 'random' ); ?>><?php _e('Random products', 'dina-kala') ?></option>
   <option value="viewed" <?php selected( $prod_sort, 'viewed' ); ?>><?php _e('Most viewed products', 'dina-kala') ?></option>
   <option value="saled" <?php selected( $prod_sort, 'saled' ); ?>><?php _e('Best selling products', 'dina-kala') ?></option>
   <option value="discounted" <?php selected( $prod_sort, 'discounted' ); ?>><?php _e('Discounted products', 'dina-kala') ?></option>
   <option value="special" <?php selected( $prod_sort, 'special' ); ?>><?php _e('Special products', 'dina-kala') ?></option>
   </select>

   <label for="<?php echo $this->get_field_id('prod_cat'); ?>"><?php _e('Category','dina-kala') ?></label><br />
   <?php $categories = get_terms("product_cat");
   if ( !empty( $categories ) && !is_wp_error( $categories ) ) { ?>
   <select class="widefat" name="<?php echo $this->get_field_name('prod_cat'); ?>" id="<?php echo $this->get_field_id('prod_cat'); ?>" >
   <option value=""><?php _e("--Select Category--",'dina-kala') ?></option>
   <?php foreach ( $categories as $category ) { ?>
   <option value="<?php echo $category->term_id ?>" <?php selected( $prod_cat, $category->term_id ); ?>><?php echo $category->name ?></option>
   <?php } ?>
   </select>

   <?php } ?>
<?php
}

}
// register Products Widget
add_action('widgets_init', function() {return register_widget("Dina_Product_widget");});
?>