<?php
namespace HTMegaPro\Extension\Conditional_Display\Conditions;

use Elementor\Controls_Manager;

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

/**
 * Class Url_Referrer
 * Contain all element of url referrer condition
 * @package HTMegaPro\Extension\Conditional_Display\Conditions
 */
class Url_Referrer extends Condition {

	/**
	 * Get Condition Key
	 *
	 * @return string|void
	 */
	public function get_key_name() {
		return 'url_referrer';
	}

	/**
	 * Get Condition Title
	 *
	 * @return string|void
	 */
	public function get_title() {
		return __( 'URL Referrer', 'htmega-pro' );
	}

	/**
	 * Get Repeater Control Field Value
	 *
	 * @param array $condition
	 * @return array|void
	 */
	public function get_repeater_control( array $condition ) {
			return [
				'label' 		=> $this->get_title(),
				'show_label' 	=> false,
				'type'        => Controls_Manager::TEXTAREA,
				'label_block' => true,
				'placeholder' => 'param1=value1
param2=value2',
				'description' => __( 'Enter each "referrer" parameter on a new line, following the format of param=value pairs.', 'htmega-pro' ),
				'condition' 		=> $condition,
			];
	}

	/**
	 * Compare Condition value
	 *
	 * @param $settings
	 * @param $operator
	 * @param $value
	 * @return bool|void
	 */
	public function compare_value( $settings, $operator, $value ) {

		if ( ! isset( $_SERVER['REQUEST_URI'] ) || empty( $_SERVER['REQUEST_URI'] ) ) {
			return;
		}

		$page_url = wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) );

		if ( ! $page_url || ! isset( $page_url['query'] ) || empty( $page_url['query'] ) ) {
			return false;
		}

		$query_params = explode( '&', $page_url['query'] );

		$value = explode( "\n", sanitize_textarea_field( $value ) );

		foreach ( $value as $index => $param ) {

			$is_strict = strpos( $param, '=' );
			if ( ! $is_strict ) {

				$ref = isset( $_GET[ $param ] ) ? sanitize_text_field( wp_unslash( $_GET[ $param ] ) ) : '';  // phpcs:ignore WordPress.Security.NonceVerification.Recommended

				$value[ $index ] = $value[ $index ] . '=' . rawurlencode( $ref );
			}
		}

		$condition_result = ! empty( array_intersect( $value, $query_params ) ) ? true : false;

		return htmega_value_compare( $condition_result, true, $operator );
	}
}
