<?php
/**
 * Class Dashboard_Widgets
 *
 * @package dvcrs-core
 */

namespace DVCRS\Core;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Dashboard_Wigets Class
 */
class Dashboard_Widgets {

	/**
	 * Dashboard_Widgets constructor
	 */
	public function __construct() {

		\add_action( 'wp_dashboard_setup', [ $this, 'remove_dashboard_widgets' ], 999, 1 );

		\add_filter( 'dashboard_glance_items', [ $this, 'filter_glance_items' ], 10, 1 );
		\add_filter( 'update_right_now_text', [ $this, 'filter_right_now_text' ], 10, 1 );

	}

	/**
	 * Remove dashboard widgets
	 */
	public function remove_dashboard_widgets() {

		global $wp_meta_boxes;

		unset( $wp_meta_boxes['dashboard']['normal']['core']['tribe_dashboard_widget'] );
		unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] );
		unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] );

		\wp_add_dashboard_widget( 'dashboard_cnp_feed', 'CNP News', [ $this, 'cnp_rss' ] );

	}

	/**
	 * CNP RSS dashboard widget
	 */
	public function cnp_rss() {

		?>
		<div class="rss-widget">
			<?php
			\wp_widget_rss_output(
				[
					'url'          => 'https://cnpagency.com/feed/',
					'title'        => 'News from CNP',
					'items'        => 3,
					'show_summary' => 1,
					'show_author'  => 1,
					'show_date'    => 1,
				]
			);
			?>
		</div>
		<?php

	}

	/**
	 * Adds custom post types to Dashboard At A Glance
	 *
	 * @param string[] $items Array of extra 'At a Glance' widget items.
	 *
	 * @return array
	 */
	public function filter_glance_items( $items ) {

		$post_types = [ 'person', 'resort' ];
		foreach ( $post_types as $post_type ) {
			$num_posts = \wp_count_posts( $post_type );
			if ( $num_posts && $num_posts->publish ) {
				$post_type_object = \get_post_type_object( $post_type );
				$text             = sprintf( '%1$s %2$s', $num_posts->publish, $post_type_object->label );
				if ( $post_type_object && \current_user_can( $post_type_object->cap->edit_posts ) ) {
					$item = sprintf( '<a class="%1$s" href="edit.php?post_type=%2$s">%3$s</a>', $post_type_object->menu_icon, $post_type, $text );
				} else {
					$item = sprintf( '<span class="%1$s">%2$s</span>', $post_type_object->menu_icon, $text );
				}

				array_push( $items, $item );
			}
		}

		return $items;
	}

	/**
	 * Filters dashboard right now message.
	 *
	 * @param string $content Right now content.
	 *
	 * @return string
	 */
	public function filter_right_now_text( $content ) {

		$theme = \wp_get_theme();
		if ( \current_user_can( 'switch_themes' ) ) {
			$theme_name = sprintf( '<a href="themes.php">%1$s v%2$s</a>', $theme->get( 'Name' ), $theme->get( 'Version' ) );
		} else {
			$theme_name = sprintf( '%1$s v%2$s', $theme->get( 'Name' ), $theme->get( 'Version' ) );
		}
		$content = sprintf( \__( 'WordPress %1$s running %2$s theme.' ), \get_bloginfo( 'version', 'display' ), $theme_name );

		return $content;
	}

}

new Dashboard_Widgets();
