<?php
/**
 * Dynamic Tag: Post Terms
 *
 * @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_Terms
 * Outputs comma-separated post terms for a selected taxonomy.
 */
class Captwiki_Tag_Post_Terms extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-terms'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Terms', '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, Module::POST_META_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 {
		$taxonomies = get_taxonomies( array( 'public' => true ), 'objects' );
		$options    = array();
		foreach ( $taxonomies as $tax ) {
			$options[ $tax->name ] = $tax->label; }
		$this->add_control(
			'captwiki_taxonomy',
			array(
				'label'   => esc_html__( 'Taxonomy', 'captain-widgets-kit' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'options' => $options,
				'default' => 'category',
			)
		);
		$this->add_control(
			'captwiki_separator',
			array(
				'label'   => esc_html__( 'Separator', 'captain-widgets-kit' ),
				'type'    => \Elementor\Controls_Manager::TEXT,
				'default' => ', ',
				'ai'      => array( 'active' => false ),
			)
		);
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$post_id = get_the_ID();
		if ( ! $post_id ) {
			return; }
		$taxonomy  = $this->get_settings( 'captwiki_taxonomy' );
		$separator = $this->get_settings( 'captwiki_separator' );
		if ( empty( $taxonomy ) ) {
			return; }
		$terms = get_the_terms( $post_id, $taxonomy );
		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			return; }
		echo esc_html( implode( $separator, wp_list_pluck( $terms, 'name' ) ) );
	}
}
