<?php
namespace AIOSEO\Plugin\Pro\Meta;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use AIOSEO\Plugin\Common\Meta as CommonMeta;

/**
 * Handles the description.
 *
 * @since 4.0.0
 */
class Description extends CommonMeta\Description {
	/**
	 * Returns the term description.
	 *
	 * @since 4.0.0
	 *
	 * @param  \WP_Term $term    The term object.
	 * @param  boolean  $default Whether we want the default value, not the post one.
	 * @return string            The term description.
	 */
	public function getTermDescription( $term, $default = false ) {
		if ( ! is_a( $term, 'WP_Term' ) ) {
			return '';
		}

		static $terms = [];
		if ( isset( $terms[ $term->term_id ] ) ) {
			return $terms[ $term->term_id ];
		}

		$description = '';
		$metaData    = aioseo()->meta->metaData->getMetaData( $term );
		if ( ! empty( $metaData->description ) && ! $default ) {
			$description = $this->helpers->prepare( $metaData->description, $term->term_id );
		}

		if (
			in_array( 'autogenerateDescriptions', aioseo()->internalOptions->deprecatedOptions, true ) &&
			! aioseo()->options->deprecated->searchAppearance->advanced->autogenerateDescriptions
		) {
			$terms[ $term->term_id ] = $description;

			return $terms[ $term->term_id ];
		}

		$dynamicOptions = aioseo()->dynamicOptions->noConflict();
		if ( ! $description && $dynamicOptions->searchAppearance->taxonomies->has( $term->taxonomy ) ) {
			$description = $this->helpers->prepare( aioseo()->dynamicOptions->searchAppearance->taxonomies->{$term->taxonomy}->metaDescription, false, $default );
		}

		$terms[ $term->term_id ] = $description ? $description : $this->helpers->prepare( term_description( $term->term_id ), $term->term_id, $default );

		return $terms[ $term->term_id ];
	}

	/**
	 * Retrieve the default description for the taxonomy.
	 *
	 * @since 4.0.17
	 *
	 * @param  string $taxonomy The taxonomy description.
	 * @return string           The description.
	 */
	public function getTaxonomyDescription( $taxonomy ) {
		$dynamicOptions = aioseo()->dynamicOptions->noConflict();

		return $dynamicOptions->searchAppearance->taxonomies->has( $taxonomy, false ) ?
			$dynamicOptions->{$taxonomy}->metaDescription :
			'';
	}
}