<?php

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Plus Addons Dynamic Tag - Archive URL
 *
 * Provides a dynamic tag for Elementor to output the current archive URL.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Archive_URL extends Tag {

    /**
     * Unique dynamic tag name used internally by Elementor.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_name(): string {
		return 'plus-tag-archive-url';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Archive URL', 'theplus' );
	}

    /**
     * Registers the group under which this tag will appear.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_group(): array {
		return [ 'plus-opt-archive' ];
	}

    /**
     * Defines the category type (URL) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::URL_CATEGORY,
		];
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_advanced_section(): void {}

    /**
     * Render the dynamic archive url on frontend.
     *
     * Gets the current archive url and prints it.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		$url = '';

		if ( is_category() || is_tag() || is_tax() ) {

			$term = get_queried_object();

			if ( $term && isset( $term->term_id ) ) {
				$url = get_term_link( $term->term_id );
			}
		} elseif ( is_author() ) {
			$author_id = get_queried_object_id();
			$url = get_author_posts_url( $author_id );
		} elseif ( is_post_type_archive() ) {
			$post_type = get_query_var( 'post_type' );
			$url = get_post_type_archive_link( $post_type );
		} elseif ( is_date() ) {
			$url = get_day_link(
				get_query_var( 'year' ),
				get_query_var( 'monthnum' ),
				get_query_var( 'day' )
			);
		}

		if ( empty( $url ) ) {
			$url = home_url( add_query_arg( [], $_SERVER['REQUEST_URI'] ) );
		}

		echo esc_url( $url );
	}
}
