<?php
/**
 * Ef Practical Recent Posts Widget.
 *
 * @package Ef Practical
 */

/**
 * Widget class.
 */
if ( ! class_exists( 'Practical_Recent_Posts_Widget' ) ) {
	class Practical_Recent_Posts_Widget extends WP_Widget {
        
		private $defaults;
		
		/**
		 * Register widget
		 */
		public function __construct() {
			
			// Defaults
			$this->defaults = array(
				'title'         => esc_html__( 'Recent Posts', 'ef-practical' ),
				'number'        => '5',
				'post_type'     => 'post',
				'order'         => 'DESC',
				'orderby'       => 'date',
				'date'          => '',
				'thumb'         => '',
				'excerpt'       => '',
			);
            
            $widget_ops = array(
                'classname'   => 'ef_recent_posts_widget',
                'description' => esc_html__( 'Display recent posts.', 'ef-practical' ),
            );
            parent::__construct( 'practical_recent_posts_widget', esc_html__( 'Practical: Recent Posts', 'ef-practical' ), $widget_ops );
		}
		
		/**
         * Output the content
		 */
		public function widget( $args, $instance ) {
            
			extract( wp_parse_args( $instance, $this->defaults ) );
            
			// Define output var
			$output = '';
			$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
			$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
            
			// Before widget
			$output .= $args['before_widget'];
            
			// Query posts
			$query_args = array(
				'post_type' 		  => 'post',
				'posts_per_page'   	  => $number,
				'no_found_rows'  	  => true,
				'post_status' 		  => 'publish', 
				'ignore_sticky_posts' => true,
			);
			
			// Current post exclude
			if ( is_singular() ) {
				$query_args['post__not_in'] = array( get_the_ID() );
			}
			
			// Order / orderby
			if ( ! empty( $orderby ) ) {
				$query_args['order']   = $order;
				$query_args['orderby'] = $orderby;
			} else {
				$query_args['orderby'] = $order; // fallback
			}
            
			// Query posts
			$ef_query = new WP_Query( $query_args );
			if ( $ef_query->have_posts()) :
            
			// Widget title
			if ( $title ) {
				$output .= $args['before_title'];
					$output .= $title;
				$output .= $args['after_title'];
			}
            
            $output .= '<ul class="ef-recent-entries">';
                
                while ( $ef_query->have_posts() ) : $ef_query->the_post();
                    
                    $output .= '<li>';
                    if ( 'on' != $thumb && has_post_thumbnail() ) {
                        $output .= '<div class="ef-recent-entries-thumb">';
                        $output .= get_the_post_thumbnail(get_the_ID(), 'full'); 
                        $output .= '</div>';
                    }
                    
                    $output .= '<div class="ef-recent-entries-body">';
                    
                    $output .= '<h5 class="ef-recent-entry-title"><a href="' . esc_url ( get_the_permalink() ) . '" title="'. esc_attr ( get_the_title() ) .'">';
                    $output .= get_the_title();
                    $output .= '</a></h5>';
                    
                    // date
                    if ( 'on' != $date ) {
                        $output .= '<div class="ef-recent-entries-date">' .  get_the_date() . '</div>';
                    }
                    
                    // excerpt
                    if ( 'on' != $excerpt ) {
                        $output .= '<div class="ef-recent-entries-excerpt">';
                            $content = wp_trim_words( get_the_excerpt(), 12, '...' );
                            $content = preg_replace( '/\[[^\]]+\]/', '', $content );
                            $output .= $content;
                        $output .= '</div>';						
                    }
                    
                    $output .= '</div>';
                    
                    $output .= '</li>';
                    
                endwhile; 
                
            $output .= '</ul>';
            
            wp_reset_postdata();
			endif;
			// output ends
            
			// After widget
			$output .= $args['after_widget'];
            
			// output echo
			echo $output; // WPCS: XSS ok.
            
		} 
        
		/**
		 *  Update the information in the WordPress database
		 */	
		public function update( $new_instance, $old_instance ) {
			$instance            = $old_instance;
			$instance['title']   = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
			$instance['number']  = ! empty( $new_instance['number'] ) ? absint( $new_instance['number'] ) : '';
			$instance['order'] 	 = ! empty( $new_instance['order'] ) ? sanitize_text_field( $new_instance['order'] ) : '';
			$instance['orderby'] = ! empty( $new_instance['orderby'] ) ? sanitize_text_field( $new_instance['orderby'] ) : '';
			$instance['date']	 = isset( $new_instance['date'] ) ? true : false;
			$instance['thumb'] 	 = isset( $new_instance['thumb'] ) ? true : false;
			$instance['excerpt'] = isset( $new_instance['excerpt'] ) ? true : false;
			return $instance;
		} 
        
		/**
		 * Add form fields to the widget which will be displayed in the WordPress admin area.
		 */
		public function form( $instance ) {
			extract( wp_parse_args( ( array ) $instance, $this->defaults ) ); ?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
                <?php esc_attr_e( 'Title', 'ef-practical' ); ?>
            </label>
            <input class="widefat" 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( 'order' ) ); ?>">
                <?php esc_html_e( 'Order', 'ef-practical' ); ?>
            </label>
            <br>
            <select name="<?php echo esc_attr( $this->get_field_name( 'order' ) ); ?>">
                <option value="DESC" <?php selected( $order, 'DESC', true ); ?>>
                    <?php esc_html_e( 'Descending', 'ef-practical' ); ?>
                </option>
                <option value="ASC" <?php selected( $order, 'ASC', true ); ?>>
                    <?php esc_html_e( 'Ascending', 'ef-practical' ); ?>
                </option>
            </select>
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'orderby' ) ); ?>">
                <?php esc_html_e( 'Order By', 'ef-practical' ); ?>
                :</label>
            <br>
            <select name="<?php echo esc_attr( $this->get_field_name( 'orderby' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'orderby' ) ); ?>">
                <?php
                    // Orderby options
                    $orderby_array = array (
                        'date'          => esc_html__( 'Date', 'ef-practical' ),
                        'title'         => esc_html__( 'Title', 'ef-practical' ),
                        'rand'          => esc_html__( 'Random', 'ef-practical' ),
                        'author'        => esc_html__( 'Author', 'ef-practical' ),
                        'comment_count' => esc_html__( 'Comment Count', 'ef-practical' ),
                    );
                foreach ( $orderby_array as $key => $value ) { ?>
                    <option value="<?php echo esc_attr( $key ); ?>" <?php selected( $orderby, $key ); ?>> <?php echo esc_html( strip_tags( $value ) ); /* WPCS: xss ok. */ ?> </option>
                <?php } ?>
            </select>
        </p>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>">
                <?php esc_html_e( 'Number', 'ef-practical' ); ?>
            </label>
            <input class="widefat" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" type="text" value="<?php echo esc_attr( $number ); ?>" />
        </p>
        <p>
            <input name="<?php echo esc_attr( $this->get_field_name( 'date' ) ); ?>" type="checkbox" value="1" <?php checked( $date, '1', true ); ?> />
            <label for="<?php echo esc_attr( $this->get_field_id( 'date' ) ); ?>">
                <?php esc_html_e( 'Hide Date', 'ef-practical' ); ?>
            </label>
        </p>
        <p>
            <input name="<?php echo esc_attr( $this->get_field_name( 'thumb' ) ); ?>" type="checkbox" value="1" <?php checked( $thumb, '1', true ); ?> />
            <label for="<?php echo esc_attr( $this->get_field_id( 'thumb' ) ); ?>">
                <?php esc_html_e( 'Hide Image', 'ef-practical' ); ?>
            </label>
        </p>
        <p>
            <input name="<?php echo esc_attr( $this->get_field_name( 'excerpt' ) ); ?>" type="checkbox" value="1" <?php checked( $excerpt, '1', true ); ?> />
            <label for="<?php echo esc_attr( $this->get_field_id( 'excerpt' ) ); ?>">
                <?php esc_html_e( 'Hide Excerpt', 'ef-practical' ); ?>
            </label>
        </p>
        <?php
		} 
	}
}