<?php

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

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

/**
 * Plus Addons Dynamic Tag - Back to Shop URL
 *
 * Provides a dynamic tag for Elementor to output the back to shop url.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Back_To_Shop_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-back-to-shop-url';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Back to Shop 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-woocommerce' ];
	}

    /**
     * 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_advanced_section() {}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {
		$this->add_control(
			'tpd_fallback_url',
			[
				'label'       => esc_html__( 'Fallback URL', 'theplus' ),
				'type'        => \Elementor\Controls_Manager::URL,
				'dynamic'     => [
					'active' => false,
				],
				'description' => wp_kses_post(
					sprintf(
						'<p class="tp-controller-label-text"><i>%s</i></p>',
						esc_html__( 'Used if shop page is not set', 'theplus' )
					),
				),
			]
		);
	}

    /**
     * Render the dynamic product Back to Shop URL on frontend.
     *
     * Gets the current product ID and prints its Back to Shop URL.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {
		$shop_page_id = wc_get_page_id( 'shop' );

		if ( $shop_page_id && get_post_status( $shop_page_id ) === 'publish' ) {
			$url = get_permalink( $shop_page_id );
		} else {
			$settings = $this->get_settings();
			$url = $settings['tpd_fallback_url']['url'] ?? '';
		}

		if ( ! $url ) {
			return;
		}

		echo esc_url( $url );
	}
}
