<?php

class Popular_Posts extends WP_Widget {

	/**
	 * Sets up the widgets name etc
	 */
	public function __construct() {
		$params = array(
      'classname' => 'popular_posts',
      'description' => 'Display popular posts for Prime Theme',
		);
		parent::__construct( 'popular_posts', 'PT Popular posts', $params );
	}

	/**
	 * Outputs the content of the widget
	 *
	 * @param array $args
	 * @param array $instance
	 */
	public function widget( $args, $instance ) {
		extract($args);
		extract($instance);
		$count = 0;

		echo $before_widget;
    echo $before_title. $instance['title'] .$after_title;

		query_posts('&meta_key=post_views_count&orderby=meta_value_num&order=DESC');
		if(have_posts()): while (have_posts() && $post_count != $count): the_post();
			?>
			<div class="pp-container">
				<div class="pp-thumb"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></div>
				<li class="pp-title"><a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a></li>
				<div class="pp-meta"><?php prime_theme_posted_on();?></div>
				<div class="pp-comment">
					<?php
					if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) {
						echo '<span class="comments-link"><i class="fa fa-comment" aria-hidden="true"></i>';
						comments_popup_link( __( 'Leave a comment', 'prime-theme' ), __( '1 Comment', 'prime-theme' ), __( '% Comments', 'prime-theme' ) );
						echo '</span>';
					}
					?>
				</div>
			</div>
			<?php
			$count++;
		endwhile; endif;
		wp_reset_query();
		echo $after_widget;
	}

	/**
	 * Outputs the options form on admin
	 *
	 * @param array $instance The widget options
	 */
	public function form( $instance ) {
		extract($instance);
		?>
						<p>
                <label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
                <input class="widefat"
                id="<?php echo $this->get_field_id('title'); ?>"
                name="<?php echo $this->get_field_name('title'); ?>"
                value="<?php if( isset($title) ) echo esc_attr($title); ?>">
            </p>
						<p>
                <label for="<?php echo $this->get_field_id('post_count'); ?>">Number of Posts:</label>
                <input class="widefat" type="number" min="0" max="10" style="width:40px;"
                id="<?php echo $this->get_field_id('post_count'); ?>"
                name="<?php echo $this->get_field_name('post_count'); ?>"
                value="<?php echo !empty($post_count) ? $post_count : 5; ?>" />
            </p>
		<?php
	}
}

add_action( 'widgets_init', function(){
	register_widget( 'Popular_Posts' );
});

 ?>
