<?php
/**
 * Elementor Dynamic Cookie Value tag.
 *
 * @link       https://chrisjayden.com
 * @since      1.0.0
 *
 * @package    Yummy_Cookies
 * @subpackage Yummy_Cookies/Yummy_Cookies_Elementor_Cookie_Value
 */
class Yummy_Cookies_Elementor_Cookie_Value extends \Elementor\Core\DynamicTags\Tag {

	/**
	 * Get Name
	 *
	 * Returns the Name of the tag
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return string
	 */
	public function get_name() {
		return 'yummy-cookies-cookie-value';
	}

	/**
	 * Get Title
	 *
	 * Returns the title of the Tag
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return string
	 */
	public function get_title() {
		return __( 'Cookie Value', 'yummy-cookies' );
	}

	/**
	 * Get Group
	 *
	 * Returns the Group of the tag
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return string
	 */
	public function get_group() {
		return 'yummy-cookies';
	}

	/**
	 * Get Categories
	 *
	 * Returns an array of tag categories
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return array
	 */
	public function get_categories() {
		return [ \Elementor\Modules\DynamicTags\Module::TEXT_CATEGORY ];
	}

	/**
	 * Register Controls
	 *
	 * @since 1.0.0
	 * @access protected
	 *
	 * @return void
	 */
	protected function _register_controls() {

		$variables = [
			'' => __( 'Select...', 'yummy-cookies' ),
		];

		foreach ( array_keys( $_COOKIE ) as $variable ) {
			$variables[ $variable ] = $variable;
		}

		$this->add_control(
			'key',
			[
				'label'   => __( 'Grab Existing Cookie', 'yummy-cookies' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'options' => $variables,
			]
		);

		$this->add_control(
			'custom_key',
			[
				'label'       => __( 'Custom Cookie Name', 'elementor-pro' ),
				'type'        => \Elementor\Controls_Manager::TEXT,
				'placeholder' => 'Cookie name',
				'condition'   => [
					'key' => '',
				],
			]
		);
	}

	/**
	 * Render
	 *
	 * Prints out the value of the cookie.
	 *
	 * @since 1.0.0
	 * @access public
	 *
	 * @return void
	 */
	public function render() {
		$cookie_value_settings = $this->get_settings( 'key' );

		if ( empty( $cookie_value_settings ) ) {
			$cookie_value_settings = $this->get_settings( 'custom_key' );
		}

		if ( ! $cookie_value_settings ) {
			return;
		}

		$cookie_value = isset( $_COOKIE[ $cookie_value_settings ] ) ? wp_unslash( $_COOKIE[ $cookie_value_settings ] ) : false; // @codingStandardsIgnoreLine.

		if ( ! $cookie_value ) {
			return;
		}

		echo wp_kses_post( $cookie_value );
	}
}
