<?php
/**
 * Dynamic Tag: Back To Shop URL.
 *
 * @package captain-widgets-kit
 */

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 Captwiki_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 'captwiki-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', 'captain-widgets-kit' );
	}

	/**
	 * Registers the group under which this tag will appear.
	 *
	 * @since 6.4.5
	 * @return array
	 */
	public function get_group(): array {

		return array( 'captwiki-woocommerce' );
	}

	/**
	 * Defines the category type (URL) for this dynamic tag.
	 *
	 * @since 6.4.5
	 * @return array
	 */
	public function get_categories(): array {

		return array(
			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',
			array(
				'label'       => esc_html__( 'Fallback URL', 'captain-widgets-kit' ),
				'type'        => \Elementor\Controls_Manager::URL,
				'dynamic'     => array(
					'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', 'captain-widgets-kit' )
					),
				),
			)
		);
	}

	/**
	 * 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          = isset( $settings['tpd_fallback_url']['url'] ) ? $settings['tpd_fallback_url']['url'] : '';
		}

		if ( ! $url ) {
			return;
		}

		echo esc_url( $url );
	}
}
