<?php
// Adds widget: Book Review Blog Latest Posts
class Book_Review_Blog_Latest_Posts_Widget extends WP_Widget {

	function __construct() {
		parent::__construct(
			'book_review_blog_latest_posts',
			esc_html__( '[Book Review Blog] Latest Posts', 'book-review-blog' )
		);
		$this->widget_fields = array(
			array(
				'label' => esc_html__( 'Posts Per Page', 'book-review-blog' ),
				'id' => 'postsperpage',
				'default' => '4',
				'type' => 'number',
			),
			array(
				'label' => esc_html__( 'Show Post Date', 'book-review-blog' ),
				'id' => 'showpostdate',
				'default' => '1',
				'type' => 'checkbox',
			),
			array(
				'label' => esc_html__( 'Category', 'book-review-blog' ),
				'id' => 'category',
				'default' => '',
				'type' => 'select',
				'options' => $this->get_category_options(),
			),
			array(
				'label' => esc_html__( 'Show Excerpt', 'book-review-blog' ),
				'id' => 'showexcerpt',
				'default' => '',
				'type' => 'checkbox',
			),
			array(
				'label' => esc_html__( 'Excerpt Length (words)', 'book-review-blog' ),
				'id' => 'excerptlength',
				'default' => '20',
				'type' => 'number',
			),
			array(
				'label' => esc_html__( 'Show Post Author', 'book-review-blog' ),
				'id' => 'showpostauthor',
				'default' => '',
				'type' => 'checkbox',
			),
		);
	}

	private $widget_fields;

	private function get_category_options() {
		$categories = get_categories();
		$options = array( '' => esc_html__( 'All Categories', 'book-review-blog' ) );
		foreach ( $categories as $category ) {
			$options[$category->term_id] = $category->name;
		}
		return $options;
	}

	public function widget( $args, $instance ) {
		echo $args['before_widget'];

		if ( ! empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
		}

		$posts_per_page = ! empty( $instance['postsperpage'] ) ? absint( $instance['postsperpage'] ) : 4;
		$show_post_date = ! empty( $instance['showpostdate'] );
		$category = ! empty( $instance['category'] ) ? absint( $instance['category'] ) : '';
		$show_excerpt = ! empty( $instance['showexcerpt'] );
		$excerpt_length = ! empty( $instance['excerptlength'] ) ? absint( $instance['excerptlength'] ) : 20;
		$show_post_author = ! empty( $instance['showpostauthor'] );

		// Generate cache key
		$cache_key = 'book_review_latest_posts_' . md5( serialize( $instance ) );
		$output = get_transient( $cache_key );

		if ( false === $output ) {
			ob_start();
			?>
			<ul class="recent-post-widget">
				<?php
				$query_args = array(
					'post_type' => 'post',
					'posts_per_page' => $posts_per_page,
					'ignore_sticky_posts' => true,
				);
				if ( $category ) {
					$query_args['cat'] = $category;
				}
				$recent_posts = new WP_Query( $query_args );

				while ( $recent_posts->have_posts() ) :
					$recent_posts->the_post();
					$post_classes = 'book-review-blog-recent-post';
					if ( ! has_post_thumbnail() ) {
						$post_classes .= ' no-post-thumbnail';
					}
					?>
					<li <?php post_class( $post_classes ); ?>>
						<?php if ( has_post_thumbnail() ) : ?>
							<div class="recent-post-thumb">
								<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'book-review-blog-recent-post' ); ?></a>
							</div>
						<?php endif; ?>
						<div class="recent-widget-content">
							<h2 class="rct-news-title"><a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a></h2>
							<?php if ( $show_post_date ) : ?>
								<div class="recent-post-date">
									<?php book_review_blog_posted_on(true); ?>
								</div>
							<?php endif; ?>
							<?php if ( $show_excerpt ) : ?>
								<div class="recent-post-excerpt">
									<?php echo wp_trim_words( get_the_excerpt(), $excerpt_length, '...' ); ?>
								</div>
							<?php endif; ?>
							<?php if ( $show_post_author ) : ?>
								<div class="recent-post-author">
									<?php esc_html_e( 'By ', 'book-review-blog' ); ?><a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>"><?php the_author(); ?></a>
								</div>
							<?php endif; ?>
						</div>
					</li>
				<?php endwhile; wp_reset_postdata(); ?>
			</ul>
			<?php
			$output = ob_get_clean();
			set_transient( $cache_key, $output, HOUR_IN_SECONDS );
		}

		echo $output;
		echo $args['after_widget'];
	}

	public function field_generator( $instance ) {
		foreach ( $this->widget_fields as $widget_field ) {
			$default = isset( $widget_field['default'] ) ? $widget_field['default'] : '';
			$widget_value = ! empty( $instance[ $widget_field['id'] ] ) ? $instance[ $widget_field['id'] ] : $default;
			?>
			<p>
				<label for="<?php echo esc_attr( $this->get_field_id( $widget_field['id'] ) ); ?>"><?php echo esc_html( $widget_field['label'] ); ?></label>
				<?php
				switch ( $widget_field['type'] ) {
					case 'checkbox':
						?>
						<input type="checkbox" class="checkbox" <?php checked( $widget_value, '1' ); ?> id="<?php echo esc_attr( $this->get_field_id( $widget_field['id'] ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( $widget_field['id'] ) ); ?>" value="1">
						<?php
						break;
					case 'select':
						?>
						<select class="widefat" id="<?php echo esc_attr( $this->get_field_id( $widget_field['id'] ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( $widget_field['id'] ) ); ?>">
							<?php foreach ( $widget_field['options'] as $value => $label ) : ?>
								<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $widget_value, $value ); ?>><?php echo esc_html( $label ); ?></option>
							<?php endforeach; ?>
						</select>
						<?php
						break;
					case 'number':
						?>
						<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( $widget_field['id'] ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( $widget_field['id'] ) ); ?>" type="number" value="<?php echo esc_attr( $widget_value ); ?>" min="1">
						<?php
						break;
					default:
						?>
						<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( $widget_field['id'] ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( $widget_field['id'] ) ); ?>" type="<?php echo esc_attr( $widget_field['type'] ); ?>" value="<?php echo esc_attr( $widget_value ); ?>">
						<?php
				}
				?>
			</p>
			<?php
		}
	}

	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'book-review-blog' ); ?></label>
			<input class="widefat" 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>
		<?php $this->field_generator( $instance ); ?>
		<?php
	}

	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ! empty( $new_instance['title'] ) ? sanitize_text_field( $new_instance['title'] ) : '';
		foreach ( $this->widget_fields as $widget_field ) {
			$id = $widget_field['id'];
			switch ( $widget_field['type'] ) {
				case 'number':
					$instance[$id] = ! empty( $new_instance[$id] ) ? absint( $new_instance[$id] ) : '';
					break;
				case 'checkbox':
					$instance[$id] = ! empty( $new_instance[$id] ) ? '1' : '';
					break;
				case 'select':
					$instance[$id] = ! empty( $new_instance[$id] ) ? absint( $new_instance[$id] ) : '';
					break;
				default:
					$instance[$id] = ! empty( $new_instance[$id] ) ? sanitize_text_field( $new_instance[$id] ) : '';
			}
		}
		// Invalidate cache when settings change
		$cache_key = 'book_review_latest_posts_' . md5( serialize( $old_instance ) );
		delete_transient( $cache_key );
		return $instance;
	}
}

function book_review_blog_latest_posts_wr() {
	register_widget( 'Book_Review_Blog_Latest_Posts_Widget' );
}
add_action( 'widgets_init', 'book_review_blog_latest_posts_wr' );

// Clear cache when a post is saved
function book_review_blog_clear_widget_cache( $post_id ) {
	$widgets = wp_get_sidebars_widgets();
	foreach ( $widgets as $sidebar => $widget_list ) {
		if ( ! empty( $widget_list ) ) {
			foreach ( $widget_list as $widget ) {
				if ( strpos( $widget, 'book_review_blog_latest_posts' ) !== false ) {
					$settings = get_option( 'widget_book_review_blog_latest_posts' );
					foreach ( $settings as $instance ) {
						if ( is_array( $instance ) ) {
							$cache_key = 'book_review_latest_posts_' . md5( serialize( $instance ) );
							delete_transient( $cache_key );
						}
					}
				}
			}
		}
	}
}
add_action( 'save_post', 'book_review_blog_clear_widget_cache' );