<?php

namespace Automattic\P2\Themes\P2020;

use Automattic\P2\Plugins\Core as P2_Core;

class Tags_Widget extends \WP_Widget {
	const WIDGET_ID_BASE = 'p2020-tags-widget';
	private $default_title;

	/**
	 * Registers the widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			self::WIDGET_ID_BASE, // Base ID
			__( 'P2 Tags', 'p2020' ), // Name
			[
				'description'                 => __( 'Allows you to showcase your tags.', 'p2020' ),
				'customize_selective_refresh' => true,
			]
		);

		if ( is_active_widget( false, false, $this->id_base ) || is_active_widget( false, false, 'monster' ) || is_customize_preview() ) {
			add_action( 'wp_print_styles', [ $this, 'enqueue_style' ] );
		}

		$this->default_title = __( 'Tags', 'p2020' );
	}

	public function enqueue_style() {
		wp_enqueue_style( 'widget-grid-and-list' );
	}

	/**
	 * Back-end widget form.
	 *
	 * @param array $instance Previously saved values from database.
	 *
	 * @see WP_Widget::form()
	 *
	 */
	public function form( $instance ) {
		$instance = $this->extend_default_options( $instance );

		$title = $instance['title'];
		if ( false === $title ) {
			$title = $this->default_title;
		}

		$id    = $this->get_field_id( 'title' );
		$label = translate( 'Title:', 'p2020' );
		$name  = $this->get_field_name( 'title' );
		?>
		<p>
			<label for="<?php echo esc_html( $id ); ?>"><?php echo esc_html( $label ); ?></label>
			<input class="widefat" type="text" id="<?php echo esc_html( $id ); ?>" name="<?php echo esc_html( $name ); ?>"
						 value="<?php echo esc_html( $title ); ?>"/>
		</p>

		<?php
		$selected_limit = (int) $instance['limit'];
		$limits         = [
			5  => 5,
			10 => 10,
			20 => 20,
			30 => 30,
		];
		$id             = $this->get_field_id( 'limit' );
		$label          = translate( 'Limit:', 'p2020' );
		$name           = $this->get_field_name( 'limit' );
		?>
		<p>
			<label for="<?php echo esc_html( $id ); ?>"><?php echo esc_html( $label ); ?></label>
			<select class="widefat" id="<?php echo esc_html( $id ); ?>" name="<?php echo esc_html( $name ); ?>">
				<?php foreach ( $limits as $limit_value => $limit_label ) : ?>
					<option <?php selected( $selected_limit, $limit_value ); ?>
						value="<?php echo esc_html( $limit_value ); ?>"><?php echo esc_html( $limit_label ); ?></option>
				<?php endforeach; ?>
			</select>
		</p>

		<?php
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 * @see WP_Widget::update()
	 *
	 */
	// Reason: -- Function signature for WP_Widget::update()
	// phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
	// phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed
	public function update( $new_instance, $old_instance ) {
		$instance          = [];
		$instance['title'] = wp_kses( $new_instance['title'], [] );

		$instance['limit'] = (int) $new_instance['limit'];

		return $instance;
	}
	// phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
	// phpcs:enable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassAfterLastUsed

	/**
	 * Front-end display of widget.
	 *
	 * @param array $args Widget arguments.
	 * @param array $instance Saved values from database.
	 *
	 * @return void
	 * @see WP_Widget::widget()
	 *
	 */
	public function widget( $args, $instance ) {
		$instance = $this->extend_default_options( $instance );

		$title = $instance['title'];
		$title = apply_filters( 'widget_title', $title );

		// phpcs:ignore WordPress.Security.EscapeOutput -- HTML from theme
		echo $args['before_widget'];

		if ( ! empty( $title ) ) {
			if ( is_user_member_of_blog() && current_user_can( 'customize' ) ) {
				$customize_url = P2_Core\Navigation\Urls::get_customizer_url();
				$simple_menu   = new P2_Core\Navigation\Simple_Menu( 'tags-widget-menu', __( 'More', 'p2' ) );
				$simple_menu->add_item( __( 'Widget settings', 'p2020' ), $customize_url );
			}

			// phpcs:ignore WordPress.Security.EscapeOutput -- HTML from theme
			echo $args['before_title'];

			echo esc_html( $title );

			if ( $simple_menu ) {
				get_template_part(
					'partials/ellipsis-menu',
					$simple_menu->get_type(),
					[ 'simple_menu' => $simple_menu ],
				);
			}

			// phpcs:ignore WordPress.Security.EscapeOutput -- HTML from theme
			echo $args['after_title'];
		}

		$limit = (int) $instance['limit'];
		$tags  = get_tags(
			[
				'orderby' => 'count',
				'order'   => 'DESC',
				'number'  => $limit,
			]
		);

		if ( empty( $tags ) ) {
			echo 'There are no post tags.';
		} else {
			?>
			<div class="widgets-multi-column-grid">
				<ul>
					<?php foreach ( $tags as $key => $tag ) : ?>
						<li>
							<a href="<?php echo esc_url( Shared\get_blog_url( '/tag	/' . $tag->slug ) ); ?>" class="widget-tags-item">
								<span class="widget-tags-name"><?php echo esc_html( $tag->name ); ?></span>
								<span class="widget-tags-count"><?php echo esc_html( $tag->count ); ?></span>
							</a>
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
			<?php
		}

		// phpcs:ignore WordPress.Security.EscapeOutput -- HTML from theme
		echo $args['after_widget'];

		do_action( 'p2_widgets_stats', self::WIDGET_ID_BASE );
	}

	protected function extend_default_options( array $options = [] ): array {
		$defaults = [
			'title' => $this->default_title,
			'limit' => 5,
		];

		$merged = array_merge( $defaults, $options );

		return $merged;
	}
}