<?php

/***** Latest Post Widget *****/

class vt_latest_posts_widget extends WP_Widget {
	# New object.
	function __construct() {
		$widget_ops = array(
			  'classname'   => 'vt-posts-widget'
			, 'description' => esc_html__( 'Displays the latest posts with post thumbnail.', 'vt-grid-mag' )
		);
		parent::__construct( 'vt_latest_posts_widget', esc_html__( '[VT] Latest Posts', 'vt-grid-mag' ), $widget_ops );
	}

	# Output.
	function widget( $args, $instance ) {
		$args  = wp_parse_args( (array) $args, array( 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '' ) );

		$instance  = (array) $instance;
		$title     = empty( $instance['title'] )    ? esc_html__('Latest', 'vt-grid-mag') : apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base );
		$count     = empty( $instance['count'] )    ? 5                                : $instance['count'];
		$cat       = empty( $instance['category'] ) ? ''                               : $instance['category'];
		$order     = empty( $instance['order'] )    ? 'DESC'                           : $instance['order'];
		$orderby   = empty( $instance['orderby'] )  ? 'date'                           : $instance['orderby'];
		$new_posts = new WP_Query( array(
			  'post_status' => 'publish'
			, 'post_type'   => 'post'
			, 'ignore_sticky_posts' => true
			, 'posts_per_page'      => $count
			, 'cat'                 => $cat
			, 'order'               => $order
			, 'orderby'             => $orderby
		) );
		
		if( $new_posts->have_posts() ) {
			echo $args['before_widget'];

				if( $title ) {
					echo $args['before_title'] . $title . $args['after_title'];
				}

				echo '<ul>';

					while ( $new_posts->have_posts() ) {
						$new_posts->the_post();

						echo '<li><div class="item clearfix">';
						
							// thumbnail
							if( has_post_thumbnail() ) {
								printf('<a href="%1$s" class="thumb-link">%2$s</a>', esc_url( get_permalink() ), get_the_post_thumbnail( get_the_ID(), 'vt-grid-mag-cp-small' ) );
							} else { 
								echo '<img class="thumb-link" src="' . get_template_directory_uri() . '/images/no-thumbnail.png' . '" alt="No Picture" />'; 
								} 

							 echo '<div class="item-content">';
							// title.
							the_title( '<h5><a href="'.esc_url( get_permalink() ).'">', '</a></h5>' );

							// date.
							if( ! vt_grid_mag('hide_post_date') ) {
								printf('<span class="post-date">%s</span>'
									, sprintf( _x( '%s ago', '%s = human-readable time difference', 'vt-grid-mag' )
											, human_time_diff( get_the_time( 'U' )
											, current_time( 'timestamp' ) ) 
										)
								);
							}

						echo '</div>';

						echo '</div></li>';
					}
					
					wp_reset_postdata();

				echo '</ul>';

			echo $args['after_widget'];
		}

	}

	# Input.
	function form( $instance ) {
		$defaults = array(
			  'title'    => esc_html__('Latest', 'vt-grid-mag')
			, 'count'    => 5
			, 'category' => ''
			, 'order'    => 'DESC'
			, 'orderby'  => 'date'
		);
		$_categories = self::categories_output();
		$instance    = wp_parse_args( (array) $instance, $defaults );

		?>

		<p>
			<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php esc_html_e( 'Title:', 'vt-grid-mag' ); ?></label>
			<input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php if(!empty($instance['title'])) { echo esc_attr($instance['title'] ); } ?>" class="widefat" type="text" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'count' ); ?>"><?php esc_html_e( 'Number of posts to show:', 'vt-grid-mag' ); ?></label>
			<input id="<?php echo $this->get_field_id( 'count' ); ?>" name="<?php echo esc_attr($this->get_field_name( 'count' ) ); ?>" type="text" value="<?php echo esc_attr($instance['count'] ); ?>" size="3" />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('category'); ?>"><?php esc_html_e( 'Category:', 'vt-grid-mag' ); ?></label>

			<select name="<?php echo $this->get_field_name('category'); ?>" id="<?php echo $this->get_field_id('category'); ?>" class="widefat">
				<?php
					foreach( (array) $_categories as $cat_id => $name ) {
						echo '<option value="'. esc_attr($cat_id).'"'. selected( $instance['category'], $cat_id, false ) .'>'. $name .'</option>';
					}
				?>

			</select>
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('order'); ?>"><?php esc_html_e( 'Order:', 'vt-grid-mag' ); ?></label>

			<select name="<?php echo $this->get_field_name('order'); ?>" id="<?php echo $this->get_field_id('order'); ?>" class="widefat">
				<option value="ASC"<?php selected( $instance['order'], 'ASC' ); ?>><?php esc_html_e( 'Ascending', 'vt-grid-mag' ); ?></option>
				<option value="DESC"<?php selected( $instance['order'], 'DESC' ); ?>><?php esc_html_e( 'Descending ', 'vt-grid-mag' ); ?></option>
			</select>
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e( 'Orderby:', 'vt-grid-mag' ); ?></label>

			<select name="<?php echo $this->get_field_name('orderby'); ?>" id="<?php echo $this->get_field_id('orderby'); ?>" class="widefat">
				<option value="date"<?php selected( $instance['orderby'], 'date' ); ?>><?php esc_html_e( 'Order by date', 'vt-grid-mag' ); ?></option>
				<option value="ID"<?php selected( $instance['orderby'], 'ID' ); ?>><?php esc_html_e( 'Order by post id', 'vt-grid-mag' ); ?></option>
				<option value="title"<?php selected( $instance['orderby'], 'title' ); ?>><?php esc_html_e( 'Order by title', 'vt-grid-mag' ); ?></option>
				<option value="comment_count"<?php selected( $instance['orderby'], 'comment_count' ); ?>><?php esc_html_e( 'Order by number of comments', 'vt-grid-mag' ); ?></option>
				<option value="rand"<?php selected( $instance['orderby'], 'rand' ); ?>><?php esc_html_e( 'Random order', 'vt-grid-mag' ); ?></option>
			</select>
		</p>

		<?php
	}

	# Update.
	function update( $new_instance, $old_instance ) {
		$new_instance         = (array) $new_instance;
		$instance             = (array) $old_instance;
		$defaults             = array(
			  'title'         => ''
			, 'count'         => 5
			, 'category'      => ''
			, 'order'         => 'DESC'
			, 'orderby'       => 'date'
		);
		$new_instance         = wp_parse_args( $new_instance, $defaults );
		$instance['title']    = strip_tags( $new_instance['title'] ) ? sanitize_text_field( $new_instance['title'] ) : '';
		$instance['count']    = strip_tags( intval( $new_instance['count'] ) );
		$instance['category'] = strip_tags( intval( $new_instance['category'] ) );
		$instance['order']    = in_array( $new_instance['order'], array('ASC', 'DESC') )                                      ? $new_instance['order']   : 'DESC';
		$instance['orderby']  = in_array( $new_instance['orderby'], array( 'date', 'ID', 'title', 'comment_count', 'rand' ) ) ? $new_instance['orderby'] : 'date';

		return $instance;
	}

	# Categories.
	function categories_output() {
		$categories = get_categories( array( 'hide_empty' => 1 ) );
		$output     = array();
		$output[''] = esc_html__('&mdash; All &mdash;', 'vt-grid-mag');
		foreach( $categories as $cat ) {
			$output[$cat->term_id] = $cat->name;
		}

		return $output;
	}
}