<?php
/**
 * Dynamic Tag: Archive Title
 *
 * @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_Archive_Title
 * Outputs the current archive or post title with optional context prefix.
 */
class Captwiki_Tag_Archive_Title extends Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-archive-title'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Archive Title', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-archive' ); }
	/**
	 * 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(
			'captwiki_include_context',
			array(
				'label'   => esc_html__( 'Include Context', 'captain-widgets-kit' ),
				'type'    => \Elementor\Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$include_context = 'yes' === $this->get_settings( 'captwiki_include_context' );
		$title           = '';
		if ( is_archive() || is_home() || is_post_type_archive() || is_category() || is_tag() || is_tax() || is_author() || is_date() ) {
			$title = get_the_archive_title();
			if ( ! $include_context ) {
				$title = wp_strip_all_tags( $title );
				$title = preg_replace( '/^[^:]+:\s*/u', '', $title );
			}
		} elseif ( is_singular() ) {
			$post_id = get_the_ID();
			$title   = get_the_title( $post_id );
			if ( $include_context ) {
				$obj = get_post_type_object( get_post_type( $post_id ) );
				if ( $obj && isset( $obj->labels->singular_name ) ) {
					$title = $obj->labels->singular_name . ': ' . $title;
				}
			}
		} else {
			$qo = get_queried_object();
			if ( isset( $qo->name ) ) {
				$title = $qo->name; } elseif ( isset( $qo->post_title ) ) {
				$title = $qo->post_title; }
		}
		echo wp_kses_post( $title );
	}
}
