<?php

add_action( 'widgets_init', 'wp_superlike_topliked_init' );
function wp_superlike_topliked_init() { register_widget( 'wp_superlike_topliked' ); }

class wp_superlike_topliked extends WP_Widget {

	function wp_superlike_topliked() {
		$widget_ops = array( 'classname' => 'wp_superlike_topliked', 'description' => __('Display the top liked posts in a widget.', 'wp_superlike') );
		
		$control_ops = array( 'width' => 300, 'height' => 200, 'id_base' => 'wp_superlike_topliked_widget' );
		
		$this->WP_Widget( 'wp_superlike_topliked_widget', __('GAMELEON: SuperLike - Top Liked Posts', 'wp_superlike'), $widget_ops, $control_ops );
	}

	function widget( $args, $instance ) {
		extract( $args );
		global $wp_superlike;

		//Our variables from the widget settings.
		$title = apply_filters('widget_title', $instance['title'] );
		$limit = $instance['limit'];
		
		// Display widget
		echo $before_widget . $before_title . $title . $after_title;
		
		/**
		**
		**/
		$the_query = new WP_Query( array(
			'post_type' => get_post_types(),
			'meta_key' => 'wp_superlike_count',
			'orderby' => 'meta_value_num',
			'order' => 'DESC',
			'posts_per_page' => $limit
		) );
		echo '<ol>';
		while ( $the_query->have_posts() ) :
			$the_query->the_post();
			printf(__('<li><a href="%s">%s</a><span>Likes: %s</span></li>','wp_superlike'),
			get_permalink(get_the_ID()),
			 get_the_title(),
			 $wp_superlike->get_likes(get_the_ID())
			);
		endwhile;
		echo '</ol>';
		wp_reset_postdata();
		
		echo $after_widget;

	}

	//Update the widget
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		//Strip tags from title and name to remove HTML
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['limit'] = $new_instance['limit'];

		return $instance;
	}

	function form( $instance ) {

		//Set up some default widget settings.
		$defaults = array( 'title' => __('Top 5 Liked Posts','wp_superlike'), 'limit' => 5 );
		$instance = wp_parse_args( (array) $instance, $defaults ); ?>

		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'ocart'); ?></label>
			<input type="text" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" class="widefat" />
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id( 'limit' ); ?>"><?php _e('Number of posts to show:', 'ocart'); ?></label>
			<input type="text" id="<?php echo $this->get_field_id( 'limit' ); ?>" name="<?php echo $this->get_field_name( 'limit' ); ?>" value="<?php echo $instance['limit']; ?>" class="widefat" />
		</p>

	<?php
	}
}