<?php 
namespace HTMegaPro\Extension\Conditional_Display;
use Elementor\Repeater;
use Elementor\Controls_Manager;

class HTMegaConditionalDisplay_Elementor {

	private static $assets_load = null;

    private static $_instance = null;
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
	/**
	 * Contain all existing condition class instance
	 * @var array
	 */
	public static $conditions = [];

	/**
	 * Namespace of this class
	 * @var string
	 */
	public static $namespace = __NAMESPACE__;

	/**
	 * Contain condition's result of single element
	 * @var array
	 */
	protected $conditions_list_store = [];

    public function __construct() {
		//add condition section
		add_action( 'elementor/element/section/section_advanced/after_section_end', array( $this, 'register_controls' ), 10 );
		add_action( 'elementor/element/container/section_layout/after_section_end', array( $this, 'register_controls' ), 10 );
		add_action( 'elementor/element/column/section_advanced/after_section_end', array( $this, 'register_controls' ), 10 );
		add_action( 'elementor/element/common/_section_style/after_section_end', array( $this, 'register_controls' ), 10 );
		//enqueue js and css
		add_action( 'elementor/frontend/section/before_render', array( $this, 'check_assets_enqueue' ) );
		add_action( 'elementor/frontend/container/before_render', array( $this, 'check_assets_enqueue' ) );
		add_action( 'elementor/frontend/column/before_render', array( $this, 'check_assets_enqueue' ) );
		add_action( 'elementor/frontend/widget/before_render', array( $this, 'check_assets_enqueue' ) );
		//conditon check and render content
		$this->conditions_init();
		add_filter( 'elementor/frontend/section/should_render', [ $this, 'content_render' ], 10, 2 );
		add_filter( 'elementor/frontend/container/should_render', [ $this, 'content_render' ], 10, 2 );
		add_filter( 'elementor/frontend/column/should_render', [ $this, 'content_render' ], 10, 2 );
		add_filter( 'elementor/frontend/widget/should_render', [ $this, 'content_render' ], 10, 2 );

    }

	/**
	 * Contain all existing condition class key name
	 * @var array
	 */
	public $file_key = [
		'login_status',
		'user_role',
		'operating_system',
		'browser',
		'country',
		'url_string',
		'url_referrer',
		'recurring_visitor',
		'date_range',
		'date',
		'time',
		'day',
	];

	/**
	 * Condition File Include
	 * Set condition's class instance as value to  $conditions property
	 */
	public function conditions_init() {
		include_once HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/conditional-display/conditions/condition.php';
		foreach ( $this->file_key as $single_key ) {
			$file_name = str_replace( '_', '-', strtolower( $single_key ) );

			if ( file_exists( HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/conditional-display/conditions/' . $file_name . '.php' ) ) {
				include_once HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/conditional-display/conditions/' . $file_name . '.php';
			}

			$class_name = str_replace( '_', ' ', $single_key );
			$class_name = str_replace( ' ', '_', ucwords( $class_name ) );
			$class_name = static::$namespace . '\Conditions\\' . $class_name;

			if ( class_exists( $class_name ) ) {
				static::$conditions[ $single_key ] = new $class_name();
			}
		}
	}

	/**
	 * Render Content based on condition result
	 *
	 * @param $should_render
	 * @param $element
	 * @return bool
	 */
	public function content_render( $should_render, $element ) {
		$settings = $element->get_settings();


		if ( isset( $settings['htmega_condition_enable'] ) &&  'yes' === $settings['htmega_condition_enable'] ) {

			$id    = $element->get_id();
			$condition_to    = $settings['htmega_condition_to'];
			$lists = $settings['htmega_condition_list'];
			$this->conditions_list_store( $settings, $id, $lists );
			$check_result = $this->condition_check( $id, $settings['htmega_condition_relation'] );

			if ( ( 'show' === $condition_to && $check_result ) || ( 'hide' === $condition_to && false === $check_result ) ) {
				$should_render = true;
			} elseif ( ( 'show' === $condition_to && false === $check_result ) || ( 'hide' === $condition_to && $check_result ) ) {
				$should_render = false;
			}
		}

		//return true;
		return $should_render;
	}

	/**
	 * Condition Key Option For Repeater Field
	 * @return array
	 */
	public static function option_keys() {
		$options = [];
		foreach ( static::$conditions as $key => $value ) {
			$options[ $value->get_key_name() ] = $value->get_title();
		}
		return $options;
	}
	/**
	 * Add Repeater Control Field
	 *
	 * @param $repeater
	 */
	public function add_repeater_controls( $repeater ) {
		$condition = [];
		foreach ( static::$conditions as $key => $value ) {
			$repeater_field_id                   = 'htmega_condition_' . $value->get_key_name();
			$condition[ $value->get_key_name() ] = [
				'htmega_condition_key' => $value->get_key_name(),
			];
			$repeater->add_control(
				$repeater_field_id,
				$value->get_repeater_control( $condition[ $value->get_key_name() ] )
			);
		}
	}

	/**
	 * Condition Result Store in $conditions_list_store property
	 *
	 * @param $section_id
	 * @param array $lists
	 */
	protected function conditions_list_store( $settings, $section_id, $lists = [] ) {
		if ( ! $lists ) {
			return;
		}

		foreach ( $lists as $key => $list ) {
			$class    = static::$conditions[ $list['htmega_condition_key'] ];
			$operator = $list['htmega_condition_operator'];
			$item_key = 'htmega_condition_' . $list['htmega_condition_key'];
			$value    = $list[ $item_key ];
			$id       = $item_key . '_' . $list['_id'];
			$check    = $class->compare_value( $settings, $operator, $value );
			$this->conditions_list_store[ $section_id ][ $id ] = $check;
		}
	}

	/**
	 * Condition Check based on relation status
	 *
	 * @param $section_id
	 * @param $relation
	 * @return bool|void
	 */
	protected function condition_check( $section_id, $relation ) {
		$result = true;
		if ( ! array_key_exists( $section_id, $this->conditions_list_store ) ) {
			return;
		}

		if ( 'or' === $relation ) {
			//If any condition true
			$result = in_array( true, $this->conditions_list_store[ $section_id ] ) ? true : false;
		} else {
			//If any condition not true
			$result = in_array( false, $this->conditions_list_store[ $section_id ] ) ? false : true;
		}

		return $result;
	}

	/**
	 * Enqueue scripts.
	 *
	 * Enqueue required JS dependencies for the extension.
	 *
	 * @since 1.6.0
	 * @access public
	 */
	public static function enqueue_scripts() {

		wp_enqueue_script( 'htmega-pro-conditionals-script' );

	}

	 //Register Display option controls.
	public function register_controls( $element ) {
// . htmega_get_elementor_section_icon()
		$element->start_controls_section(
			'section_htmega_conditional_display',
			[
				'label' => __( 'HTMega Conditional Display', 'htmega-pro' ),
				'tab'   => Controls_Manager::TAB_ADVANCED,
			]
		);

		$element->add_control(
			'htmega_condition_enable',
			[
				'label'              => __( 'Display Condition', 'htmega-pro' ),
				'type'               => Controls_Manager::SWITCHER,
				'label_on'           => __( 'On', 'htmega-pro' ),
				'label_off'          => __( 'Off', 'htmega-pro' ),
				'return_value'       => 'yes',
				'default'            => '',
				'frontend_available' => true,
			]
		);

		$element->add_control(
			'htmega_condition_to',
			[
				'label'     => __( 'Element You Want To', 'htmega-pro' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'show',
				'options'   => [
					'show' => __( 'Show ', 'htmega-pro' ),
					'hide' => __( 'Hide', 'htmega-pro' ),
				],
				'condition' => [
					'htmega_condition_enable' => 'yes',
				],
			]
		);

		$element->add_control(
			'htmega_condition_relation',
			[
				'label'     => __( 'Display On', 'htmega-pro' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'and',
				'options'   => [
					'and' => __( 'All Conditions Met', 'htmega-pro' ),
					'or'  => __( 'Any Condition Met', 'htmega-pro' ),
				],
				'condition' => [
					'htmega_condition_enable' => 'yes',
				],
			]
		);

		$element->add_control(
			'htmega_time_zone',
			[
				'label'       => __( 'Timezone', 'htmega-pro' ),
				'type'        => Controls_Manager::SELECT,
				'description' => __( 'To change the Server', 'htmega-pro' ) . sprintf( ' <a href="%1$s" target="_blank">%2$s</a>', admin_url() . '/options-general.php', __( 'Timezone', 'htmega-pro' ) ),
				'default'     => 'server',
				'options'     => [
					'server' => __( 'Server Timezone', 'htmega-pro' ),
					'local'  => __( 'Local Timezone', 'htmega-pro' ),
				],
				'condition'   => [
					'htmega_condition_enable' => 'yes',
				],
			]
		);
		$repeater = new Repeater();

		$repeater->add_control(
			'htmega_condition_key',
			[
				'type'        => Controls_Manager::SELECT,
				'default'     => 'login_status',
				'label_block' => true,
				'options'     => static::option_keys(),
			]
		);

		$repeater->add_control(
			'htmega_condition_operator',
			[
				'type'        => Controls_Manager::SELECT,
				'default'     => 'is',
				'label_block' => true,
				'options'     => [
					'is'  => __( 'Is', 'htmega-pro' ),
					'not' => __( 'Is not', 'htmega-pro' ),
				],
			]
		);

		$this->add_repeater_controls( $repeater );

		$element->add_control(
			'htmega_condition_list',
			[
				'label'       => __( 'Conditions', 'htmega-pro' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'default'     => [
					[
						'htmega_condition_key'          => 'login_status',
						'htmega_condition_operator'     => 'is',
						'htmega_condition_login_status' => 'login',
					],
				],
				'title_field' => '{{{ htmega_condition_key.replace(/_/i, " ").split(" ").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ") }}}',
				'condition'   => [
					'htmega_condition_enable' => 'yes',
				],
			]
		);
		$element->end_controls_section();

	}


	 //Check Assets Enqueue
	public function check_assets_enqueue( $element ) {
		if ( self::$assets_load ) {
			return;
		}
		if ( 'yes' === $element->get_settings_for_display( 'htmega_condition_enable' ) ) {
			$this->enqueue_scripts();
			self::$assets_load = true;
		}
	}
}


HTMegaConditionalDisplay_Elementor::instance();