<?php
/**
 * Dynamic Tag: Post Term URL
 *
 * @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_Term_URL
 * Outputs the URL of the first term in a selected taxonomy for the current post.
 */
class Captwiki_Tag_Post_Term_URL extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-term-url'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Term URL', '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::URL_CATEGORY, Module::TEXT_CATEGORY ); }
	/**
	 * 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',
			)
		);
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$post_id = get_the_ID();
		if ( ! $post_id ) {
			return; }
		$taxonomy = $this->get_settings( 'captwiki_taxonomy' );
		$taxonomy = $taxonomy ? $taxonomy : 'category';
		$terms    = get_the_terms( $post_id, $taxonomy );
		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			return; }
		$url = get_term_link( $terms[0] );
		if ( ! is_wp_error( $url ) ) {
			echo esc_url( $url ); }
	}
}
