<?php

namespace HulkPlugins\Woo\ProductDescriptionInLoop\Frontend\Services;

use HulkPlugins\Woo\ProductDescriptionInLoop\Core\SingletonTrait;
use HulkPlugins\Woo\ProductDescriptionInLoop\Support\SettingsConst;
use WC_Product;

defined( 'ABSPATH' ) || exit;

class DescriptionService {
	use SingletonTrait;

	/**
	 * Get long full product description
	 * @return string
	 */
	public function getDetailDescription(): string {
		global /** @var WC_Product $product */
		$product;

		return $product->get_description();
	}

	/**
	 * Get short product description
	 * @return string
	 */
	public function getShortDescription(): string {
		global /** @var WC_Product $product */
		$product;

		return $product->get_short_description();
	}

	/**
	 * Get custom loop description
	 * @return string
	 */
	public function getLoopDescription(): string {
		global /** @var WC_Product $product */
		$product;
		return (string) get_post_meta(
            $product->get_id(),
            'hulk_woo_pdil_loop_desc',
            true
        );
	}

	/**
	 * Get description based on type and worlds
	 * @param string $type
	 * @param int $num_words
	 *
	 * @return string
	 */
	public function getDescription( string $type, int $num_words ): string {
		$description = '';

		// Get description based on type
		switch ( $type ) {
			case SettingsConst::PRODUCT_DETAIL_DESCRIPTION:
				$description = $this->getDetailDescription();
				break;
			case SettingsConst::PRODUCT_SHORT_DESCRIPTION:
				$description = $this->getShortDescription();
				break;
			case SettingsConst::LOOP_DESCRIPTION:
				$description = $this->getLoopDescription();
				break;
		}

		// Properly strips all HTML tags including 'script' and 'style'.
		if ( $description ) {
			$description = wp_strip_all_tags( $description, true );
		}

		// Trims text to a certain number of words.
		if ( $num_words ) {
			$description = wp_trim_words(
				$description,
				$num_words,
				apply_filters( 'hulk_woo_pdil_trim_words_more', '...' )
			);
		}

		return $description;
	}
}
