<?php

/*-----------------------------------------------------------------------------------*/
/*  Popular Home View Most widget
/*-----------------------------------------------------------------------------------*/
class ex_themes_most_views_ extends WP_Widget {

	public function __construct(){
		$widget_ops = array(
			'classname'   => 'exthemes-mostview',
			'description' => __( THEMES_NAMES.' Sidebar Post Widget', THEMES_NAMES ),
		);
		parent::__construct( 'exthemes-mostview', __( '(MDR) Sidebar Post Widget', THEMES_NAMES ), $widget_ops );
	}
	
	public function widget( $args, $instance ){
		$widget_id			= $this->id_base . '-' . $this->number;
		$category_ids		= ( ! empty( $instance['category_ids'] ) ) ? array_map( 'absint', $instance['category_ids'] ) : array( 0 );
		$number_posts		= ( ! empty( $instance['number_posts'] ) ) ? absint( $instance['number_posts'] ) : absint( 5 ); 
		$link_title			= ( ! empty( $instance['link_title'] ) ) ? esc_url( $instance['link_title'] ) : '';
		$title_button		= ( ! empty( $instance['title_button'] ) ) ? $instance['title_button'] : '';
		$title			= apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
		global $opt_themes;
		?>
		
		

		<?php 
		switch($opt_themes['themes_styles']){
			case 'moddroid':
			?>
			<section class="mb-2">
			<div class="h5 font-weight-semibold mb-3">
			<a class="text-body border-bottom-2 border-secondary d-inline-block pb-1" href="<?php echo $instance['title_link']; ?>"><?php echo $instance['title']; ?></a>
			</div>
			<?php 
			break; 
			
			case 'modyolo':
			?>
			<section class="bg-white border rounded shadow-sm pt-3 px-2 px-md-3 mb-3">
			<header class="d-flex align-items-end mb-3">
			<h2 class="h5 font-weight-semibold mb-0">
			<a class="text-body" href="<?php echo $instance['title_link']; ?>">
			<?php echo $instance['title']; ?>			
			</a>
			</h2>
			<a class="btn btn-primary btn-sm ml-auto" href="<?php echo $instance['title_link']; ?>"><?php echo $instance['title_button']; ?></a>
			</header>
			<?php 
			break; 
			
			case 'reborn':
			?> 
			<section class="bg-white rounded pb-3 pt-3 px-2 mb-4 ">
			
			<div class="d-flex align-items-baseline justify-content-between ">
			<h2 class="h5 font-weight-semibold m-0 p-0 mb-3 "><?php echo $instance['title']; ?>		</h2>
			<a class="small text-truncate text-muted pr-2 " href="<?php echo $instance['title_link']; ?>"><?php echo $instance['title_button']; ?></a>
			</div>
			<?php 
			break; 
			
			case 'liteapks':
			?> 
			<section class="mb-4">
			<h4 class="h4 font-weight-bold mb-3"><?php echo $instance['title']; ?></h4> 
			<?php 
			break; 
			
			default:
			?>
			<section class="mb-2">
			<div class="h5 font-weight-semibold mb-3">
			<a class="text-body border-bottom-2 border-secondary d-inline-block pb-1" href="<?php echo $instance['title_link']; ?>"><?php echo $instance['title']; ?></a>
			</div>
			<?php 
			break;
		} ?> 

 
		
		 
		
		<?php
		/* global $opt_themes; if($opt_themes['ex_themes_home_style_2_activate_']) {  } else { echo $args['after_title']; }  */
		
        if ( in_array( 0, $category_ids, true ) ) {
            $category_ids = array( 0 );
        }
		$args = array(
			'posts_per_page'			=> $instance['number_posts'],
			'post_type'		=> 'post',
			'no_found_rows'			=> true,
			'post_status'			=> 'publish', 
			'orderby'		=> $instance['orderby'],
			'update_post_term_cache'	=> false,
			'update_post_meta_cache'	=> false,
		);

		if ( ! in_array( 0, $category_ids, true ) ) {
			$args['category__in'] = $category_ids;
		} 
			
		if( $instance['orderby'] == 'views' ){
			$args = array(
			'posts_per_page'	=> $instance['number_posts'],
			'post_type'			=> 'post',
			'order'			=> 'DESC',
			'orderby'			=> 'meta_value_num',
			'meta_key'			=> 'post_views_count',
			'ignore_sticky_posts' => true
			);
		}

		if( $instance['orderby'] == 'rate' ){
			$args = array(
			'posts_per_page'	=> $instance['number_posts'],
			'post_type'			=> 'post',
			'meta_query' => array(
			'relation' => 'AND',
			'average_clause' => array(
		'key'     => 'rmp_avg_rating',
		'compare' => 'EXISTS',
			),
			'count_clause' => array(
		'key'     => 'rmp_vote_count',
		'compare' => 'EXISTS',
			),
			),
			'orderby'  => array(
		'average_clause' => 'DESC',
		'count_clause'   => 'DESC',
			),
			'ignore_sticky_posts' => true
			
			);
		}
		
		if( $instance['orderby'] == 'rategps' ){
			$args = array(
			'posts_per_page'	=> $instance['number_posts'],
			'post_type'			=> 'post',
			'meta_query' => array(
			'relation' => 'AND',
			'average_clause' => array(
		'key'     => 'wp_rated_GP',
		'compare' => 'EXISTS',
			),
			'count_clause' => array(
		'key'     => 'wp_ratings_GP',
		'compare' => 'EXISTS',
			),
			),
			'orderby'  => array(
		'average_clause' => 'DESC',
		'count_clause'   => 'DESC',
			),
			'ignore_sticky_posts' => true
			
			);
		}
		
		if( isset($instance['orderdate']) && $instance['orderdate'] != 'alltime' ){
			$year		= date('Y');
			$month		= absint( date('m') );
			$week		= absint( date('W') );
			
			$args['year']	= $year;

			if( $instance['orderdate'] == 'pastmonth' ){
		$args['monthnum'] = $month - 1;
			}
			if( $instance['orderdate'] == 'pastweek' ){
		$args['w'] = $week - 1;
			}
			if( $instance['orderdate'] == 'pastyear' ){
		unset( $args['year'] );
		$today = getdate();
		$args['date_query'] = array(
			array(
			'after' => $today[ 'month' ] . ' 1st, ' . ($today[ 'year' ] - 2)
			)
		);
			}
		}

		if( isset($instance['orderdate']) && $instance['orderdate'] == 'bydays' && isset($instance['days_amount']) ){
			$args['year'] = '';
			$days_amount = absint( $instance['days_amount'] ); 
			if( $days_amount > 0 ){
			$days_string = "-$days_amount days";
			$args['date_query'] = array(
		'after'		=> date('Y-m-d', strtotime( $days_string ) ),
		'inclusive'	=> true,
		'column'	=> 'post_date'
			);
			}
		}
		$rp = new WP_Query( apply_filters( 'ex_themes_most_views__widget_posts_args', $args ) );
		while( $rp->have_posts() ) :
		$rp->the_post();
		
		global $wpdb, $post, $opt_themes; 
			$sizes					=	get_post_meta( $post->ID, 'wp_sizes', true ); 
			$sizes_alt				=	get_post_meta( $post->ID, 'wp_sizes_GP', true );
			if ( $sizes === FALSE or $sizes == '' ) $sizes = $sizes_alt; 
		 
		switch($opt_themes['themes_styles']){
			case 'moddroid':
				get_template_part('loop/item.sidebar.mdr'); 			 
			break; 
			
			case 'modyolo':
			?>
			<div class=" mb-3">
			<a class="text-body border rounded overflow-hidden d-block h-100 position-relative archive-post" href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
			<div class="d-flex" style="padding: 0.5rem;">
			<div class="flex-shrink-0 mr-2" style="width: 3.75rem;">
			
			<img width="65" height="65" src="<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo $opt_themes['no_img']['url']; } ?>" class="rounded " alt="<?php the_title(); ?>" > 
			</div>
			<div style="min-width: 0;">
			<h3 class="h6 font-weight-semibold text-truncate w-100" style="margin-bottom: 2px;"><?php if($opt_themes['app_name']){ if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); }} else { the_title(); } ?></h3>

			<div class="small text-truncate text-muted">
			<svg class="svg-6 svg-muted mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M567.938 243.908L462.25 85.374A48.003 48.003 0 0 0 422.311 64H153.689a48 48 0 0 0-39.938 21.374L8.062 243.908A47.994 47.994 0 0 0 0 270.533V400c0 26.51 21.49 48 48 48h480c26.51 0 48-21.49 48-48V270.533a47.994 47.994 0 0 0-8.062-26.625zM162.252 128h251.497l85.333 128H376l-32 64H232l-32-64H76.918l85.334-128z"></path></svg>
			<span class="align-middle"><?php if (get_post_meta( $post->ID, 'wp_version_GP', true )) { echo trim(get_post_meta( $post->ID, 'wp_version_GP', true )); } ?></span>
			<?php if( $sizes){?>
			<span class="align-middle"> + </span>
			<span class="align-middle"><?php echo $sizes; ?></span>
			<?php } ?>
			</div>
			
			<div class="small text-truncate text-muted">
			<svg class="svg-6 svg-muted mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M501.1 395.7L384 278.6c-23.1-23.1-57.6-27.6-85.4-13.9L192 158.1V96L64 0 0 64l96 128h62.1l106.6 106.6c-13.6 27.8-9.2 62.3 13.9 85.4l117.1 117.1c14.6 14.6 38.2 14.6 52.7 0l52.7-52.7c14.5-14.6 14.5-38.2 0-52.7zM331.7 225c28.3 0 54.9 11 74.9 31l19.4 19.4c15.8-6.9 30.8-16.5 43.8-29.5 37.1-37.1 49.7-89.3 37.9-136.7-2.2-9-13.5-12.1-20.1-5.5l-74.4 74.4-67.9-11.3L334 98.9l74.4-74.4c6.6-6.6 3.4-17.9-5.7-20.2-47.4-11.7-99.6.9-136.6 37.9-28.5 28.5-41.9 66.1-41.2 103.6l82.1 82.1c8.1-1.9 16.5-2.9 24.7-2.9zm-103.9 82l-56.7-56.7L18.7 402.8c-25 25-25 65.5 0 90.5s65.5 25 90.5 0l123.6-123.6c-7.6-19.9-9.9-41.6-5-62.7zM64 472c-13.2 0-24-10.8-24-24 0-13.3 10.7-24 24-24s24 10.7 24 24c0 13.2-10.7 24-24 24z"></path></svg>
			<span class="align-middle">
					
			<?php if (get_post_meta( get_the_ID(), 'wp_mods', true )) { ?>
			<?php _e($opt_themes['exthemes_MODAPK'], TEXT_DOMAIN); ?>&nbsp;<?php echo trim(strip_tags(limit_words(get_post_meta( $post->ID, 'wp_mods', true ), '3'))) ?>
			<?php } else { ?>	
			<?php
			$i = 0;
			foreach((get_the_category()) as $cat) {
			echo ''.$cat->cat_name.'';
			if (++$i == 1) break;
			}
			?>
			<?php } ?>	
			</span>
			</div>
			</div>
			</div>
			</a>
			</div>
			<?php
			break; 
			
			case 'reborn':
			?>
			<div class="mb-4">
			<a class="position-relative archive-post--remove app-container" href="<?php the_permalink() ?>" title="<?php if($opt_themes['app_name']){ if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); }} else { the_title(); } ?>">
			<div class="flex-shrink-0">
			
			<img width="65" height="65" src="<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo $opt_themes['no_img']['url']; } ?>" class="rounded " alt="<?php the_title(); ?>" > 
			 
			</div>
			<div class="app-info">
			<h3 class="h5 font-weight-semibold w-100 app-title"><?php if($opt_themes['app_name']){ if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); }} else { the_title(); } ?></h3>
			<div class="text-truncate text-muted app-desc">			
			<?php 
			if( $instance['show_mod']){ ?>
			<?php if(get_post_meta( $post->ID, 'wp_mods', true )) { ?>
			<span class="clamp-1 w-100"><?php echo trim(strip_tags(limit_words(get_post_meta( $post->ID, 'wp_mods', true ), '3'))) ?></span>
			<?php } else { ?><span class="clamp-1 w-100"> <?php echo $mod_gps_alt; ?></span><?php } ?>
			<?php } if( $instance['rate'] == 'none' ){
			} else if( $instance['rate'] == 'rate_gp' ){ ?>			
			<div class="Stars" style="--rating:<?php if($rate_GP){ echo $rate_GP; } else { ?>0<?php } ?>;" aria-label="Rating of this product is <?php if($rate_GP){ echo $rate_GP; } else { ?>0<?php } ?> out of 5">
			<?php if ($instance['show_count_rate']) { ?>
			<div class="rmp-results-widget__avg-rating"><span class="js-rmp-avg-rating"><?php echo $rate_GP; ?></span></div>
			<div class="rmp-results-widget__vote-count">(<span class="js-rmp-vote-count"><?php echo $ratings_GP; ?></span>)</div>
			<?php } ?>
			</div>			
			<?php } else if (shortcode_exists( 'ratemypost-result' )) { ?>
			<span class="byuser-sidebar pt-2 clamp-1 w-100"><?php echo do_shortcode( '[ratemypost-result]' ); ?> </span> 
			<?php } ?>
			</div>
			</div>
			<div class="app-get">
			<span class="get-button"><?php echo $opt_themes['mdr_text_get']; ?></span>
			<?php if($instance['show_version']){ ?><span class="app-version text-truncate"> <svg class="mr-1" xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" viewBox="0 0 16 16">
			<path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-7.5 3.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V11.5z"></path>
			</svg> <?php if (get_post_meta( $post->ID, 'wp_version_GP', true )) { echo trim(get_post_meta( $post->ID, 'wp_version_GP', true )); }   ?></span><?php } ?>
			</div>
			</a>
			</div>
			<?php
			break; 
			
			case 'liteapks':
			?> 
			<a class="text-body bg-white border rounded shadow-sm overflow-hidden d-block h-100 mb-3 position-relative archive-post" href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
			<div class="d-flex" style="padding: 0.75rem;">
			<div class="flex-shrink-0" style="width: 4rem; margin-right: 0.75rem;">
			 
			<img width="65" height="65" src="<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo $opt_themes['no_img']['url']; } ?>" class="rounded " alt="<?php the_title(); ?>" > 
			</div>
			<div style="min-width: 0;">
			<h3 class="h6 font-weight-semibold text-truncate w-100 mb-1"><?php if($opt_themes['app_name']){ if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); }} else { the_title(); } ?></h3>
			<div class="small text-truncate text-muted">
			<svg class="svg-6 svg-secondary mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M567.938 243.908L462.25 85.374A48.003 48.003 0 0 0 422.311 64H153.689a48 48 0 0 0-39.938 21.374L8.062 243.908A47.994 47.994 0 0 0 0 270.533V400c0 26.51 21.49 48 48 48h480c26.51 0 48-21.49 48-48V270.533a47.994 47.994 0 0 0-8.062-26.625zM162.252 128h251.497l85.333 128H376l-32 64H232l-32-64H76.918l85.334-128z"></path></svg>
			<span class="align-middle"><?php if (get_post_meta( $post->ID, 'wp_version_GP', true )) { echo trim(get_post_meta( $post->ID, 'wp_version_GP', true )); } ?></span>
			<?php if( $sizes){?>
			<span class="align-middle"> + </span>
			<span class="align-middle"><?php echo $sizes; ?></span>
			<?php } ?>
			</div>
			<div class="small text-truncate text-muted">
			<svg class="svg-6 svg-secondary mr-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M501.1 395.7L384 278.6c-23.1-23.1-57.6-27.6-85.4-13.9L192 158.1V96L64 0 0 64l96 128h62.1l106.6 106.6c-13.6 27.8-9.2 62.3 13.9 85.4l117.1 117.1c14.6 14.6 38.2 14.6 52.7 0l52.7-52.7c14.5-14.6 14.5-38.2 0-52.7zM331.7 225c28.3 0 54.9 11 74.9 31l19.4 19.4c15.8-6.9 30.8-16.5 43.8-29.5 37.1-37.1 49.7-89.3 37.9-136.7-2.2-9-13.5-12.1-20.1-5.5l-74.4 74.4-67.9-11.3L334 98.9l74.4-74.4c6.6-6.6 3.4-17.9-5.7-20.2-47.4-11.7-99.6.9-136.6 37.9-28.5 28.5-41.9 66.1-41.2 103.6l82.1 82.1c8.1-1.9 16.5-2.9 24.7-2.9zm-103.9 82l-56.7-56.7L18.7 402.8c-25 25-25 65.5 0 90.5s65.5 25 90.5 0l123.6-123.6c-7.6-19.9-9.9-41.6-5-62.7zM64 472c-13.2 0-24-10.8-24-24 0-13.3 10.7-24 24-24s24 10.7 24 24c0 13.2-10.7 24-24 24z"></path></svg>
			<span class="align-middle">
					
			<?php if (get_post_meta( get_the_ID(), 'wp_mods', true )) { ?>
			<?php _e($opt_themes['exthemes_MODAPK'], TEXT_DOMAIN); ?>&nbsp;<?php echo trim(strip_tags(limit_words(get_post_meta( $post->ID, 'wp_mods', true ), '3'))) ?>
			<?php } else { ?>	
			<?php
			$i = 0;
			foreach((get_the_category()) as $cat) {
			echo ''.$cat->cat_name.'';
			if (++$i == 1) break;
			}
			?>
			<?php } ?>	
			</span>
			</div>
			</div>
			</div>
			</a>
			
			<?php
			break;
			
			default:
			?>
			<div class="mb-4">
			<a class="d-flex position-relative archive-post" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
			<div class="flex-shrink-0 mr-2">
			<img width="65" height="65" src="<?php if (get_the_post_thumbnail( get_the_ID() )) { echo wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' )[0]; } elseif(get_post_meta( get_the_ID(), 'wp_poster_GP', true )) { echo get_post_meta( get_the_ID(), 'wp_poster_GP', true ); } else { echo $opt_themes['no_img']['url']; } ?>" class="rounded " alt="<?php the_title(); ?>" > 
			</div>
			<div style="min-width: 0;">
			<h3 class="h5 font-size-body font-weight-normal text-body text-truncate w-100 mb-1"><?php if($opt_themes['app_name']){ if(get_post_meta( get_the_ID(), 'wp_title_GP', true)){ echo get_post_meta( get_the_ID(), 'wp_title_GP', true); } else { the_title(); }} else { the_title(); } ?></h3>
			<div class="small text-truncate text-muted d-flex align-items-center">
			 
			<svg class="svg-4 align-middle mr-1" fill="var(--color_svg)" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M8 256C8 119 119 8 256 8s248 111 248 248-111 248-248 248S8 393 8 256zm292 116V256h70.9c10.7 0 16.1-13 8.5-20.5L264.5 121.2c-4.7-4.7-12.2-4.7-16.9 0l-115 114.3c-7.6 7.6-2.2 20.5 8.5 20.5H212v116c0 6.6 5.4 12 12 12h64c6.6 0 12-5.4 12-12z"></path></svg>
			<?php if (get_post_meta( $post->ID, 'wp_version', true )) { echo trim(get_post_meta( $post->ID, 'wp_version', true )); } else { echo trim(get_post_meta( $post->ID, 'wp_version_GP', true )); } ?>
			<span class="mx-1">·</span>
			<span class="text-truncate">
			
					
			<?php if (get_post_meta( get_the_ID(), 'wp_mods', true )) { ?>
			<?php _e($opt_themes['exthemes_MODAPK'], TEXT_DOMAIN); ?>&nbsp;<?php echo trim(strip_tags(limit_words(get_post_meta( $post->ID, 'wp_mods', true ), '3'))) ?>
			<?php } else { ?>	
			<?php
			$i = 0;
			foreach((get_the_category()) as $cat) {
			echo ''.$cat->cat_name.'';
			if (++$i == 1) break;
			}
			?>
			<?php } ?>	
			</span>
			</div>
			 
			</div>
			</a>
			</div>
			<?php
			break;
		} ?> 
		<?php endwhile; ?>

		<?php 
		wp_reset_postdata();	
		?>		
		</section>
		<?php 
		if( $instance['rate'] == 'rate' ){ if (!$instance['show_count_rate']) { ?>
		<style>.app-info .byuser-sidebar .rmp-results-widget__avg-rating, .app-info .byuser-sidebar .rmp-results-widget__vote-count {display: none;}</style>
		<?php }}
	}

	public function update( $new_instance, $old_instance ){
		$instance		= $old_instance;
		$new_instance	= wp_parse_args(
			(array) $new_instance,
			array(
			'title'			=> '',
			'title_button'		=> '',
			'title_link'		=> '',
			'category_ids'		=> array( 0 ),
			'number_posts'		=> 3,  
			'orderby'			=> 'date',
			'orderdate'			=> 'alltime',
			'days_amount'		=> 30,
			'rate'			=> 'none',			
			'show_mod'			=> false,
			'show_version'		=> false,
			'show_count_rate'	=> false,
			)
		); 
		$instance['title']			= sanitize_text_field( $new_instance['title'] );
		$instance['title_button']		= sanitize_text_field( $new_instance['title_button'] );
		$instance['title_link']			= $new_instance['title_link'];
		$instance['category_ids']		= array_map( 'absint', $new_instance['category_ids'] );
		$instance['number_posts']		= absint( $new_instance['number_posts'] );
		$instance['orderby']			= $new_instance['orderby'];
		$instance['orderdate']			= $new_instance['orderdate'];
		$instance['days_amount']		= (int) $new_instance['days_amount'];
		$instance['rate']			= $new_instance['rate'];
		$instance['show_mod']			= (bool) $new_instance['show_mod'];
		$instance['show_version']		= (bool) $new_instance['show_version'];
		$instance['show_count_rate']	= (bool) $new_instance['show_count_rate'];
		
		if( in_array( 0, $instance['category_ids'], true ) ){
			$instance['category_ids'] = array( 0 );
		}
		return $instance;
	}

	public function form( $instance ){
		$instance = wp_parse_args(
			(array) $instance,
			array(
			'title'			=> __( 'Popular Apk', THEMES_NAMES ),
			'title_button'		=> __( 'Get More...', THEMES_NAMES ),
			'title_link'		=> home_url( '/' ),
			'category_ids'		=> array( 0 ),
			'number_posts'		=> 3,  
			'orderby'			=> 'date',
			'orderdate'			=> 'alltime',
			'days_amount'		=> 30,
			'rate'			=> 'none',
			'show_mod'			=> true, 
			'show_version'		=> true,  
			'show_count_rate'	=> true, 
			)
		);
		$title			= sanitize_text_field( $instance['title'] );
		$title_button			= sanitize_text_field( $instance['title_button'] );
		$title_link		= $instance['title_link'];
		$category_ids			= array_map( 'absint', $instance['category_ids'] );
		$number_posts			= absint( $instance['number_posts'] );	
		$days_amount			= isset( $instance['days_amount'] ) ? absint( $instance['days_amount'] ) : 30;
 		$show_mod		= (bool) $instance['show_mod'];
		$show_version			= (bool) $instance['show_version'];
		$show_count_rate			= (bool) $instance['show_count_rate'];
		
		$categories		= get_categories(
			array(
			'hide_empty'		=> 0,
			'hierarchical'		=> 1,
			)
		);
		$number_of_cats			= count( $categories );
		$number_of_rows			= ( 10 > $number_of_cats ) ? $number_of_cats + 1 : 10;
		if( in_array( 0, $category_ids, true ) ){
			$category_ids			= array( 0 );
		}
		$selection_category			= sprintf(
			'<select name="%s[]" id="%s" class="cat-select widefat" multiple size="%d">',
			$this->get_field_name( 'category_ids' ),
			$this->get_field_id( 'category_ids' ),
			$number_of_rows
		);
		$selection_category .= "\n";

		$cat_list = array();
		if( 0 < $number_of_cats ){
			while( $categories ){
			if( 0 === $categories[0]->parent ){
		$current_entry = array_shift( $categories );
		$cat_list[] = array(
			'id'		=> absint( $current_entry->term_id ),
			'name'		=> esc_html( $current_entry->name ),
			'depth'		=> 0,
		);
		continue;
			}
			
			$parent_index = $this->get_cat_parent_index( $cat_list, $categories[0]->parent );
			if( false === $parent_index ){
		$current_entry = array_shift( $categories );
		$categories[] = $current_entry;
		continue;
			}

			$depth = $cat_list[ $parent_index ]['depth'] + 1;
			$new_index = $parent_index + 1;
			foreach( $cat_list as $entry ){
		if( $depth <= $entry['depth'] ){
			$new_index = $new_index++;
			continue;
		}

		$current_entry = array_shift( $categories );
		$end_array  = array_splice( $cat_list, $new_index );
		$cat_list[] = array(
			'id'    => absint( $current_entry->term_id ),
			'name'  => esc_html( $current_entry->name ),
			'depth' => $depth,
		);
		$cat_list   = array_merge( $cat_list, $end_array );
		break;
			} 
			} 

			$selected            = ( in_array( 0, $category_ids, true ) ) ? ' selected="selected"' : '';
			$selection_category .= "\t";
			$selection_category .= '<option value="0"' . $selected . '>' . __( 'All Categories', THEMES_NAMES ) . '</option>';
			$selection_category .= "\n";
			foreach( $cat_list as $category ){
			$cat_name            = apply_filters( 'gmr_list_cats', $category['name'], $category );
			$pad                 = ( 0 < $category['depth'] ) ? str_repeat( '&ndash;&nbsp;', $category['depth'] ) : '';
			$selection_category .= "\t";
			$selection_category .= '<option value="' . $category['id'] . '"';
			$selection_category .= ( in_array( $category['id'], $category_ids, true ) ) ? ' selected="selected"' : '';
			$selection_category .= '>' . $pad . $cat_name . '</option>';
			$selection_category .= "\n";
			}
		}

		$selection_category .= "</select>\n";
		?>
		<p class="info-notice danger"><?php _e( 'Sidebar Post by Popular post', THEMES_NAMES ); ?> </p>
		<hr />
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:', THEMES_NAMES ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>
		<hr />
		
		<p>
            <label for="<?php echo esc_html( $this->get_field_id( 'title_button' ) ); ?>"><?php _e( 'Title Button:', THEMES_NAMES ); ?></label>
            <input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title_button' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'title_button' ) ); ?>" type="text" value="<?php echo esc_attr( $title_button ); ?>" />
        </p>
		<p >
			<label for="<?php echo esc_html( $this->get_field_id( 'title_link' ) ); ?>"><?php _e( 'Link Url:', THEMES_NAMES ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title_link' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'title_link' ) ); ?>" type="url" value="<?php echo $title_link; ?>" />
			<br />
			<small><?php _e( 'Target url for title', THEMES_NAMES ); ?> (example: <?php echo home_url( '/' ); ?>), <?php _e( 'leave blank if you want using title without link.', THEMES_NAMES ); ?></small>
		</p>
		<hr />
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'category_ids' ) ); ?>"><?php _e( 'Selected categories', THEMES_NAMES ); ?></label>
			<?php echo $selection_category;  ?>
			<br />
			<small><?php _e( 'Click on the categories with pressed CTRL key to select multiple categories. If All Categories was selected then other selections will be ignored.', THEMES_NAMES ); ?></small>
		</p>
		<hr />
		<p>
			<label for="<?php echo esc_html( $this->get_field_id( 'number_posts' ) ); ?>"><?php _e( 'Number post', THEMES_NAMES ); ?></label>
			<input class="widefat" id="<?php echo esc_html( $this->get_field_id( 'number_posts' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'number_posts' ) ); ?>" type="number" value="<?php echo esc_attr( $number_posts ); ?>" />
		</p>  
		<hr />
		<p>
			<label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e('Mode:', THEMES_NAMES) ?> </label>
			<select id="<?php echo $this->get_field_id('orderby'); ?>" name="<?php echo $this->get_field_name('orderby'); ?>">
			<option <?php if ($instance['orderby'] == 'date') echo 'selected="selected"'; ?> value="date"><?php _e('Recent Posts', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderby'] == 'rand') echo 'selected="selected"'; ?> value="rand"><?php _e('Random Posts', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderby'] == 'modified') echo 'selected="selected"'; ?> value="modified"><?php _e('Recent Modified date', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderby'] == 'views') echo 'selected="selected"'; ?> value="views"><?php _e('Post views', THEMES_NAMES); ?></option>			
			<option <?php if ($instance['orderby'] == 'rate') echo 'selected="selected"'; ?> value="rate"><?php _e('Post Rate by User (Just Working For Reborns Styles)', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderby'] == 'rategps') echo 'selected="selected"'; ?> value="rategps"><?php _e('Post Rate by Play Store (Just Working For Reborns Styles)', THEMES_NAMES); ?></option>			
			</select>
		</p>
		<hr />
		<div class="mdn-select-day">
		<p>
			<label for="<?php echo $this->get_field_id('orderdate'); ?>"><?php _e('Date:', THEMES_NAMES) ?> </label>
			<select id="<?php echo $this->get_field_id('orderdate'); ?>" name="<?php echo $this->get_field_name('orderdate'); ?>">
			<option <?php if ($instance['orderdate'] == 'alltime') echo 'selected="selected"'; ?> value="alltime"><?php _e('All Time', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderdate'] == 'pastyear') echo 'selected="selected"'; ?> value="pastyear"><?php _e('Past Year', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderdate'] == 'pastmonth') echo 'selected="selected"'; ?> value="pastmonth"><?php _e('Past Month', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderdate'] == 'pastweek') echo 'selected="selected"'; ?> value="pastweek"><?php _e('Past Week', THEMES_NAMES); ?></option>
			<option <?php if ($instance['orderdate'] == 'bydays') echo 'selected="selected"'; ?> value="bydays"><?php _e('Last "X" days', THEMES_NAMES); ?></option>
			</select>
		</p>
		<p class="mdn-days <?php echo $this->get_field_id('orderdate'); ?> <?php if ($instance['orderdate'] != 'bydays') echo 'hidden'; ?>">
			<label for="<?php echo $this->get_field_id('days_amount'); ?>"><?php _e( 'Number of last days to filter:', THEMES_NAMES); ?></label>
			<input id="<?php echo $this->get_field_id('days_amount'); ?>" name="<?php echo $this->get_field_name('days_amount'); ?>" type="text" value="<?php echo $days_amount; ?>" size="1" />
		</p>
		</div>
		<hr />		
		<p>
			<label for="<?php echo $this->get_field_id('rate'); ?>"><?php _e('Show Rate:', THEMES_NAMES) ?> </label>
			<select id="<?php echo $this->get_field_id('rate'); ?>" name="<?php echo $this->get_field_name('rate'); ?>">
			<option <?php if ($instance['rate'] == 'none') echo 'selected="selected"'; ?> value="none"><?php _e('disable', THEMES_NAMES); ?></option>
			<option <?php if ($instance['rate'] == 'rate') echo 'selected="selected"'; ?> value="rate"><?php _e('Rate by user', THEMES_NAMES); ?></option> 
			<option <?php if ($instance['rate'] == 'rate_gp') echo 'selected="selected"'; ?> value="rate_gp"><?php _e('Rate by PlayStore', THEMES_NAMES); ?></option> 
			</select>
		</p>
		<p><?php _e('Just Working For Reborns Styles', THEMES_NAMES); ?> </p>
		<hr />		
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $show_mod ); ?> id="<?php echo esc_html( $this->get_field_id( 'show_mod' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'show_mod' ) ); ?>" /><label for="<?php echo esc_html( $this->get_field_id( 'show_mod' ) ); ?>"><?php _e( 'Show Mod ?', THEMES_NAMES ); ?></label>
		</p>
		<p><?php _e('Just Working For Reborns Styles', THEMES_NAMES); ?> </p>
		<hr />
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $show_version ); ?> id="<?php echo esc_html( $this->get_field_id( 'show_version' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'show_version' ) ); ?>" /><label for="<?php echo esc_html( $this->get_field_id( 'show_version' ) ); ?>"><?php _e( 'Show Version ?', THEMES_NAMES ); ?></label>
		</p>
		<p><?php _e('Just Working For Reborns Styles', THEMES_NAMES); ?> </p>
		<hr />		
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $show_count_rate ); ?> id="<?php echo esc_html( $this->get_field_id( 'show_count_rate' ) ); ?>" name="<?php echo esc_html( $this->get_field_name( 'show_count_rate' ) ); ?>" /><label for="<?php echo esc_html( $this->get_field_id( 'show_count_rate' ) ); ?>"><?php _e( 'Show Count Rate ?', THEMES_NAMES ); ?></label>
		</p>
		<p><?php _e('Just Working For Reborns Styles', THEMES_NAMES); ?> </p>
		<hr />
		
		
		<script>
			(function($){
			$(document).ready(function(){
			$('.mdn-select-day').each(function(){
		var container = $(this);
		container.find('select').on('change', function(){
			var value = $(this).val();
			if( value == 'bydays' ){
			container.find('.mdn-days').show();
			}else{
			container.find('.mdn-days').hide();
			}
		});
			});
			});
		})(jQuery);
		</script>
        
		<?php
	}
	
	private function get_cat_parent_index( $arr, $id ){
		$len = count( $arr );
		if( 0 === $len ){
			return false;
		}
		$id = absint( $id );
		for( $i = 0; $i < $len; $i++ ){
			if( $id === $arr[ $i ]['id'] ){
			return $i;
			}
		}
		return false;
	}
	
}
add_action(	'widgets_init',	function(){	register_widget( 'ex_themes_most_views_' );	});
