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

/**
 * Class Forumax_Recent_Replies
 * A list of the most recent replies.
 * 
 * @package Forumax\WpWidgets
 */
class Forumax_Recent_Replies extends WP_Widget
{
	/**
	 * Forumax Recent Replies Widget
	 *
	 * Registers the replies widget
	 */
	public function __construct()
	{
		$widget_ops = apply_filters('forumax_replies_widget_options', array(
			'classname' => 'forumax_recent_replies_widget widget_display_replies',
			'description' => esc_html__('A list of the most recent replies.', 'forumax'),
			'customize_selective_refresh' => true
		));

		parent::__construct('forumax_recent_replies', esc_html__('(Forumax) Recent Replies', 'forumax'), $widget_ops);
	}

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

	/**
	 * Displays the output, the replies 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_replies_widget_title', $settings['title'], $instance, $this->id_base);

		// 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(array(
			'post_type' => bbp_get_reply_post_type(),
			'post_status' => bbp_get_public_reply_statuses(),
			'posts_per_page' => (int) $settings['max_shown'],
			'ignore_sticky_posts' => true,
			'no_found_rows' => true,
			'update_post_term_cache' => false,
			'update_post_meta_cache' => false
		));

		// Bail if no replies 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="bbp-replies-widget frmx-list-unstyled">

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

				<li>

					<?php
					// Verify the reply ID
					$reply_id = bbp_get_reply_id($widget_query->post->ID);
					$reply_link = '<a class="bbp-reply-topic-title" href="' . esc_url(bbp_get_reply_url($reply_id)) . '" title="' . esc_attr(bbp_get_reply_excerpt($reply_id, 50)) . '">' . esc_html(bbp_get_reply_topic_title($reply_id)) . '</a>';
					$time = get_the_time('U', $reply_id);
					$show_date = '<time datetime="' . gmdate('Y-m-d H:i:s', $time) . '">' . esc_html(bbp_get_time_since($time)) . '</time>';

					// Only query user if showing them
					if (!empty($settings['show_user'])):
						$author_link = bbp_get_reply_author_link(array('post_id' => $reply_id, 'type' => 'both', 'size' => 14));
					else:
						$author_link = false;
					endif;

					// Reply author, link, and timestamp
					if (!empty($settings['show_date']) && !empty($author_link)):

						// translators: 1: reply author, 2: reply link, 3: reply timestamp
						printf(esc_html_x('%1$s on %2$s %3$s', 'widgets', 'bbpress'), $author_link, $reply_link, $show_date);

						// Reply link and timestamp
					elseif (!empty($settings['show_date'])):
						echo $reply_link . ' ' . $show_date;

						// Reply author and title
					elseif (!empty($author_link)):

						// translators: 1: reply author, 2: reply link
						printf(esc_html_x('%1$s on %2$s', 'widgets', 'bbpress'), $author_link, $reply_link);

						// Only the reply title
					else:
						echo $reply_link;
					endif;
					?>

				</li>

			<?php endwhile; ?>

		</ul>

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

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

	/**
	 * Update the reply 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['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;

		return $instance;
	}

	/**
	 * Output the reply 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 replies 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('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 reply author', 'forumax'); ?>
			</label>
		</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 Replies', 'forumax'),
			'max_shown' => 5,
			'show_date' => true,
			'show_user' => true
		), 'forumax_replies_widget_settings');
	}
}
