<?php
/**
 * WhitePapers
 *
 * @package CommonFrameworkPlugin
 */

namespace CommonFrameworkPlugin;

use CommonFrameworkPlugin\CPTGenerator;

/**
 * Creates the CommonFrameworkPlugin post type and shortcodes to output them.
 */
class WhitePapers extends \CommonFrameworkPlugin\Module {
	/**
	 * Only register if on an admin page and if the Fieldmanager plugin is active.
	 *
	 * @return bool True if the registration is allowed.
	 */
	public function can_register() {
		return true;
	}

	/**
	 * Register our hooks.
	 *
	 * @return void
	 */
	public function register() {
		add_action( 'init', [ $this, 'create_white_papers_custom_post_type' ] );
		add_shortcode( 'white_paper_sidebar', [ $this, 'white_paper_sidebar_shortcode' ] );
		add_shortcode( 'white_paper_title', [ $this, 'white_paper_title' ] );
		add_action( 'template_redirect', [ $this, 'disable_single_view' ], 10, 1 );
		add_filter( 'wpseo_robots', [ $this, 'exclude_from_yoast_index' ], 10, 2 );
		add_filter( 'wpseo_sitemap_exclude_post_type', [ $this, 'exclude_from_sitemap' ], 10, 2 );
	}

	/**
	 * Creates a custom post type for white papers.
	 *
	 * This function registers the custom post type for white papers, including taxonomy,
	 * slug settings, and support for custom fields, thumbnails, and authors.
	 *
	 * @return void
	 */
	public function create_white_papers_custom_post_type() {
		$cpt = new CPTGenerator();

		$fields = [
			'slug'                  => 'white-papers',
			'singular'              => 'White Paper',
			'plural'                => 'White Papers',
			'menu_name'             => 'White Papers',
			'description'           => 'White Papers',
			'has_archive'           => true,
			'hierarchical'          => true,
			'menu_icon'             => 'dashicons-media-text',
			'rewrite' => array(
				'slug'                  => 'white-papers',
				'with_front'            => false,
				'pages'                 => true,
				'feeds'                 => false,
				'ep_mask'               => EP_PERMALINK,
			),
			'menu_position'         => 22,
			'public'                => true,
			'publicly_queryable'    => true,
			'exclude_from_search'   => false,
			'show_ui'               => true,
			'show_in_menu'          => true,
			'query_var'             => true,
			'show_in_admin_bar'     => true,
			'show_in_nav_menus'     => true,
			'show_in_rest'          => true,
			'supports'              => array(
				'title',
				'editor',
				'excerpt',
				'author',
				'thumbnail',
				'custom-fields',
			),
			'custom_caps'           => false,
			'custom_caps_users'     => array(
				'administrator',
			),
			'taxonomies'            => array(
				// Register "white-paper-category" Taxonomy
				array(
					'taxonomy'          => 'white-paper-category',
					'plural'            => 'White Paper Categories',
					'single'            => 'White Paper Category',
					'post_types'        => array( 'white-papers' ),
					'show_admin_column' => true,
					'show_in_rest'      => true,
					'hierarchical'      => true,
					'rewrite'           => true,
				),
			),
		];

		$cpt->register_single_post_type( $fields );
	}

	/**
	 * Shortcode to display the white paper sidebar.
	 *
	 * Outputs quick links and categories for white papers.
	 *
	 * @return string The HTML output for the sidebar.
	 */
	public function white_paper_sidebar_shortcode() {
		ob_start();

		$case_studies = get_term_by( 'slug', 'case-studies', 'white-paper-category' );
		?>
		<h2>Quick Links</h2>
		<ul>
			<li>
				<a href="<?php echo esc_url( get_post_type_archive_link( 'white-papers' ) ); ?>">All White Papers</a>
			</li>
			<li>
				<a href="<?php echo esc_url( get_term_link( $case_studies ) ); ?>">Case Studies</a>
			</li>
		</ul>
		<h2>White Paper Categories</h2>
		<ul>
		<?php
		$terms = get_terms(
			array(
				'taxonomy' => 'white-paper-category',
				'exclude' => $case_studies->term_id,
			)
		);
		foreach ( $terms as $term ) {
			?>
			<li>
				<a href="<?php echo esc_url( get_term_link( $term ) ); ?>"><?php echo esc_html( $term->name ); ?></a>
			</li>
		<?php } ?>
		</ul>
		<?php

		$sidebar = ob_get_clean();

		return $sidebar;
	}

	/**
	 * Shortcode to display the white paper title.
	 *
	 * Outputs the title based on the current archive type, appending 'White Papers' where appropriate.
	 *
	 * @param array $atts The shortcode attributes.
	 *
	 * @return string The title for the current archive page.
	 */
	public function white_paper_title( $atts ) {
		$output = '';

		if ( is_category() ) {
			$output = single_cat_title( '', false );
		} elseif ( is_tag() ) {
			$output = single_tag_title( '', false );
		} elseif ( is_author() ) {
			$output = '<span class="vcard">' . esc_html( get_the_author() ) . '</span>';
		} elseif ( is_post_type_archive() ) {
			$output = post_type_archive_title( '', false );
		} elseif ( is_tax() ) {
			$output = single_term_title( '', false );
		}

		if ( strstr( $output, 'White Papers' ) ) {
			$output = 'Data Center Solutions White Papers';
		} else if ( strstr( $output, 'Case Studies' ) ) {
			$output = 'Data Center Products & Solutions Case&nbsp;Studies';
		} else {
			$output = esc_html( $output ) . ' White Papers';
		}

		return $output;
	}

	/**
	 * Disable the single view of 'white-papers' post type and redirect to the archive page.
	 *
	 * This function checks if the current query is not for the admin panel, is the main query,
	 * and is for a singular 'white-papers' post type. If all conditions are met, it redirects
	 * the user to the archive page of 'white-papers'.
	 *
	 * @param WP_Query $query The current WordPress query instance.
	 *
	 * @return void
	 */
	public function disable_single_view( $query ) {
		if ( ! is_admin() && is_main_query() && is_singular( 'white-papers' ) ) {
			wp_safe_redirect( get_post_type_archive_link( 'white-papers' ) );
			exit;
		}
	}

	/**
	 * Modify Yoast SEO robots meta to exclude 'white-papers' post type from indexing.
	 *
	 * This function checks if the current post is a singular 'white-papers' post type,
	 * and if so, sets the 'noindex' directive in the robots meta for Yoast SEO.
	 *
	 * @param array   $robots An array of robots meta directives.
	 * @param WP_Post $post   The current post object.
	 *
	 * @return array Modified robots meta directives.
	 */
	public function exclude_from_yoast_index( $robots, $post ) {
		if ( is_singular( 'white-papers' ) ) {
			$robots['index'] = 'noindex';
		}
		return $robots;
	}

	/**
	 * Exclude a post type from XML sitemaps.
	 *
	 * @param boolean $excluded  Whether the post type is excluded by default.
	 * @param string  $post_type The post type to exclude.
	 *
	 * @return bool Whether a given post type should be excluded.
	 */
	public function exclude_from_sitemap( $excluded, $post_type ) {
		return 'white-papers' === $post_type;
	}
}
