<?php
/**
 * MetaBooster Main Class
 *
 * @package MetaBoosters
 */

namespace Optikit\MetaBoosters;

/**
 * Class MetaBooster
 */
final class Meta_Booster extends \Optikit\DediData\Singleton {

	/**
	 * Constructor.
	 */
	protected function __construct() {
		if ( is_admin() || wp_doing_ajax() || wp_is_json_request() ) {
			return;
		}
		add_action( 'wp_head', array( $this, 'add_meta_description' ) );
	}

	/**
	 * Generates a meta description tag based on different conditions like front page, archive, excerpt, or post content.
	 *
	 * @return void
	 * @SuppressWarnings(PHPMD.Superglobals)
	 */
	public function add_meta_description() {
		// phpcs:ignore SlevomatCodingStandard.Variables.DisallowSuperGlobalVariable.DisallowedSuperGlobalVariable
		$post = $GLOBALS['post'];

		if ( is_front_page() ) {
			$content = $this->prepare_description_content( get_bloginfo( 'name' ) . ' - ' . get_bloginfo( 'description' ) . ' - ' . $post->post_content );
		} elseif ( is_archive() ) {
			$page_content = '';
			if ( is_paged() ) {
				$page_content = ' - ' . esc_html__( 'Page:', 'optikit' ) . get_query_var( 'paged' );
			}
			$content = $this->prepare_description_content( wp_title( '', false ) . $page_content );
			if ( '' !== get_the_archive_description() ) {
				$content = $this->prepare_description_content( get_the_archive_description() . $page_content );
			}
		} elseif ( has_excerpt() ) {
			// Return the excerpt() if it exists other truncate.
			$content = $this->prepare_description_content( $post->post_excerpt );
		} elseif ( '' !== $post->post_content ) {
			$content = $this->prepare_description_content( $post->post_content );
		}

		if ( '' !== $content ) {
			$content = $this->prepare_description_content( wp_title( '', false ) );
		}


		echo '<meta name="description" content="' . esc_attr( wp_strip_all_tags( stripslashes( $content ) ) ) . '" />' . \PHP_EOL;
	}

	/**
	 * Strips shortcodes and trims the content to 35 words with an ellipsis.
	 *
	 * @param string $content Takes a piece of content as input and processes it to return a shortened version with a maximum of 35 words.
	 * @return string Final trimmed and shortcode-free content is being returned.
	 */
	protected function prepare_description_content( string $content ) {
		return strip_shortcodes( wp_trim_words( $content, 35, '...' ) );
	}
}
