<?php

if ( !defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly


class Thim_Recent_Posts_Widget extends WP_Widget {

	function __construct() {
		parent::__construct(
		// Base ID of your widget
			'thim_recent_posts_widget',

			// Widget name will appear in UI

			esc_html__( 'Thim: Recent Posts', 'cakeart' ),


// Widget description
			array( 'description' => esc_html__( 'display recent posts with thumbnails of theme', 'cakeart' ), ) );
	}

// Creating widget front-end
	public function widget( $args, $instance ) {
		echo '<div class="recent-posts">';
		echo '<h3 class="widget-title">' . esc_html( $instance['title'] ) . '</h3>';
		$args  = array(
			'posts_per_page' => $instance['number'],

		);
		$posts = get_posts( $args );

		foreach ( $posts as $post ) : setup_postdata( $post )
			?>

			<div class="row">
				<div class="col-md-3 col-sm-4 col-xs-3">
					<a href="<?php echo esc_url( get_permalink( $post ) ); ?>"><?php echo get_the_post_thumbnail( $post->ID, 'thumbnail' ); ?></a>
				</div>
				<div class="col-md-9 col-sm-8 col-xs-9">
					<p class="title">
						<a href="<?php echo esc_url( get_permalink( $post ) ); ?>"><?php echo esc_attr( $post->post_title ); ?></a>
					</p>

					<p><?php echo get_the_date( 'M d,Y', $post->ID ); ?></p>
				</div>
			</div>

		<?php
		endforeach;

		wp_reset_postdata();

		echo '</div>';
	}

// Widget Backend
	public function form( $instance ) {
		if ( isset( $instance['title'] ) ) {
			$title = $instance['title'];
		} else {
			$title = '';
		}
		if ( isset( $instance['title'] ) ) {
			$number = $instance['number'];
		} else {
			$number = '2';
		}

// Widget admin form
		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'The title:', 'cakeart' ); ?></label>

			<input id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>
		<p>

			<label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php esc_html_e( 'Number of posts to show:', 'cakeart' ); ?></label>

			<input id="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" type="number" value="<?php echo esc_attr( $number ); ?>" />
		</p>
	<?php
	}


// Updating widget replacing old instances with new
	public function update( $new_instance, $old_instance ) {
		$instance           = array();
		$instance['title']  = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
		$instance['number'] = ( !empty( $new_instance['number'] ) ) ? strip_tags( $new_instance['number'] ) : 1;
		return $instance;
	}

}

// Register and load the widget
function thim_recent_posts_load_widget() {
	register_widget( 'Thim_Recent_Posts_Widget' );
}

add_action( 'widgets_init', 'thim_recent_posts_load_widget' );
