<?php
namespace Forumax\WpWidgets;
use WP_Widget;
use WP_Query;

/**
 * Class Forumax_Recent_Topics
 * A list of recent topics, sorted by: newness, popularity, or recent replies.
 * 
 * @package Forumax\WpWidgets
 */
class Forumax_Recent_Topics extends WP_Widget
{
	/**
	 * Forumax Recent Topics Widget
	 *
	 * Registers the topic widget
	 */
	public function __construct()
	{
		$widget_ops = apply_filters('forumax_topics_widget_options', array(
			'classname' => 'forumax_recent_topics_widget widget_display_topics',
			'description' => esc_html__('A list of recent topics, sorted by: newness, popularity, or recent replies.', 'forumax'),
			'customize_selective_refresh' => true
		));

		parent::__construct('forumax_recent_topics', esc_html__('(Forumax) Recent Topics', 'forumax'), $widget_ops);
	}

	/**
	 * Register the widget
	 */
	public static function register_widget()
	{
		register_widget(__CLASS__);
	}

	/**
	 * Displays the output, the topic list
	 *
	 * @param array $args Arguments
	 * @param array $instance Instance
	 */
	public function widget($args = array(), $instance = array())
	{

		// Get widget settings
		$settings = $this->parse_settings($instance);

		// Typical WordPress filter
		$settings['title'] = apply_filters('widget_title', $settings['title'], $instance, $this->id_base);

		// Forumax filter
		$settings['title'] = apply_filters('forumax_topic_widget_title', $settings['title'], $instance, $this->id_base);

		// How do we want to order our results?
		switch ($settings['order_by']) {

			// Order by most recent replies
			case 'freshness':
				$topics_query = array(
					'post_type' => bbp_get_topic_post_type(),
					'post_status' => bbp_get_public_topic_statuses(),
					'post_parent' => $settings['parent_forum'],
					'posts_per_page' => (int) $settings['max_shown'],
					'meta_query' => array(
						array(
							'key' => '_bbp_last_active_time',
							'type' => 'DATETIME'
						)
					),
					'orderby' => 'meta_value',
					'order' => 'DESC',
					'ignore_sticky_posts' => true,
					'no_found_rows' => true,
					'update_post_term_cache' => false,
					'update_post_meta_cache' => false
				);
				break;

			// Order by total number of replies
			case 'popular':
				$topics_query = array(
					'post_type' => bbp_get_topic_post_type(),
					'post_status' => bbp_get_public_topic_statuses(),
					'post_parent' => $settings['parent_forum'],
					'posts_per_page' => (int) $settings['max_shown'],
					'meta_query' => array(
						array(
							'key' => '_bbp_reply_count',
							'type' => 'NUMERIC'
						)
					),
					'orderby' => 'meta_value_num',
					'order' => 'DESC',
					'ignore_sticky_posts' => true,
					'no_found_rows' => true,
					'update_post_term_cache' => false,
					'update_post_meta_cache' => false
				);
				break;

			// Order by which topic was created most recently
			case 'newness':
			default:
				$topics_query = array(
					'post_type' => bbp_get_topic_post_type(),
					'post_status' => bbp_get_public_topic_statuses(),
					'post_parent' => $settings['parent_forum'],
					'posts_per_page' => (int) $settings['max_shown'],
					'orderby' => 'date',
					'order' => 'DESC',
					'ignore_sticky_posts' => true,
					'no_found_rows' => true,
					'update_post_term_cache' => false,
					'update_post_meta_cache' => false
				);
				break;
		}

		// Note: private and hidden forums will be excluded via the
		// bbp_pre_get_posts_normalize_forum_visibility action and function.
		$widget_query = new WP_Query($topics_query);

		// Bail if no topics are found
		if (!$widget_query->have_posts()) {
			return;
		}

		echo $args['before_widget'];

		if (!empty($settings['title'])) {
			echo $args['before_title'] . $settings['title'] . $args['after_title'];
		} ?>

		<ul class="frmx-list-unstyled bbp-topics-widget <?php echo esc_attr($settings['order_by']); ?>">

			<?php while ($widget_query->have_posts()):

				$widget_query->the_post();
				$topic_id = bbp_get_topic_id($widget_query->post->ID);
				$author_link = bbp_get_topic_author_link(array('post_id' => $topic_id, 'type' => 'both', 'size' => 14));
				?>

				<li>
					<a class="bbp-forum-title" href="<?php bbp_topic_permalink($topic_id); ?>">
						<?php bbp_topic_title($topic_id); ?>
					</a>

					<?php if (!empty($author_link)): ?>
						<?php printf(esc_html_x('by %1$s', 'widgets', 'bbpress'), '<span class="topic-author">' . $author_link . '</span>'); ?>
					<?php endif; ?>

					<div><?php bbp_topic_last_active_time($topic_id); ?></div>
				</li>

			<?php endwhile; ?>

		</ul>

		<?php echo $args['after_widget'];

		// Reset the $post global
		wp_reset_postdata();
	}

	/**
	 * Update the topic widget options
	 *
	 * @param array $new_instance The new instance options
	 * @param array $old_instance The old instance options
	 * @return array Updated instance
	 */
	public function update($new_instance = array(), $old_instance = array())
	{
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['order_by'] = strip_tags($new_instance['order_by']);
		$instance['parent_forum'] = sanitize_text_field($new_instance['parent_forum']);
		$instance['max_shown'] = (int) $new_instance['max_shown'];

		// Date
		$instance['show_date'] = isset($new_instance['show_date'])
			? (bool) $new_instance['show_date']
			: false;

		// Author
		$instance['show_user'] = isset($new_instance['show_user'])
			? (bool) $new_instance['show_user']
			: false;

		// Force to any
		if (!empty($instance['parent_forum']) && !is_numeric($instance['parent_forum'])) {
			$instance['parent_forum'] = 'any';
		}

		return $instance;
	}

	/**
	 * Output the topic widget options form
	 *
	 * @param array $instance Instance
	 */
	public function form($instance = array())
	{

		// Get widget settings
		$settings = $this->parse_settings($instance); ?>

		<p>
			<label for="<?php echo $this->get_field_id('title'); ?>"><?php esc_html_e('Title:', 'forumax'); ?>
				<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
					name="<?php echo $this->get_field_name('title'); ?>" type="text"
					value="<?php echo esc_attr($settings['title']); ?>" />
			</label>
		</p>

		<p>
			<label
				for="<?php echo $this->get_field_id('max_shown'); ?>"><?php esc_html_e('Maximum topics to show:', 'forumax'); ?>
				<input class="widefat" id="<?php echo $this->get_field_id('max_shown'); ?>"
					name="<?php echo $this->get_field_name('max_shown'); ?>" type="text"
					value="<?php echo esc_attr($settings['max_shown']); ?>" />
			</label>
		</p>

		<p>
			<label
				for="<?php echo $this->get_field_id('parent_forum'); ?>"><?php esc_html_e('Parent Forum ID:', 'forumax'); ?>
				<input class="widefat" id="<?php echo $this->get_field_id('parent_forum'); ?>"
					name="<?php echo $this->get_field_name('parent_forum'); ?>" type="text"
					value="<?php echo esc_attr($settings['parent_forum']); ?>" />
			</label>

			<br />

			<small><?php esc_html_e('"0" to show only root - "any" to show all', 'forumax'); ?></small>
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('show_date'); ?>">
				<input type="checkbox" id="<?php echo $this->get_field_id('show_date'); ?>"
					name="<?php echo $this->get_field_name('show_date'); ?>" <?php checked(true, $settings['show_date']); ?>
					value="1" />
				<?php esc_html_e('Show post date', 'forumax'); ?>
			</label>
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('show_user'); ?>">
				<input type="checkbox" id="<?php echo $this->get_field_id('show_user'); ?>"
					name="<?php echo $this->get_field_name('show_user'); ?>" <?php checked(true, $settings['show_user']); ?>
					value="1" />
				<?php esc_html_e('Show topic author', 'forumax'); ?>
			</label>
		</p>

		<p>
			<label for="<?php echo $this->get_field_id('order_by'); ?>"><?php esc_html_e('Order By:', 'forumax'); ?></label>
			<select class="widefat" name="<?php echo $this->get_field_name('order_by'); ?>"
				id="<?php echo $this->get_field_id('order_by'); ?>">
				<option <?php selected($settings['order_by'], 'newness'); ?> value="newness">
					<?php esc_html_e('Newest Topics', 'forumax'); ?></option>
				<option <?php selected($settings['order_by'], 'popular'); ?> value="popular">
					<?php esc_html_e('Popular Topics', 'forumax'); ?></option>
				<option <?php selected($settings['order_by'], 'freshness'); ?> value="freshness">
					<?php esc_html_e('Topics With Recent Replies', 'forumax'); ?></option>
			</select>
		</p>

		<?php
	}

	/**
	 * Merge the widget settings into defaults array.
	 *
	 * @param array $instance Instance
	 * @return array Parsed settings
	 */
	public function parse_settings($instance = array())
	{
		return bbp_parse_args($instance, array(
			'title' => esc_html__('Recent Topics', 'forumax'),
			'max_shown' => 5,
			'show_date' => true,
			'show_user' => true,
			'parent_forum' => 'any',
			'order_by' => 'newness'
		), 'forumax_topic_widget_settings');
	}
}
