<?php
/**
 * Dynamic Tag: Post Excerpt
 *
 * @package captain-widgets-kit
 * @since   1.1.0
 */

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
/**
 * Class Captwiki_Tag_Post_Excerpt
 * Outputs the current post excerpt as an Elementor dynamic tag.
 */
class Captwiki_Tag_Post_Excerpt extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-excerpt'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Excerpt', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-post' ); }
	/**
	 * Get tag categories.
	 *
	 * @return array
	 */
	public function get_categories(): array {
		return array( Module::TEXT_CATEGORY ); }
	/**
	 * Check whether settings are required.
	 *
	 * @return bool
	 */
	public function is_settings_required() {
		return true; }
	/**
	 * Register tag controls.
	 *
	 * @return void
	 */
	protected function register_controls(): void {
		$this->add_control(
			'excerpt_length',
			array(
				'label'   => esc_html__( 'Excerpt Length (words)', 'captain-widgets-kit' ),
				'type'    => \Elementor\Controls_Manager::NUMBER,
				'default' => 30,
				'min'     => 5,
				'max'     => 200,
			)
		);
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$post_id = get_the_ID();
		if ( ! $post_id ) {
			return; }
		$post = get_post( $post_id );
		if ( ! $post ) {
			return; }
		$excerpt = $post->post_excerpt;
		if ( empty( $excerpt ) ) {
			$content        = wp_strip_all_tags( strip_shortcodes( $post->post_content ) );
			$excerpt_length = $this->get_settings( 'excerpt_length' );
			$excerpt        = wp_trim_words( $content, $excerpt_length ? $excerpt_length : 30 );
		}
		echo wp_kses_post( $excerpt );
	}
}
