<?php

namespace Automattic\P2\Themes\P2020;

use \Automattic\P2\Plugins\Core\Navigation;

/**
 * Extends WP_Widget_Pages to provide a custom page menu for P2s.
 */
class P2_Page_Menu_Widget extends \WP_Widget_Pages {
	const WIDGET_ID_BASE = 'p2020-page-menu-widget';

	public function __construct() {
		\WP_Widget::__construct(
			self::WIDGET_ID_BASE, // Base ID
			__( 'P2 Pages', 'p2020' ), // Name
			[
				'description'                 => __( "Display a list of your site's pages on your sidebar.", 'p2020' ),
				'customize_selective_refresh' => true,
			]
		);

		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
	}

	/**
	 * Overrides WP_Widget_Pages::udpate().
	 *
	 * @param array $new_instance New settings for this instance as input by the user via
	 *                            WP_Widget::form().
	 * @param array $old_instance Old settings for this instance.
	 * @return array Updated settings to save.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance             = parent::update( $new_instance, $old_instance );
		$instance['expanded'] = 'expanded' === $new_instance['expanded'];
		return $instance;
	}

	public function enqueue_scripts() {
		if ( is_active_widget( false, false, self::WIDGET_ID_BASE ) ||
			is_active_widget( false, false, 'monster' ) ||
			is_customize_preview()
		) {
			wp_enqueue_script(
				'p2020-sidebar-menu-toggler',
				get_template_directory_uri() . '/widgets/sidebar-menus/js/tree-toggler.js',
				[ 'jquery' ],
				filemtime( get_template_directory() . '/widgets/sidebar-menus/js/tree-toggler.js' ),
				true
			);
		}
	}

	/**
	 * Overrides WP_Widget_Pages::form().
	 */
	public function form( $instance ) {
		// Defaults.
		$instance = wp_parse_args(
			(array) $instance,
			[
				'sortby'  => 'menu_order',
				'title'   => __( 'Pages', 'p2020' ),
				'exclude' => '',
			]
		);
		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'p2020' ); ?></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( $instance['title'] ); ?>" />
		</p>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'sortby' ) ); ?>"><?php esc_html_e( 'Sort by:', 'p2020' ); ?></label>
			<select name="<?php echo esc_attr( $this->get_field_name( 'sortby' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'sortby' ) ); ?>" class="widefat">
				<option value="menu_order"<?php selected( $instance['sortby'], 'menu_order' ); ?>><?php esc_html_e( 'Page order', 'p2020' ); ?></option>
				<option value="post_title"<?php selected( $instance['sortby'], 'post_title' ); ?>><?php esc_html_e( 'Page title', 'p2020' ); ?></option>
				<option value="ID"<?php selected( $instance['sortby'], 'ID' ); ?>><?php esc_html_e( 'Page ID', 'p2020' ); ?></option>
			</select>
		</p>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'exclude' ) ); ?>"><?php esc_html_e( 'Exclude:', 'p2020' ); ?></label>
			<input type="text" value="<?php echo esc_attr( $instance['exclude'] ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'exclude' ) ); ?>" id="<?php echo esc_attr( $this->get_field_id( 'exclude' ) ); ?>" class="widefat" />
			<br />
			<small><?php esc_html_e( 'Page IDs, separated by commas.', 'p2020' ); ?></small>
		</p>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'expanded' ) ); ?>">
				<input type="checkbox" class="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'expanded' ) ); ?>" value="expanded"
					name="<?php echo esc_attr( $this->get_field_name( 'expanded' ) ); ?>" type="text" <?php checked( $instance['expanded'], true ); ?> />
				<?php esc_html_e( 'Show expanded', 'p2020' ); ?>
			</label>
		</p>
		<?php
	}

	/**
	 * Override of WP_Widget_Pages::widget().
	 */
	public function widget( $args, $instance ) {
		$default = array(
			'title'   => __( 'Pages', 'p2020' ),
			'sortby'  => 'menu_order',
			'exclude' => '',
		);

		$title = empty( $instance['title'] ) ? $default['title'] : $instance['title'];
		$title = apply_filters( 'widget_title', $title );

		$sortby = empty( $instance['sortby'] ) ? $default['sortby'] : $instance['sortby'];

		$exclude = empty( $instance['exclude'] ) ? $default['exclude'] : $instance['exclude'];

		$expanded = ! empty( $instance['expanded'] );

		// phpcs:disable WordPress.Security.EscapeOutput
		// Reason: HTML from theme
		echo $args['before_widget'];
		echo $this->widget_header( $title, $args['before_title'], $args['after_title'] );
		echo $this->widget_content( $title, $sortby, $exclude, $expanded );
		echo $args['after_widget'];
		// phpcs:enable WordPress.Security.EscapeOutput

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

	private function widget_header( $title, $before_title, $after_title ) {
		$simple_menu = null;
		// phpcs:disable WordPress.Security.EscapeOutput
		// Reason: HTML from theme
		echo $before_title;

		echo esc_html( $title );

		// Output actions menu if user has correct privileges.
		if ( is_user_member_of_blog() && current_user_can( 'publish_pages' ) ) {
			$new_page_url     = Navigation\Urls::get_editor_page_url();
			$manage_pages_url = Navigation\Urls::get_pages_url();
			$simple_menu      = new Navigation\Simple_Menu( 'p2020-page-menu-widget-menu', __( 'More', 'p2020' ) );
			$simple_menu->add_item( __( 'New page', 'p2020' ), $new_page_url );
			$simple_menu->add_item( __( 'Manage pages', 'p2020' ), $manage_pages_url );
		}

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

		echo $after_title;
		// phpcs:enable WordPress.Security.EscapeOutput
	}

	private function widget_content( $title, $sortby, $exclude, $expanded ) {
		self::print_menu( $title, $sortby, $exclude, $expanded );
	}

	public static function print_menu( $title, $sortby = 'menu_order', $exclude = '', $expanded = '' ) {
		echo '<nav class="p2020-page-menu" role="navigation" aria-label="' . esc_html( $title ) . '">';
		$the_pages = get_pages();
		if ( ! is_countable( $the_pages ) || 0 === count( $the_pages ) ) {
			self::print_empty_state();
		} else {
			require_once get_template_directory() . '/widgets/sidebar-menus/page-menu-walker.php';
			$options = array(
				'title_li'    => '',
				'sort_column' => $sortby,
				'exclude'     => $exclude,
				'echo'        => 1,
				'before'      => '<ul class="menu-root">',
				'after'       => '</ul>',
				'walker'      => new P2_Page_Menu_Walker( $expanded ),
			);
			wp_page_menu( $options );
		}
		echo '</nav>';
	}

	public static function print_empty_state() {
		echo '<div class="menu-empty">';
		$label = _x( 'No pages', 'there are no pages', 'p2020' );
		echo esc_html( $label );

		if ( current_user_can( 'publish_pages' ) ) {
			$new_page_url   = Navigation\Urls::get_editor_page_url();
			$new_page_label = _x( 'Start one', 'create new page', 'p2020' );
			echo ' — <a href="' . esc_url( $new_page_url ) . '">' .
				esc_html( $new_page_label ) .
				'</a>';
		}

		echo '</div>';
	}
}