<?php
class Recentposts extends WP_Widget {
	function __construct() {
		parent::__construct(
			'recentposts',
			esc_html__( 'Prestasi : Pos Terbaru', 'prestasi' ),
			array( 'description' => esc_html__( 'Widget Ini Digunakan Untuk Menampilkan Pos Terbaru', 'prestasi' ), 'customize_selective_refresh' => true, )
		);
	}

	public function widget( $args, $instance ) {
		if ( ! isset( $args['widget_id'] ) ) {
			$args['widget_id'] = $this->id;
		}

		$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : __( 'Pos Terbaru' );

		/** This filter is documented in wp-includes/widgets/class-wp-widget-pages.php */
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
		
		$post_baru = ( ! empty( $instance['post_baru'] ) ) ? absint( $instance['post_baru'] ) : 3;
		if ( ! $post_baru ) {
			$post_baru = 3;
		}
		
		$q_args = array( 
			'post_type' => 'post', 
			'numberposts' => $post_baru,
			); 
			
		global $post;
		$rpthumb_posts = get_posts($q_args);
		
		echo $args['before_widget']; 
		
		if ( $title ) {
			echo $args['before_title'] . $title . $args['after_title'];
		}
		
		foreach ($rpthumb_posts as $post):
			setup_postdata($post);
		?>
        <div class="post_widget clear">
	    	<div class="widget_thumb">
		        <?php 
				    if (has_post_thumbnail()) {
			            the_post_thumbnail('small');
		            }
		        ?>
		    </div>
		    <div class="post_wadd">
			    <span class="post_wplus"><em><?php the_time(); ?></em></span>
		        <div class="post_wtitle"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
		    </div>
        </div>
	<?php	endforeach;
		
		echo $args['after_widget'];
	}


	public function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = sanitize_text_field( $new_instance['title'] );
		$instance['post_baru'] = sanitize_text_field( $new_instance['post_baru'] );
		return $instance;
	}
		
		
	public function form( $instance ) {
		$title     = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : 'Pos Terbaru';
		$post_baru     = isset( $instance['post_baru'] ) ? esc_attr( $instance['post_baru'] ) : 3; ?>
		<p><?php _e( 'Widget Ini Digunakan Untuk Menampilkan Daftar Pos Terbaru Terbaru di Sidebar' ); ?><br/></p>
		<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title :' ); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /></p>
		
		<p><label for="<?php echo $this->get_field_id( 'post_baru' ); ?>"><?php _e( 'Jumlah Pos :' ); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'post_baru' ); ?>" name="<?php echo $this->get_field_name( 'post_baru' ); ?>" type="number" value="<?php echo $post_baru; ?>" /></p>

    <?php
	}
}