<?php
/**
 * Integrates Tasty Roundups with Yoast SEO's Open Graph.
 *
 * @package Tasty_Roundups
 */

namespace Tasty_Roundups\Integrations;

use Yoast\WP\SEO\Config\Schema_IDs;
use Yoast\WP\SEO\Context\Meta_Tags_Context;
use Yoast\WP\SEO\Generators\Schema\Abstract_Schema_Piece;

/**
 * Integrates Tasty Roundups with Yoast SEO's Open Graph.
 */
class ItemList_Graph_Piece_Yoast extends Abstract_Schema_Piece {

	/**
	 * Roundup block associated with this instance.
	 *
	 * @var array
	 */
	private $block;

	/**
	 * Whether or not an article is present on this page too.
	 *
	 * @var boolean
	 */
	private $using_article;

	/**
	 * HowTo_Graph_Piece constructor.
	 *
	 * @param Meta_Tags_Context $context A value object with context variables.
	 */
	public function __construct( Meta_Tags_Context $context ) {
		$this->context = $context;

		$this->using_article = false;
		add_filter( 'wpseo_schema_article', array( $this, 'filter_wpseo_schema_article' ) );
	}

	/**
	 * Keeps track of whether the Yoast SEO article schema is used.
	 *
	 * @param array $data Existing article schema data.
	 * @return array
	 */
	public function filter_wpseo_schema_article( $data ) {
		$this->using_article = true;
		if ( $this->is_needed() ) {
			// Use the how-to block as the main entity of the page.
			unset( $data['mainEntityOfPage'] );
		}
		return $data;
	}

	/**
	 * Determines whether or not a piece should be added to the graph.
	 *
	 * @return boolean
	 */
	public function is_needed() {
		if ( ! is_singular() ) {
			return false;
		}
		$post = get_post( $this->context->id );
		if ( empty( $post ) ) {
			return false;
		}
		$blocks = \Tasty_Roundups\Utils::parse_roundup_blocks(
			$post->post_content
		);
		if ( empty( $blocks ) ) {
			return false;
		}
		$this->block = array_shift( $blocks );
		return true;
	}

	/**
	 * Returns ItemList Schema data.
	 *
	 * @return array|boolean ItemList Schema on success, false on failure.
	 */
	public function generate() {
		$schema                     = \Tasty_Roundups\Distribution_Metadata::get_enriched_google_schema_for_roundup_block( $this->block );
		$schema['@id']              = $this->context->canonical . '#itemlist';
		$schema['isPartOf']         = array(
			'@id' => $this->using_article ? $this->context->canonical . Schema_IDs::ARTICLE_HASH : $this->context->main_schema_id,
		);
		$schema['mainEntityOfPage'] = $this->context->main_schema_id;
		return $schema;
	}
}
