<?php
/**
 * URL Conditions
 *
 * @package Captwiki_Advanced_URL_Condition
 * @since 1.0.0
 */

use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Plugin;

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

/**
 * Captwiki_URL_Conditions class.
 *
 * @since 1.0.0
 */
if ( ! class_exists( 'Captwiki_URL_Conditions' ) ) {

	/**
	 * Captwiki_URL_Conditions class.
	 *
	 * @since 1.0.0
	 */
	class Captwiki_URL_Conditions {

		/**
		 * Instance.
		 *
		 * @since 1.0.0
		 * @var Captwiki_URL_Conditions
		 */
		private static $instance = null;

		/**
		 * Get instance.
		 *
		 * @since 1.0.0
		 * @return Captwiki_URL_Conditions
		 * @static
		 */
		public static function get_instance() {
			if ( null === self::$instance ) {
				self::$instance = new self();
			}

			return self::$instance;
		}

		/**
		 * Constructor.
		 *
		 * @since 1.0.0
		 * @return void
		 */
		public function __construct() {
			add_action( 'elementor/element/common/_section_style/after_section_end', array( $this, 'register_controls' ), 10, 2 );
			add_action( 'elementor/element/column/section_advanced/after_section_end', array( $this, 'register_controls' ), 10, 2 );
			add_action( 'elementor/element/section/section_advanced/after_section_end', array( $this, 'register_controls' ), 10, 2 );

			if ( Plugin::$instance->experiments->is_feature_active( 'container' ) ) {
				add_action( 'elementor/element/container/section_layout/after_section_end', array( $this, 'register_controls' ), 10, 2 );
			}

			add_filter( 'elementor/frontend/widget/should_render', array( $this, 'should_render_content' ), 10, 2 );
			add_filter( 'elementor/frontend/column/should_render', array( $this, 'should_render_content' ), 10, 2 );
			add_filter( 'elementor/frontend/section/should_render', array( $this, 'should_render_content' ), 10, 2 );
			add_filter( 'elementor/frontend/container/should_render', array( $this, 'should_render_content' ), 10, 2 );
		}

		/**
		 * Register controls.
		 *
		 * @since 1.0.0
		 * @param Element_Base $element The element being rendered.
		 * @return void
		 */
		public function register_controls( $element ) {
			$element->start_controls_section(
				'captwiki_advanced_url_match_section',
				array(
					'label' => esc_html__( 'URL Condition (Param / String)', 'captain-widgets-kit' ),
					'tab'   => Controls_Manager::TAB_ADVANCED,
				)
			);

			$element->add_control(
				'captwiki_enable_advanced_url_match',
				array(
					'label' => esc_html__( 'Enable URL Match', 'captain-widgets-kit' ),
					'type'  => Controls_Manager::SWITCHER,
				)
			);

			$repeater = new Repeater();

			$repeater->add_control(
				'match_type',
				array(
					'label'   => esc_html__( 'Type', 'captain-widgets-kit' ),
					'type'    => Controls_Manager::SELECT,
					'options' => array(
						'parameter' => 'URL Parameter',
						'string'    => 'URL String',
					),
					'default' => 'parameter',
				)
			);

			$repeater->add_control(
				'param_key',
				array(
					'label'       => esc_html__( 'Parameter Name', 'captain-widgets-kit' ),
					'type'        => Controls_Manager::TEXT,
					'label_block' => true,
					'condition'   => array(
						'match_type' => 'parameter',
					),
				)
			);

			$repeater->add_control(
				'match_condition',
				array(
					'label'   => esc_html__( 'Condition', 'captain-widgets-kit' ),
					'type'    => Controls_Manager::SELECT,
					'options' => array(
						'is'     => 'is',
						'is_not' => 'is not',
					),
					'default' => 'is',
				)
			);

			$repeater->add_control(
				'param_value',
				array(
					'label'       => esc_html__( 'Value', 'captain-widgets-kit' ),
					'type'        => Controls_Manager::TEXT,
					'label_block' => true,
				)
			);

			$element->add_control(
				'captwiki_advanced_url_conditions',
				array(
					'label'       => esc_html__( 'Conditions', 'captain-widgets-kit' ),
					'type'        => Controls_Manager::REPEATER,
					'fields'      => $repeater->get_controls(),
					'title_field' => '{{{ match_type }}} {{{ param_key }}} {{{ match_condition }}} {{{ param_value }}}',
					'condition'   => array(
						'captwiki_enable_advanced_url_match' => 'yes',
					),
				)
			);

			$element->end_controls_section();
		}

		/**
		 * Should render content.
		 *
		 * @since 1.0.0
		 * @param bool         $should_render Whether the content should be rendered.
		 * @param Element_Base $element The element being rendered.
		 * @return bool The updated should_render value.
		 */
		public function should_render_content( $should_render, $element ) {

			if ( ! $should_render ) {
				return false;
			}

			$settings = $element->get_settings();

			if ( 'yes' !== $settings['captwiki_enable_advanced_url_match'] || empty( $settings['captwiki_advanced_url_conditions'] ) ) {
				return $should_render;
			}

			$request_uri  = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
			$url          = wp_parse_url( filter_var( $request_uri, FILTER_SANITIZE_FULL_SPECIAL_CHARS ) );
			$query_string = isset( $url['query'] ) ? $url['query'] : '';
			$parameters   = explode( '&', $query_string );

			foreach ( $settings['captwiki_advanced_url_conditions'] as $rule ) {
				$type      = isset( $rule['match_type'] ) ? $rule['match_type'] : '';
				$key       = trim( isset( $rule['param_key'] ) ? $rule['param_key'] : '' );
				$value     = trim( isset( $rule['param_value'] ) ? $rule['param_value'] : '' );
				$condition = isset( $rule['match_condition'] ) ? $rule['match_condition'] : 'is';

				if ( 'parameter' === $type && ! empty( $key ) && ! empty( $value ) ) {
					$actual = null;

					if ( isset( $_GET[ $key ] ) ) {
						// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking URL params, no action or save.
						$actual = trim( sanitize_text_field( wp_unslash( $_GET[ $key ] ) ) );
					}

					if ( 'is' === $condition && $actual !== $value ) {
						return false;
					}

					if ( 'is_not' === $condition && $actual === $value ) {
						return false;
					}
				}

				if ( 'string' === $type && ! empty( $value ) ) {
					$found = strpos( $request_uri, $value ) !== false;

					if ( 'is' === $condition && ! $found ) {
						return false;
					}

					if ( 'is_not' === $condition && $found ) {
						return false;
					}
				}
			}

			return true;
		}
	}
}

Captwiki_URL_Conditions::get_instance();
