<?php
/**
 * Seventhqueen\Typer\Featured_Content\Component class
 *
 * @package typer
 */

namespace Seventhqueen\Typer\Featured_Content;

use Seventhqueen\Typer\Component_Interface;
use function Seventhqueen\Typer\typer;

/**
 * Class for integrating featured posts
 *
 * @link https://wordpress.org/gutenberg/handbook/extensibility/theme-support/
 */
class Component implements Component_Interface {

	/**
	 * @var int
	 */
	public static $max_posts = 20;

	/**
	 * Gets the unique identifier for the theme component.
	 *
	 * @return string Component slug.
	 */
	public function get_slug() {
		return 'featured_posts';
	}

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	public function initialize() {

		if ( typer()->get_option( 'blog_featured_content_status' ) ) {
			add_action( 'init', [ $this, 'init' ], 30 );
		}

	}

	/**
	 * Conditionally hook into WordPress.
	 *
	 * Theme must declare that they support this module by adding
	 * add_theme_support( 'featured-content' ); during after_setup_theme.
	 *
	 * If no theme support is found there is no need to hook into WordPress.
	 * We'll just return early instead.
	 *
	 * @static
	 * @access public
	 * @since 1.0
	 */
	public static function init() {
		$theme_support = get_theme_support( 'featured-content' );

		// Return early if theme does not support Featured Content.
		if ( ! $theme_support ) {
			return;
		}

		/*
		 * An array of named arguments must be passed as the second parameter
		 * of add_theme_support().
		 */
		if ( ! isset( $theme_support[0] ) ) {
			return;
		}

		// Return early if "featured_content_filter" has not been defined.
		if ( ! isset( $theme_support[0]['featured_content_filter'] ) ) {
			return;
		}

		$filter = $theme_support[0]['featured_content_filter'];

		// Theme can override the number of max posts.
		if ( isset( $theme_support[0]['max_posts'] ) ) {
			self::$max_posts = absint( $theme_support[0]['max_posts'] );
		}

		add_filter( $filter, [ __CLASS__, 'get_featured_posts' ] );
		add_action( 'save_post', [ __CLASS__, 'delete_transient' ] );
		add_action( 'delete_post_tag', [ __CLASS__, 'delete_post_tag' ] );
		add_action( 'pre_get_posts', [ __CLASS__, 'pre_get_posts' ] );
		add_action( 'wp_loaded', [ __CLASS__, 'wp_loaded' ] );
	}

	/**
	 * Hide "featured" tag from the front-end.
	 *
	 * Has to run on wp_loaded so that the preview filters of the customizer
	 * have a chance to alter the value.
	 *
	 * @static
	 * @access public
	 * @since 1.0
	 */
	public static function wp_loaded() {
		if ( self::get_setting( 'hide-tag' ) ) {
			add_filter( 'get_terms', [ __CLASS__, 'hide_featured_term' ], 10, 2 );
			add_filter( 'get_the_terms', [ __CLASS__, 'hide_the_featured_term' ], 10, 3 );
		}
	}

	/**
	 * Get featured posts.
	 *
	 * @static
	 * @access public
	 * @return \Wp_Query|array
	 * @since 1.0
	 *
	 */
	public static function get_featured_posts() {
		$post_ids = self::get_featured_post_ids();

		// No need to query if there is are no featured posts.
		if ( empty( $post_ids ) ) {
			return [];
		}

		$args = [
			'post__in'            => $post_ids,
			'posts_per_page'      => count( $post_ids ),
			'ignore_sticky_posts' => 1,
		];

		if ( function_exists( 'fup_is_profile_page' ) && is_user_logged_in() && typer()->get_option( 'fup_custom_feed' ) ) {
			$exclude = get_transient( 'fup_home_feed_posts_' . get_current_user_id() );

			if ( is_array( $exclude ) && ! empty( $exclude ) ) {
				$args['post__in']     = array_diff( $args['post__in'], $exclude );
				$args['post__not_in'] = $exclude;
			}
		}

		return new \WP_Query( $args );
	}

	/**
	 * Get featured post IDs
	 *
	 * This function will return the an array containing the
	 * post IDs of all featured posts.
	 *
	 * Sets the "featured_content_ids" transient.
	 *
	 * @static
	 * @access public
	 * @return array Array of post IDs.
	 * @since 1.0
	 *
	 */
	public static function get_featured_post_ids() {
		// Return array of cached results if they exist.
		$featured_ids = get_transient( 'featured_content_ids' );

		if ( ! empty( $featured_ids ) ) {
			return array_map( 'absint', (array) $featured_ids );
		}

		$settings = self::get_setting();

		$featured_ids = [];

		$term = get_term_by( 'name', $settings['tag-name'], 'post_tag' );
		/* If we have featured posts */
		if ( $term ) {
			// Query for featured posts.
			$args              = [
				'numberposts'         => $settings['quantity'],
				'ignore_sticky_posts' => 1,
			];
			$args['tax_query'] = [
				[
					'field'    => 'term_id',
					'taxonomy' => 'post_tag',
					'terms'    => $term->term_id,
				],
			];

			$featured = new \WP_Query( $args );

			// Return array with sticky posts if no Featured Content exists.
			if ( $featured->have_posts() ) {
				// Ensure correct format before save/return.
				$featured_ids = wp_list_pluck( (array) $featured->posts, 'ID' );
			}

		}

		if ( $settings['include-sticky'] && self::get_sticky_posts() ) {
			$featured_ids = array_merge( $featured_ids, self::get_sticky_posts() );
			$featured_ids = array_unique( $featured_ids );
		}

		$featured_ids = array_map( 'absint', $featured_ids );

		set_transient( 'featured_content_ids', $featured_ids );

		return $featured_ids;
	}

	/**
	 * Return an array with IDs of posts maked as sticky.
	 *
	 * @static
	 * @access public
	 * @return array|bool
	 * @since 1.0
	 *
	 */
	public static function get_sticky_posts() {
		if ( get_option( 'sticky_posts' ) ) {
			return get_option( 'sticky_posts' );
		}

		return false;
	}

	/**
	 * Delete featured content ids transient.
	 *
	 * Hooks in the "save_post" action.
	 *
	 * @see Featured_Content::validate_settings().
	 *
	 * @static
	 * @access public
	 * @since 1.0
	 */
	public static function delete_transient() {
		delete_transient( 'featured_content_ids' );
	}

	/**
	 * Exclude featured posts from the home page blog query.
	 *
	 * Filter the home page posts, and remove any featured post ID's from it.
	 * Hooked onto the 'pre_get_posts' action, this changes the parameters of
	 * the query before it gets any posts.
	 *
	 * @static
	 * @access public
	 *
	 * @param WP_Query $query WP_Query object.
	 *
	 * @return WP_Query|void
	 * @since 1.0
	 *
	 */
	public static function pre_get_posts( $query ) {

		// Bail if not home or not main query.
		if ( ! $query->is_home() || ! $query->is_main_query() ) {
			return;
		}

		$page_on_front = get_option( 'page_on_front' );

		// Bail if the blog page is not the front page.
		if ( ! empty( $page_on_front ) ) {
			return;
		}

		$featured = apply_filters( 'typer_featured_content_ids', self::get_featured_post_ids() );

		// Bail if no featured posts.
		if ( ! $featured ) {
			return;
		}

		// We need to respect post ids already in the blacklist.
		$post__not_in = $query->get( 'post__not_in' );

		if ( ! empty( $post__not_in ) ) {
			$featured = array_merge( (array) $post__not_in, $featured );
			$featured = array_unique( $featured );
		}

		$query->set( 'post__not_in', $featured );
	}

	/**
	 * Reset tag option when the saved tag is deleted.
	 *
	 * It's important to mention that the transient needs to be deleted,
	 * too. While it may not be obvious by looking at the function alone,
	 * the transient is deleted by Featured_Content::validate_settings().
	 *
	 * Hooks in the "delete_post_tag" action.
	 *
	 * @param int $tag_id The term_id of the tag that has been deleted.
	 *
	 * @return void
	 * @see Featured_Content::validate_settings().
	 *
	 * @static
	 * @access public
	 * @since 1.0
	 *
	 */
	public static function delete_post_tag( $tag_id ) {
		$settings = self::get_setting();

		if ( empty( $settings['tag-id'] ) || (int) $tag_id !== (int) $settings['tag-id'] ) {
			return;
		}

		$settings['tag-id'] = 0;
		$settings           = self::validate_settings( $settings );
		update_option( 'featured-content', $settings );
	}

	/**
	 * Hide featured tag from displaying when global terms are queried from the front-end.
	 *
	 * Hooks into the "get_terms" filter.
	 *
	 * @static
	 * @access public
	 *
	 * @param array $terms List of term objects. This is the return value of get_terms().
	 * @param array $taxonomies An array of taxonomy slugs.
	 *
	 * @return array A filtered array of terms.
	 *
	 * @since 1.0
	 *
	 * @uses Featured_Content::get_setting()
	 */
	public static function hide_featured_term( $terms, $taxonomies ) {

		// This filter is only appropriate on the front-end.
		if ( is_admin() ) {
			return $terms;
		}

		// We only want to hide the featured tag.
		if ( ! in_array( 'post_tag', $taxonomies, true ) ) {
			return $terms;
		}

		// Bail if no terms were returned.
		if ( empty( $terms ) ) {
			return $terms;
		}

		foreach ( $terms as $order => $term ) {
			if ( 'post_tag' === $term->taxonomy && (int) self::get_setting( 'tag-id' ) === (int) $term->term_id ) {
				unset( $terms[ $order ] );
			}
		}

		return $terms;
	}

	/**
	 * Hide featured tag from display when terms associated with a post object
	 * are queried from the front-end.
	 *
	 * Hooks into the "get_the_terms" filter.
	 *
	 * @static
	 * @access public
	 *
	 * @param array $terms A list of term objects. This is the return value of get_the_terms().
	 * @param int $id The ID field for the post object that terms are associated with.
	 * @param array $taxonomy An array of taxonomy slugs.
	 *
	 * @return array Filtered array of terms.
	 *
	 * @since 1.0
	 *
	 * @uses Featured_Content::get_setting()
	 */
	public static function hide_the_featured_term( $terms, $id, $taxonomy ) {

		// This filter is only appropriate on the front-end.
		if ( is_admin() ) {
			return $terms;
		}

		// Make sure we are in the correct taxonomy.
		if ( 'post_tag' !== $taxonomy ) {
			return $terms;
		}

		// No terms? Return early!
		if ( empty( $terms ) ) {
			return $terms;
		}

		foreach ( $terms as $order => $term ) {
			if ( (int) self::get_setting( 'tag-id' ) === (int) $term->term_id ) {
				unset( $terms[ $term->term_id ] );
			}
		}

		return $terms;
	}

	/**
	 * Get featured content settings.
	 *
	 * Get all settings recognized by this module. This function
	 * will return all settings whether or not they have been stored
	 * in the database yet. This ensures that all keys are available
	 * at all times.
	 *
	 * In the event that you only require one setting, you may pass
	 * its name as the first parameter to the function and only that
	 * value will be returned.
	 *
	 * @static
	 * @access public
	 *
	 * @param string $key The key of a recognized setting.
	 *
	 * @return mixed Array of all settings by default. A single value if passed as first parameter.
	 * @since 1.0
	 *
	 */
	public static function get_setting( $key = 'all' ) {
		$hide_tag = typer()->get_option( 'blog_featured_tag_display' );

		$options = [
			'hide-tag'       => $hide_tag === '1',
			'tag-name'       => typer()->get_option( 'blog_featured_content_tag' ),
			'include-sticky' => typer()->get_option( 'blog_featured_sticky_status' ),
		];

		$defaults = [
			'hide-tag'       => true,
			'quantity'       => 20,
			'tag-id'         => 0,
			'tag-name'       => 'featured',
			'include-sticky' => 1,
		];

		$options             = wp_parse_args( $options, $defaults );
		$options             = array_intersect_key( $options, $defaults );
		$options['quantity'] = self::sanitize_quantity( $options['quantity'] );

		if ( 'all' !== $key ) {
			return isset( $options[ $key ] ) ? $options[ $key ] : false;
		}

		return $options;
	}

	/**
	 * Validate featured content settings.
	 *
	 * Make sure that all user supplied content is in an expected
	 * format before saving to the database. This function will also
	 * delete the transient set in Featured_Content::get_featured_content().
	 *
	 * @static
	 * @access public
	 *
	 * @param array $input Array of settings input.
	 *
	 * @return array Validated settings output.
	 * @since 1.0
	 *
	 */
	public static function validate_settings( $input ) {
		$output = [];

		if ( empty( $input['tag-name'] ) ) {
			$output['tag-id'] = 0;
		} else {
			$term = get_term_by( 'name', $input['tag-name'], 'post_tag' );

			if ( $term ) {
				$output['tag-id'] = $term->term_id;
			} else {
				$new_tag = wp_create_tag( $input['tag-name'] );

				if ( ! is_wp_error( $new_tag ) && isset( $new_tag['term_id'] ) ) {
					$output['tag-id'] = $new_tag['term_id'];
				}
			}

			$output['tag-name'] = $input['tag-name'];
		}

		if ( isset( $input['quantity'] ) ) {
			$output['quantity'] = self::sanitize_quantity( $input['quantity'] );
		}

		$output['hide-tag'] = ( isset( $input['hide-tag'] ) && $input['hide-tag'] );

		// Delete the featured post ids transient.
		self::delete_transient();

		return $output;
	}

	/**
	 * Sanitize quantity of featured posts.
	 *
	 * @static
	 * @access public
	 *
	 * @param int $input The value to sanitize.
	 *
	 * @return int A number between 1 and FeaturedContent::$max_posts.
	 * @since 1.0
	 *
	 */
	public static function sanitize_quantity( $input ) {
		$quantity = absint( $input );

		if ( $quantity > self::$max_posts ) {
			$quantity = self::$max_posts;
		} else if ( 1 > $quantity ) {
			$quantity = 1;
		}

		return $quantity;
	}

}
