<?php
/**
 * Woostify template builder addons
 *
 * @package Woostify Pro
 */

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( 'Woostify_Theme_Builder_Addons_Condition' ) ) {

    class Woostify_Theme_Builder_Addons_Condition {
        /**
         * Instance of Woostify_Theme_Builder_Addons_Condition
         *
         * @var Woostify_Theme_Builder_Addons_Condition
         */
        private static $instance = null;

        /**
         * Current page type
         *
         * @since  1.0.0
         *
         * @var $current_page_type
         */
        private static $current_page_type = null;

        /**
         * CUrrent page data
         *
         * @since  1.0.0
         *
         * @var $current_page_data
         */
        private static $current_page_data = array();

        /**
         * Instance of Woostify_Theme_Builder_Addons_Condition
         *
         * @return Woostify_Theme_Builder_Addons_Condition Instance of Woostify_Theme_Builder_Addons_Condition
         */
        public static function instance() {
            if ( ! isset( self::$instance ) ) {
                self::$instance = new self();
            }

            return self::$instance;
        }

        /**
         * Constructor
         */
        public function __construct() {

            add_action( 'admin_enqueue_scripts', [ $this, 'woostify_condition_enqueue_scripts' ] );
            add_action( 'wp_ajax_woostify_builder_get_all_taxs', array( $this, 'woostify_builder_get_all_taxs_func' ) );
            add_action( 'wp_ajax_nopriv_woostify_builder_get_all_taxs', array( $this, 'woostify_builder_get_all_taxs_func' ) );
            add_action( 'wp_ajax_woostify_builder_get_all_posts', array( $this, 'woostify_builder_get_all_posts_func' ) );
            add_action( 'wp_ajax_nopriv_woostify_builder_get_all_posts', array( $this, 'woostify_builder_get_all_posts_func' ) );
            add_action( 'save_post', array( $this, 'save_wp_builder_addon_condition' ), 10, 2 );

        }

        public function render_condition_settings_field() {

            global $post;

            $template = get_post_meta( $post->ID, 'woostify_wp_builder_addon_template', true );

            ?>
            <div class="ui-popup">
                <div class="ui-popup-inner">
                    <span type="button" class="ui-popup-close">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M12 13.06l3.712 3.713 1.061-1.06L13.061 12l3.712-3.712-1.06-1.06L12 10.938 8.288 7.227l-1.061 1.06L10.939 12l-3.712 3.712 1.06 1.061L12 13.061z"></path></svg>
                    </span>
                    <div class="ui-popup-content-top">
                        <h4 class="ui-popup-heading"><?php esc_html_e( 'Display And User Role Settings','woostify-pro' ); ?></h4>
                    </div>
                    <div class="ui-popup-content">
                        <div class="ui-popup-content-body">
                            <div class="woostify-metabox-option-settings display-on">
                                <?php
                                $name = 'woostify_builder_target_include_locations';
                                $target_rule = 'include-locations';
                                $include_locations = get_post_meta( $post->ID, $name, true )? get_post_meta( $post->ID, $name, true ) : ['default'] ;

                                $this->load_autocomplete_condition( $name, $target_rule );
                                $this->load_autocomplete_input_field( $name );
                                ?>
                                <h4 class="label"><?php esc_html_e( 'Display On', 'woostify-pro' ); ?></h4>
                                <div class="woostify-metabox-option-wrap">
                                    <div class="woostify-condition <?php echo $target_rule; ?>" data-condition-location="<?php echo $target_rule; ?>">                                       
                                        <?php foreach ($include_locations as $key => $location) { ?>
                                            <div class="woostify-target-rule-builder-wrap">
                                                <?php
                                                $this->render_target_rule_settings_field($key, $name, $target_rule, $location);                  
                                                ?>
                                                <span class="woostify-target-rule-condition-delete dashicons dashicons-dismiss"></span>
                                                <div class="wooostify-target-rule-condition-search"></div>
                                            </div>
                                        <?php } ?>
                                    </div>
                                    <div class="action">
                                        <a class="add-action-button woostify-target-rule-condition-add" data-action="include-rule" data-target-rule-key="<?php echo $name; ?>"  data-target-rule="<?php echo $target_rule; ?>" href="#">
                                            <?php esc_html_e( 'Add Display Rule', 'woostify-pro' ); ?>
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php if( $template != 'woostify_builder_404'): ?>
                            <div class="woostify-metabox-option-settings not-display">
                                <?php 
                                $name = 'woostify_builder_target_exclude_locations';
                                $target_rule = 'exclude-locations';
                                $exclude_locations = get_post_meta( $post->ID, $name, true )? get_post_meta( $post->ID, $name, true ) : ['default'] ;
                                
                                $this->load_autocomplete_condition( $name, $target_rule );
                                $this->load_autocomplete_input_field( $name );
                                ?>
                                <h4 class="label"><?php esc_html_e( 'Not Display On', 'woostify-pro' ); ?></h4>
                                <div class="woostify-metabox-option-wrap">	
                                    <div class="woostify-condition <?php echo $target_rule; ?>" data-condition-location="<?php echo $target_rule; ?>">
                                        <?php foreach ($exclude_locations as $key => $location) { ?>
                                            <div class="woostify-target-rule-builder-wrap">
                                                <?php
                                                $this->render_target_rule_settings_field($key, $name, $target_rule, $location);                  
                                                ?>
                                                <span class="woostify-target-rule-condition-delete dashicons dashicons-dismiss"></span>
                                                <div class="wooostify-target-rule-condition-search"></div>
                                            </div>
                                        <?php } ?>
                                    </div>
                                    <div class="action">
                                        <a class="add-action-button woostify-target-rule-condition-add" data-action="exclusion-rule" data-target-rule-key="<?php echo $name; ?>"  data-target-rule="<?php echo $target_rule; ?>" href="#">
                                            <?php esc_html_e( 'Add Exclusion Rule', 'woostify-pro' ); ?>
                                        </a>
                                    </div>
                                </div>						
                            </div>
                            <?php endif; ?>
                            <div class="woostify-metabox-option-settings users">
                                <?php 
                                $name = 'woostify_builder_target_users_rule'; 
                                $target_rule = 'user-rule';
                                $users_rule = get_post_meta( $post->ID, $name, true )? get_post_meta( $post->ID, $name, true ) : ['default'] ;
                                $this->load_autocomplete_condition_users( $name, $target_rule );
                                ?>
                                <h4 class="label"><?php esc_html_e( 'User Roles', 'woostify-pro' ); ?></h4>
                                <div class="woostify-metabox-option-wrap">
                                    <div class="woostify-condition <?php echo $target_rule; ?>" data-condition-location="<?php echo $target_rule; ?>">
                                    <?php foreach ($users_rule as $key => $location) { ?>
                                        <div class="woostify-target-rule-builder-wrap">
                                            <?php
                                            $this->render_target_rule_settings_field_users($name, $location);                  
                                            ?>
                                            <span class="woostify-target-rule-condition-delete dashicons dashicons-dismiss"></span>
                                        </div>
                                    <?php } ?>
                                    </div>
                                    <div class="action">
                                        <a class="add-action-button woostify-target-rule-condition-add" data-action="user-rule" data-target-rule-key="<?php echo $name; ?>" data-target-rule="<?php echo $target_rule; ?>" href="#">
                                            <?php esc_html_e( 'Add User Roles', 'woostify-pro' ); ?>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="ui-popup-content-bottom">
                            <span class="description"><?php esc_html_e( 'Make sure to save your post for change to take effect','woostify-pro' ); ?></span>
                            <button type="button" class="button return-to-post" data-post-id="<?php echo $post->ID; ?>">
                                <?php esc_html_e( 'Return To Post', 'woostify-pro' ); ?>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <?php

        }


        public function render_target_rule_settings_field_users($name, $value) {
            global $wp_roles;

            $all_roles = $wp_roles->roles;
            $editable_roles = apply_filters('editable_roles', $all_roles);

            $input_name     = $name;
            $saved_values   = $value;
            $rule = isset( $saved_values )? $saved_values : 'default';
            $selection_options = !empty( $editable_roles )? $editable_roles : '';

            ?>
            <select name="<?php echo esc_attr( $input_name ) . '[]'; ?>" class="woostify-target-rule-condition <?php echo $name; ?>">
                <option value="all" <?php selected( 'all', $rule ); ?>> <?php echo __( 'All', 'woostify-pro' ); ?></option>
                <option value="logged-in" <?php selected( 'logged-in', $rule ); ?>> <?php echo __( 'Logged In', 'woostify-pro' ); ?></option>
                <option value="logged-out" <?php selected( 'logged-out', $rule ); ?>> <?php echo __( 'Logged Out', 'woostify-pro' ); ?></option>
                
                <?php foreach ( $selection_options as $group => $group_data ) { ?>
                    <option value="<?php echo $group ?>" <?php selected( $group, $rule ); ?>> <?php echo $group_data['name']; ?></option>;
                <?php } ?>
            </select>
            <?php

        }

        public function load_autocomplete_condition_users( $name, $target_rule ) {
            global $wp_roles;

            $all_roles = $wp_roles->roles;
            $editable_roles = apply_filters('editable_roles', $all_roles);

            $input_name = $name; 
            $rule_type = $target_rule;            

            $selection_options = !empty( $editable_roles )? $editable_roles : '';
            
            $output = '';
            $output .= '<script type="text/html" id="tmpl-wp-builder-target-rule-' . $rule_type . '-condition">';            
            /* Condition Selection */
            $output .= '<div class="woostify-target-rule-builder-wrap" >';
            $output .= '<select name="' . esc_attr( $input_name ) . '[]" class="woostify-target-rule-condition '.$input_name.'">';
            $output .= '<option value="all">' . __( 'All', 'woostify-pro' ) . '</option>';
            $output .= '<option value="logged-in">' . __( 'Logged In', 'woostify-pro' ) . '</option>';
            $output .= '<option value="logged-out">' . __( 'Logged Out', 'woostify-pro' ) . '</option>';
    
            foreach ( $selection_options as $group => $group_data ) {
                
                $output .= '<option value="' . $group . '">' . $group_data['name'] .'</option>';
                
            }

            $output .= '</select>';
            $output .= '<span class="woostify-target-rule-condition-delete dashicons dashicons-dismiss"></span>';

            $output .= '</div> <!-- wp-builder-target-rule-condition -->';

            $output .= '</script>';

            echo $output;
        }

        public function get_special_id_obj($post_id, $name, $index){

            $special_name_ids = $name . '_special_ids';
            $special_values_ids = get_post_meta( $post_id, $special_name_ids, true);
            $index_type = 'index_'.$index;
            $index_type_cat = 'index_cat_'.$index;
            
            if( !empty( $special_values_ids ) ){
                foreach ( $special_values_ids as $key => $item ) {

                    if( strpos($item, $index_type) !== FALSE ){
  
                        $special_values = explode(":",$item);
                        $args = array(
                            'post_type' => $special_values[1],
                            'posts_per_page' => 1,
                            'post__in' => [$special_values[0]],
                        );
                        $posts = get_posts( $args );

                        $result = array();

                        if( !empty( $posts ) ){
                            $result = array(
                                'ID' => $posts[0]->ID,
                                'type' => $posts[0]->post_type,
                                'title' => $posts[0]->post_title,
                                'index' => $index_type,
                            );
                        }

                        return $result;
                    }

                    if( strpos($item, $index_type_cat) !== FALSE ){
  
                        $special_values = explode(":",$item);
                        $term_id = $special_values[0]; 
                        $taxonomy = $special_values[1];
                        $term = get_term( $term_id, $taxonomy );

                        $result = array();
          
                        if( !empty( $term ) ){
                            $result = array(
                                'ID' => $term->term_id,
                                'type' => $term->taxonomy,
                                'title' => $term->name,
                                'index' => $index_type_cat,
                            );
                        }
                        
                        return $result;
                    }

                }
            }

            return '';
        }
        

        public function render_target_rule_settings_field($index, $name, $taget_rule, $value){

            global $post;
            $template = get_post_meta( $post->ID, 'woostify_wp_builder_addon_template', true );
            $i = $index;
            $input_name     = $name;
            $saved_values   = $value;
            $rule = isset( $saved_values )? $saved_values : 'default';
            $selection_options = $this->get_location_selections( $template );
            $special_ids = isset($selection_options['special-ids'])? $selection_options['special-ids']['value'] : [];
            
            ?>
            <select name="<?php echo esc_attr( $input_name ) . '[]'; ?>" class="woostify-target-rule-condition <?php echo esc_attr( $input_name ); ?>" data-index="<?php echo $i; ?>">
                <option value=""><?php echo __( 'Select', 'woostify-pro' ); ?></option>
            <?php
                foreach ( $selection_options as $group => $group_data ) {
                    echo '<optgroup label="' . $group_data['label'] . '">';
             
                    foreach ( $group_data['value'] as $opt_key => $opt_value ) {
                        ?>
                        <option value="<?php echo $opt_key; ?>" <?php selected( $opt_key, $rule ); ?>> <?php echo $opt_value; ?></option>;
                        <?php
                    }

                    echo '</optgroup>';
                }
            ?>
            </select>
            <?php 
            $special_obj = $this->get_special_id_obj( $post->ID, $input_name, $i );
         
            $special_obj_id = !empty($special_obj)? $special_obj['ID'] : '';
            $special_obj_type = !empty($special_obj)? $special_obj['type'] : '';
            $special_obj_title = !empty($special_obj)? $special_obj['title'] : '';
            $special_obj_index = !empty($special_obj)? $special_obj['index'] : '';
            
            $value = $special_obj_id . ':' . $special_obj_type . ':' . $special_obj_index;

            if( array_key_exists($rule, $special_ids) ){

                ?>
                <input class="woostify-target-rule-condition <?php echo array_key_exists($rule, $special_ids)? '' : 'woostify-hidden'; ?>" 
                    data-special-key="<?php echo esc_attr( $rule ); ?>"
                    type="text" 
                    name="<?php echo esc_attr( $input_name ) . '_ids[]'; ?>"
                    value="<?php echo esc_attr( $special_obj_title ); ?>"
                    placeholder="<?php echo esc_html__('Type to search by title or ID','woostify-pro'); ?>"
                    data-index="<?php echo esc_attr( $i ); ?>"
                >
                <input 
                    type="hidden"
                    name="<?php echo esc_attr( $input_name ) . '_special_ids[]'; ?>"
                    value="<?php echo esc_attr( $value ); ?>"
                    data-index="<?php echo esc_attr( $i ); ?>"
                >
                <?php 
            }else {
                if( !empty($special_obj) ){
                    ?>
                    <input class="woostify-target-rule-condition <?php echo (strpos($rule, $special_obj_type) !== false)? '' : 'woostify-hidden'; ?>" 
                        data-special-key="<?php echo esc_attr( $rule ); ?>"
                        type="text" 
                        name="<?php echo esc_attr( $input_name ) . '_ids[]'; ?>"
                        value="<?php echo esc_attr( $special_obj_title ); ?>"
                        placeholder="<?php echo esc_html__('Type to search by title or ID','woostify-pro'); ?>"
                        data-index="<?php echo esc_attr( $i ); ?>"
                    >
                    <input 
                        type="hidden"
                        name="<?php echo esc_attr( $input_name ) . '_special_ids[]'; ?>"
                        value="<?php echo esc_attr( $value ); ?>"
                        data-index="<?php echo esc_attr( $i ); ?>"
                    >
                    <?php 
                }
            }
     
            ?>
            
            <?php
        }

        public function load_autocomplete_input_field( $name ){

            global $post;
            $template = get_post_meta( $post->ID, 'woostify_wp_builder_addon_template', true );
            $input_name = $name;          

            $selection_options = $this->get_location_selections( $template );
            $special_ids = isset($selection_options['special-ids'])? $selection_options['special-ids']['value'] : [];
            
            $output = '';
            foreach ( $special_ids as $special_key => $value ) {
                $output .= '<script type="text/html" id="tmpl-' . $input_name . '-' . $special_key . '-input-field">';            
                $output .= '<input  
                                class="woostify-target-rule-condition" 
                                data-special-key="'. esc_attr( $special_key ) .'" 
                                data-special-id="'.esc_attr( $input_name.'-'.$special_key ).'" 
                                data-post-id="'.esc_attr( $post->ID ).'" 
                                type="text" 
                                name="'.esc_attr( $input_name ) . '_ids[]"
                                placeholder="'.esc_html__('Type to search by title or ID','woostify-pro').'" 
                                value=""
                                data-index=""
                            >'; 
                $output .= '<input 
                                type="hidden"
                                name="'.esc_attr( $input_name ) . '_special_ids[]"
                                value=""
                                data-index=""
                            >';       
                $output .= '</script>';
            }
            $output .= '<script type="text/html" id="tmpl-' . $input_name . '-post-tax-input-field">';            
            $output .= '<input  
                            class="woostify-target-rule-condition" 
                            data-special-key="post-tax" 
                            data-special-id="'.esc_attr( $input_name.'-post-tax' ).'" 
                            data-post-id="'.esc_attr( $post->ID ).'" 
                            type="text" 
                            name="'.esc_attr( $input_name ) . '_ids[]"
                            placeholder="'.esc_html__('Type to search by title or ID','woostify-pro').'" 
                            value=""
                            data-index=""
                        >'; 
            $output .= '<input 
                            type="hidden"
                            name="'.esc_attr( $input_name ) . '_special_ids[]"
                            value=""
                            data-index=""
                        >';       
            $output .= '</script>';

            echo $output;
        }

        public function load_autocomplete_condition( $name, $target_rule ) {

            global $post;
            $template = get_post_meta( $post->ID, 'woostify_wp_builder_addon_template', true );
            $input_name = $name; 
            $rule_type = $target_rule;            

            $selection_options = $this->get_location_selections( $template );
            
            $output = '';
            $output .= '<script type="text/html" id="tmpl-wp-builder-target-rule-' . $rule_type . '-condition">';            
            /* Condition Selection */
            $output .= '<div class="woostify-target-rule-builder-wrap" >';
            $output .= '<select name="' . esc_attr( $input_name ) . '[]" class="woostify-target-rule-condition '.$input_name.'" data-index="">';
            $output .= '<option value="">' . __( 'Select', 'woostify-pro' ) . '</option>'; 

            foreach ( $selection_options as $group => $group_data ) {
                $output .= '<optgroup label="' . $group_data['label'] . '">';
                
                foreach ( $group_data['value'] as $opt_key => $opt_value ) {
                    $output .= '<option value="' . $opt_key . '"> ' . $opt_value .'</option>';
                }
                
                $output .= '</optgroup>';
            }
            $output .= '</select>';

            $output .= '<span class="woostify-target-rule-condition-delete dashicons dashicons-dismiss"></span>';

            $output .= '<div class="wooostify-target-rule-condition-search"></div>';

            $output .= '</div> <!-- wp-builder-target-rule-condition -->';

            $output .= '</script>';

            echo $output;
        }

        public function get_location_selections( $template_type = false ){

            $args = array(
                'public'   => true,
                '_builtin' => true,
            );
    
            $post_types = get_post_types( $args, 'objects' ); 
            unset( $post_types['attachment'] );
            $args['_builtin'] = false;
            $custom_post_type = get_post_types( $args, 'objects' );            
            $post_types = apply_filters( 'location_rule_post_types', array_merge( $post_types, $custom_post_type ) );

            unset( $post_types['callback'] );
            unset( $post_types['product_filter'] );
            unset( $post_types['mega_menu'] );
            unset( $post_types['hf_builder'] );
            unset( $post_types['size_guide'] );
            unset( $post_types['woo_builder'] );
            unset( $post_types['wp_builder_addon'] );
            unset( $post_types['e-landing-page']);
            unset( $post_types['elementor_library'] );

            $selection_options = array();

            if( $template_type == 'woostify_builder_404' ){
                $selection_options = array(
                    'special-pages' => array(
                        'label' => __( 'Special Pages', 'woostify-pro' ),
                        'value' => array(
                            'special-404'    => __( '404 Page', 'woostify-pro' ),
                        ),
                    ),
                );

                return $selection_options;
            }
            
            $special_pages = array(
                'special-404'    => __( '404 Page', 'woostify-pro' ),
                'special-search' => __( 'Search Page', 'woostify-pro' ),
                'special-blog'   => __( 'Blog / Posts Page', 'woostify-pro' ),
                'special-front'  => __( 'Front Page', 'woostify-pro' ),
                'special-date'   => __( 'Date Archive', 'woostify-pro' ),
                'special-author' => __( 'Author Archive', 'woostify-pro' ),
            );

            $special_ids = array(
                'special-page_id' => __( 'Page ID', 'woostify-pro' ),
                'special-post_id'    => __( 'Post ID', 'woostify-pro' ),
                'special-post_taxonomy_id'   => __( 'Post Taxonomy ID', 'woostify-pro' ),
                'special-product_id'   => __( 'Product ID', 'woostify-pro' ),
                'special-product_taxonomy_id' => __( 'Product Taxonomy ID', 'woostify-pro' ),
                'special-taxonomy_id'  => __( 'Custom Taxonomy ID', 'woostify-pro' ),
            );
    
            if ( class_exists( 'WooCommerce' ) ) {
                $special_pages['special-woo-shop'] = __( 'WooCommerce Shop Page', 'woostify-pro' );
            }

            if ( 'woostify_builder_single' === $template_type ) {

                unset( $post_types['page'] );
                unset( $special_ids[ 'special-post_taxonomy_id' ] );
                unset( $special_ids[ 'special-product_taxonomy_id' ] );
                unset( $special_ids[ 'special-taxonomy_id' ] );
                unset( $special_ids[ 'special-page_id' ] );

				$global_val = array(
					'basic-singulars' => __( 'All Singulars', 'woostify-pro' ),
				);
			} elseif ( 'woostify_builder_archive' === $template_type ) {
 
                unset( $special_ids[ 'special-page_id' ] );
                unset( $special_ids[ 'special-post_id' ] );
                unset( $special_ids[ 'special-product_id' ] );

				$global_val = array(
					'basic-archives' => __( 'All Archives', 'woostify-pro' ),
				);

			} else {
				$global_val = array(
					'basic-global'    => __( 'Entire Website', 'woostify-pro' ),
					'basic-singulars' => __( 'All Singulars', 'woostify-pro' ),
					'basic-archives'  => __( 'All Archives', 'woostify-pro' ),
				);

			}
    
            $selection_options = array(
                'basic'         => array(
                    'label' => __( 'Basic', 'woostify-pro' ),
                    'value' => $global_val,
                ),
    
                'special-pages' => array(
                    'label' => __( 'Special Pages', 'woostify-pro' ),
                    'value' => $special_pages,
                ),

                'special-ids' => array(
                    'label' => __( 'Special ID', 'woostify-pro' ),
                    'value' => $special_ids,
                ),
            );

            if ( 'woostify_builder_single' === $template_type ) {
                unset( $selection_options[ 'special-pages' ] );
            }

            $args = array(
                'public' => true,
            );
    
            $taxonomies = get_taxonomies( $args, 'objects' );
    
            if ( ! empty( $taxonomies ) ) {
                foreach ( $taxonomies as $taxonomy ) {
                    foreach ( $post_types as $post_type ) {
                        $post_opt = $this->get_post_target_rule_options( $post_type, $taxonomy, $template_type );
    
                        if ( isset( $selection_options[ $post_opt['post_key'] ] ) ) {
                            if ( ! empty( $post_opt['value'] ) && is_array( $post_opt['value'] ) ) {
                                foreach ( $post_opt['value'] as $key => $value ) {
                                    if ( ! in_array( $value, $selection_options[ $post_opt['post_key'] ]['value'] ) ) {
                                        $selection_options[ $post_opt['post_key'] ]['value'][ $key ] = $value;
                                    }
                                }
                            }
                        } else {
                            $selection_options[ $post_opt['post_key'] ] = array(
                                'label' => $post_opt['label'],
                                'value' => $post_opt['value'],
                            );
                        }
                    }
                }
            }
            
            return $selection_options;
    
        }


        /**
		 * Get target rules for generating the markup for rule selector.
		 *
		 * @since  1.0.0
		 *
		 * @param object $post_type post type parameter.
		 * @param object $taxonomy taxonomy for creating the target rule markup.
		 * @param mixed  $consider_type consider type for dealing with rule options.
		 */
		public static function get_post_target_rule_options( $post_type, $taxonomy, $consider_type = false ) {

			$post_key    = str_replace( ' ', '-', strtolower( $post_type->label ) );
			$post_label  = ucwords( $post_type->label );
			$post_name   = $post_type->name;
			$post_option = array();

			if ( 'woostify_builder_archive' !== $consider_type ) {
				/* translators: %s post label */
				$all_posts                          = sprintf( __( 'All %s', 'woostify-pro' ), $post_label );
				$post_option[ $post_name . '|all' ] = $all_posts;
                
                $taxonomies = get_object_taxonomies( $post_name, 'objects' );
                if( !empty( $taxonomies ) ){
                    foreach ($taxonomies as $tax_slug => $tax) {
                        if( $tax->public && $tax->show_ui ){
                            $tax_label = ucwords( $tax->label );
                            $post_option[ 'post-tax-'.$tax_slug ] = sprintf( __( '%s', 'woostify-pro' ), $tax_label );
                        }
                    }
                }
			}

			if ( 'pages' != $post_key && 'woostify_builder_single' !== $consider_type ) {
				/* translators: %s post label */
				$all_archive                                = sprintf( __( 'All %s Archive', 'woostify-pro' ), $post_label );
				$post_option[ $post_name . '|all|archive' ] = $all_archive;
			}

			if ( 'woostify_builder_single' !== $consider_type ) {
				if ( in_array( $post_type->name, $taxonomy->object_type ) ) {
					$tax_label = ucwords( $taxonomy->label );
					$tax_name  = $taxonomy->name;

					/* translators: %s taxonomy label */
					$tax_archive = sprintf( __( 'All %s Archive', 'woostify-pro' ), $tax_label );

					$post_option[ $post_name . '|all|taxarchive|' . $tax_name ] = $tax_archive;
				}
			}

			$post_output['post_key'] = $post_key;
			$post_output['label']    = $post_label;
			$post_output['value']    = $post_option;

			return $post_output;
		}

        public function get_location_by_key( $key ) {

            $location_selection = $this->get_location_selections();            
    
            foreach ( $location_selection as $location_grp ) {
                if ( isset( $location_grp['value'][ $key ] ) ) {
                    return $location_grp['value'][ $key ];
                }
            }
    
            if ( strpos( $key, 'post-' ) !== false ) {
                $post_id = (int) str_replace( 'post-', '', $key );
                return get_the_title( $post_id );
            }
    
            // taxonomy options.
            if ( strpos( $key, 'tax-' ) !== false ) {
                $tax_id = (int) str_replace( 'tax-', '', $key );
                $term   = get_term( $tax_id );
    
                if ( ! is_wp_error( $term ) ) {
                    $term_taxonomy = ucfirst( str_replace( '_', ' ', $term->taxonomy ) );
                    return $term->name . ' - ' . $term_taxonomy;
                } else {
                    return '';
                }
            }
    
            return $key;
        }

        /**
         * Get current page type
         *
         * @since  1.0.0
         *
         * @return string Page Type.
         */
        public function get_current_page_type() {
            if ( null === self::$current_page_type ) {
                $page_type  = '';
                $current_id = false;

                if ( is_404() ) {
                    $page_type = 'is_404';
                } elseif ( is_search() ) {
                    $page_type = 'is_search';
                } elseif ( is_archive() ) {
                    $page_type = 'is_archive';

                    if ( is_category() || is_tag() || is_tax() ) {
                        $page_type = 'is_tax';
                    } elseif ( is_date() ) {
                        $page_type = 'is_date';
                    } elseif ( is_author() ) {
                        $page_type = 'is_author';
                    } elseif ( function_exists( 'is_shop' ) && is_shop() ) {
                        $page_type = 'is_woo_shop_page';
                    }
                } elseif ( is_home() ) {
                    $page_type = 'is_home';
                } elseif ( is_front_page() ) {
                    $page_type  = 'is_front_page';
                    $current_id = get_the_id();
                } elseif ( is_singular() ) {
                    $page_type  = 'is_singular';
                    $current_id = get_the_id();
                } else {
                    $current_id = get_the_id();
                }

                self::$current_page_data['ID'] = $current_id;
                self::$current_page_type       = $page_type;
            }

            return self::$current_page_type;
        }


        /**
         * Meta option post.
         *
         * @since  1.0.0
         * @param  string $post_type Post Type.
         * @param  array  $option meta option name.
         *
         * @return false | object
         */
        public function get_meta_option_post( $post_type, $option ) {
            $page_meta = ( isset( $option['page_meta'] ) && '' != $option['page_meta'] ) ? $option['page_meta'] : false;

            if ( false !== $page_meta ) {
                $current_post_id = isset( $option['current_post_id'] ) ? $option['current_post_id'] : false;
                $meta_id         = get_post_meta( $current_post_id, $option['page_meta'], true );

                if ( false !== $meta_id && '' != $meta_id ) {
                    self::$current_page_data[ $post_type ][ $meta_id ] = array(
                        'id'       => $meta_id,
                        'location' => '',
                    );

                    return self::$current_page_data[ $post_type ];
                }
            }

            return false;
        }

        public function get_posts_by_conditions( $post_type, $option ) {
            global $wpdb;
            global $post;
    
            $post_type = $post_type ? esc_sql( $post_type ) : esc_sql( $post->post_type );
    
            $current_page_type = $this->get_current_page_type();
    
            self::$current_page_data[ $post_type ] = array();
    
            $option['current_post_id'] = self::$current_page_data['ID'];
            $meta_wp_builder           = $this->get_meta_option_post( $post_type, $option );
            
            /* Meta option is enabled */
            if ( false === $meta_wp_builder ) {
                $current_post_type = esc_sql( get_post_type() );
                $current_post_id   = false;
                $q_obj             = get_queried_object();
    
                $location = isset( $option['location'] ) ? esc_sql( $option['location'] ) : '';
    
                $query = "SELECT p.ID, pm.meta_value FROM {$wpdb->postmeta} as pm
                            INNER JOIN {$wpdb->posts} as p ON pm.post_id = p.ID
                            WHERE pm.meta_key = '{$location}'
                            AND p.post_type = '{$post_type}'
                            AND p.post_status = 'publish'";
    
                $orderby = ' ORDER BY p.post_date DESC';
    
                /* Entire Website */
                $meta_args = "pm.meta_value LIKE '%\"basic-global\"%'";
                
                switch ( $current_page_type ) {
                    case 'is_404':
                        $meta_args .= " OR pm.meta_value LIKE '%\"special-404\"%'";
                        break;
                    case 'is_search':
                        $meta_args .= " OR pm.meta_value LIKE '%\"special-search\"%'";
                        break;
                    case 'is_archive':
                    case 'is_tax':
                    case 'is_date':
                    case 'is_author':
                        $meta_args .= " OR pm.meta_value LIKE '%\"basic-archives\"%'";
                        $meta_args .= " OR pm.meta_value LIKE '%\"{$current_post_type}|all|archive\"%'";
    
                        if ( 'is_tax' == $current_page_type && ( is_category() || is_tag() || is_tax() ) ) {
                            if ( is_object( $q_obj ) ) {
                                $meta_args .= " OR pm.meta_value LIKE '%\"{$current_post_type}|all|taxarchive|{$q_obj->taxonomy}\"%'";
                                $meta_args .= " OR pm.meta_value LIKE '%\"tax-{$q_obj->term_id}\"%'";
                                $meta_args .= " OR pm.meta_value LIKE '%\"special-post_taxonomy_id\"%'";
                                $meta_args .= " OR pm.meta_value LIKE '%\"special-product_taxonomy_id\"%'";
                                $meta_args .= " OR pm.meta_value LIKE '%\"special-taxonomy_id\"%'";
                            }
                        } elseif ( 'is_date' == $current_page_type ) {
                            $meta_args .= " OR pm.meta_value LIKE '%\"special-date\"%'";
                        } elseif ( 'is_author' == $current_page_type ) {
                            $meta_args .= " OR pm.meta_value LIKE '%\"special-author\"%'";
                        }
                        break;
                    case 'is_home':
                        $meta_args .= " OR pm.meta_value LIKE '%\"special-blog\"%'";
                        break;
                    case 'is_front_page':
                        $current_id      = esc_sql( get_the_id() );
                        $current_post_id = $current_id;
                        $meta_args      .= " OR pm.meta_value LIKE '%\"special-front\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"{$current_post_type}|all\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"post-{$current_id}\"%'";
                        break;
                    case 'is_singular':
                        $current_id      = esc_sql( get_the_id() );
                        $current_post_id = $current_id;
                        $meta_args      .= " OR pm.meta_value LIKE '%\"basic-singulars\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"{$current_post_type}|all\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"post-{$current_id}\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"special-post_id\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"special-page_id\"%'";
                        $meta_args      .= " OR pm.meta_value LIKE '%\"special-product_id\"%'";
                        
                        $taxonomies = get_object_taxonomies( $q_obj->post_type );
                        $terms      = wp_get_post_terms( $q_obj->ID, $taxonomies );
                        foreach ( $taxonomies as $key => $taxonomy ) {
                            $meta_args .= " OR pm.meta_value LIKE '%\"post-tax_{$taxonomy}\"%'";
                        }
                        foreach ( $terms as $key => $term ) {
                            $meta_args .= " OR pm.meta_value LIKE '%\"tax-{$term->term_id}-single-{$term->taxonomy}\"%'";
                        }

                        break;
                    case 'is_woo_shop_page':
                        $meta_args .= " OR pm.meta_value LIKE '%\"special-woo-shop\"%'";
                        break;
                    case '':
                        $current_post_id = get_the_id();

                        break;
                }
                
                // Ignore the PHPCS warning about constant declaration.
                // @codingStandardsIgnoreStart
                $posts  = $wpdb->get_results( $query . ' AND (' . $meta_args . ')' . $orderby );
                // @codingStandardsIgnoreEnd
                
                foreach ( $posts as $local_post ) {
                    $special_data = [];
                    
                    $include_location_ids = 'woostify_builder_target_include_locations_special_ids';
                    $include_location_special_ids = get_post_meta( $local_post->ID, $include_location_ids, true );
                    if( !empty( $include_location_special_ids ) ){
                        $special_data = array_merge($special_data, $include_location_special_ids);
                    }
                    if( !empty( $special_data ) ){
                
                        foreach ( $special_data as $key => $data ) {
                            $explode_data = explode( ":", $data );
                            $id = $explode_data[0];
                            $type = $explode_data[1];
                            $index = $explode_data[2];
                            if( strpos($data, $index ) !== FALSE ){
                                if( is_category() || is_tag() || is_tax() || is_singular() ){
                                   
                                    $obj = get_queried_object();
                                    $current_term_id = !empty($obj)? $obj->term_id : '';
                                    $current_taxonomy = !empty($obj)? $obj->taxonomy : '';
                                    $current_id = get_the_ID();
                                    $taxs_post_type = [];

                                    if( $current_id ){
                                        $post_obj = get_post( $current_id );
                                        $post_obj_post_type = $post_obj->post_type;
                                        $taxonomies = get_object_taxonomies( $post_obj_post_type, 'objects' );
                                        
                                        if( !empty( $taxonomies ) ){
                                            foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
                                                if( $taxonomy->public && $taxonomy->show_ui ){
                                                    $terms = get_the_terms( $current_id , $taxonomy_slug );
                                                    $terms_ids = [];
                                                    if ( ! empty( $terms ) ) {
                                                        foreach ( $terms as $term ) {
                                                            $terms_ids[] = $term->term_id;
                                                        }
                                                    }
                                                    $taxs_post_type[$taxonomy_slug] = $terms_ids;
                                                }
                                            }
                                        }
                                    }

                                    if( $current_taxonomy == $type && $id == $current_term_id ||
                                    ( !empty( $taxs_post_type ) && isset( $taxs_post_type[$type] ) && in_array( $id,$taxs_post_type[$type]) )){
                                        self::$current_page_data[ $post_type ][ $local_post->ID ] = array(
                                            'id'       => $local_post->ID,
                                            'location' => unserialize( $local_post->meta_value ),
                                        );
                                    }

                                }else{

                                    if( $current_post_type == $type && $id == get_the_id() ){
                                        self::$current_page_data[ $post_type ][ $local_post->ID ] = array(
                                            'id'       => $local_post->ID,
                                            'location' => unserialize( $local_post->meta_value ),
                                        );
                                    }
                                    
                                }
                                
                            }

    
                        }
                    }else{
                        self::$current_page_data[ $post_type ][ $local_post->ID ] = array(
                            'id'       => $local_post->ID,
                            'location' => unserialize( $local_post->meta_value ),
                        );
                    }
                    
                }
                
                $option['current_post_id'] = $current_post_id;
                
                $this->remove_exclusion_rule_posts( $post_type, $option );
                $this->remove_user_rule_posts( $post_type, $option );
               
            }
            
            return self::$current_page_data[ $post_type ];
        }

        /**
         * Remove exclusion rule posts.
         *
         * @since  1.0.0
         * @param  string $post_type Post Type.
         * @param  array  $option meta option name.
         */
        public function remove_exclusion_rule_posts( $post_type, $option ) {
            $exclusion       = isset( $option['exclusion'] ) ? $option['exclusion'] : '';
            $current_post_id = isset( $option['current_post_id'] ) ? $option['current_post_id'] : false;
            
            foreach ( self::$current_page_data[ $post_type ] as $post_id => $data ) {
                $exclusion_rules = get_post_meta( $post_id, $exclusion, true );
                $is_exclude      = $this->parse_layout_display_condition( $current_post_id, $post_id, $exclusion_rules );
                
                if ( $is_exclude ) {
                    unset( self::$current_page_data[ $post_type ][ $post_id ] );
                }

            }

        }

        /**
         * Remove user rule posts.
         *
         * @since  1.0.0
         * @param  int   $post_type Post Type.
         * @param  array $option meta option name.
         */
        public function remove_user_rule_posts( $post_type, $option ) {
            $users           = isset( $option['users'] ) ? $option['users'] : '';
            $current_post_id = isset( $option['current_post_id'] ) ? $option['current_post_id'] : false;

            foreach ( self::$current_page_data[ $post_type ] as $post_id => $data ) {
                $user_rules = get_post_meta( $post_id, $users, true );
                $is_user    = $this->parse_user_role_condition( $current_post_id, $user_rules );

                if ( ! $is_user ) {
                    unset( self::$current_page_data[ $post_type ][ $post_id ] );
                }
            }
        }

        /**
         * Checks for the display condition for the current page/
         *
         * @param  int   $post_id Current post ID.
         * @param  array $rules   Array of rules Display on | Exclude on.
         *
         * @return boolean      Returns true or false depending on if the $rules match for the current page and the layout is to be displayed.
         */
        public function parse_layout_display_condition( $current_post_id, $post_id, $rules ) {
            $display           = false;
            $current_post_type = get_post_type( $current_post_id );
            $exclude_location_ids = 'woostify_builder_target_exclude_locations_special_ids';
            $special_data = get_post_meta( $post_id, $exclude_location_ids, true );
             
            if ( isset( $rules ) && is_array( $rules ) && ! empty( $rules ) ) {
                foreach ( $rules as $key => $rule ) {
                    if ( strrpos( $rule, 'all' ) !== false ) {
                        $rule_case = 'all';
                    } else {
                        $rule_case = $rule;
                    }

                    switch ( $rule_case ) {
                        case 'basic-global':
                            $display = true;
                            break;

                        case 'basic-singulars':
                            if ( is_singular() ) {
                                $display = true;
                            }
                            break;

                        case 'basic-archives':
                            if ( is_archive() ) {
                                $display = true;
                            }
                            break;

                        case 'special-404':
                            if ( is_404() ) {
                                $display = true;
                            }
                            break;

                        case 'special-search':
                            if ( is_search() ) {
                                $display = true;
                            }
                            break;

                        case 'special-blog':
                            if ( is_home() ) {
                                $display = true;
                            }
                            break;

                        case 'special-front':
                            if ( is_front_page() ) {
                                $display = true;
                            }
                            break;

                        case 'special-date':
                            if ( is_date() ) {
                                $display = true;
                            }
                            break;

                        case 'special-author':
                            if ( is_author() ) {
                                $display = true;
                            }
                            break;

                        case 'special-woo-shop':
                            if ( function_exists( 'is_shop' ) && is_shop() ) {
                                $display = true;
                            }
                            break;

                        case 'all':
                            $rule_data = explode( '|', $rule );

                            $post_type     = isset( $rule_data[0] ) ? $rule_data[0] : false;
                            $archieve_type = isset( $rule_data[2] ) ? $rule_data[2] : false;
                            $taxonomy      = isset( $rule_data[3] ) ? $rule_data[3] : false;
                            if ( false === $archieve_type ) {
                                $current_post_type = get_post_type( $current_post_id );

                                if ( false !== $post_id && $current_post_type == $post_type ) {
                                    $display = true;
                                }
                            } else {
                                if ( is_archive() ) {
                                    $current_post_type = get_post_type();
                                    if ( $current_post_type == $post_type ) {
                                        if ( 'archive' == $archieve_type ) {
                                            $display = true;
                                        } elseif ( 'taxarchive' == $archieve_type ) {
                                            $obj              = get_queried_object();
                                            $current_taxonomy = '';
                                            if ( '' !== $obj && null !== $obj ) {
                                                $current_taxonomy = $obj->taxonomy;
                                            }

                                            if ( $current_taxonomy == $taxonomy ) {
                                                $display = true;
                                            }
                                        }
                                    }
                                }
                            }
                            break;

                        case 'special-post_id':
                            
                            if( $current_post_type == 'post' && !empty( $special_data )){
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $post_type = $data_explode[1];
                                    if( $current_post_id == $id ){
                                        $display = true;
                                    }
                                }
                            }

                            break;
                            
                        case 'special-page_id':
                            
                            if( $current_post_type == 'page' && !empty( $special_data ) ){
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $post_type = $data_explode[1];
                                    if( $current_post_id == $id ){
                                        $display = true;
                                    }
                                }
                            }
                           
                            break;
                        
                        case 'special-product_id':

                            if( $current_post_type == 'produt' && !empty( $special_data ) ){
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $post_type = $data_explode[1];
                                    if( $current_post_id == $id ){
                                        $display = true;
                                    }
                                }
                            }

                            break;

                        case 'special-custom_post_type_id':
                            
                            if( !empty( $special_data ) ){
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $post_type = $data_explode[1];
                                    if( $current_post_type == $post_type && $current_post_id == $id ){
                                        $display = true;
                                    }
                                }
                            }
                                
                            break;

                        case 'special-post_taxonomy_id':
                            
                            if ( ( is_category() || is_tag() || is_singular() ) && !empty( $special_data ) ) {
                                $obj              = get_queried_object();
                                $current_term_id = !empty($obj)? $obj->term_id : '';
                                $current_taxonomy = !empty($obj)? $obj->taxonomy : '';
                                $current_id = get_the_ID();
                                $taxs_post_type = [];

                                if( $current_id ){
                                    $post_obj = get_post( $current_id );
                                    $post_obj_post_type = $post_obj->post_type;
                                    $taxonomies = get_object_taxonomies( $post_obj_post_type, 'objects' );
                                    
                                    if( !empty( $taxonomies ) ){
                                        foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
                                            if( $taxonomy->public && $taxonomy->show_ui ){
                                                $terms = get_the_terms( $current_id , $taxonomy_slug );
                                                $terms_ids = [];
                                                if ( ! empty( $terms ) ) {
                                                    foreach ( $terms as $term ) {
                                                        $terms_ids[] = $term->term_id;
                                                    }
                                                }
                                                $taxs_post_type[$taxonomy_slug] = $terms_ids;
                                            }
                                        }
                                    }
                                }
                                
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $tax_type = $data_explode[1];
                                    
                                    if( ($current_term_id == $id && $current_taxonomy == $tax_type) || 
                                    ( !empty( $taxs_post_type ) && isset( $taxs_post_type[$tax_type] ) && in_array( $id, $taxs_post_type[$tax_type]) ) ){
                                        $display = true;
                                    }
                                }
                                
                            }
                                
                            break;

                        case 'special-product_taxonomy_id':
                            
                            if ( ( is_tax() || is_product() ) && !empty( $special_data ) ) {
                                $obj              = get_queried_object();
                                $current_term_id = !empty($obj)? $obj->term_id : '';
                                $current_taxonomy = !empty($obj)? $obj->taxonomy : '';
                                $product_id = get_the_ID();
                                $taxs_product = [];
                                if( $product_id ){
                                    $product = get_post( $product_id);
                                    $product_post_type = $product->post_type;
                                    $taxonomies = get_object_taxonomies( $product_post_type, 'objects' );
                                    
                                    if( !empty( $taxonomies ) ){
                                        foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
                                            if( $taxonomy->public && $taxonomy->show_ui ){
                                                $terms = get_the_terms( $product_id , $taxonomy_slug );
                                                $terms_ids = [];
                                                if ( ! empty( $terms ) ) {
                                                    foreach ( $terms as $term ) {
                                                        $terms_ids[] = $term->term_id;
                                                    }
                                                }
                                                $taxs_product[$taxonomy_slug] = $terms_ids;
                                            }
                                        }
                                    }
                                }
                  
                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $tax_type = $data_explode[1];
                                    
                                    if( ( $current_term_id == $id && $current_taxonomy == $tax_type ) ||
                                    ( !empty( $taxs_product ) && isset( $taxs_product[$tax_type] ) && in_array( $id,$taxs_product[$tax_type]) ) ){
                                        $display = true;
                                        
                                    }
                                }
                                
                            }

                            break;

                        case 'special-taxonomy_id':

                            if ( ( is_tax() || is_singular() ) && !empty( $special_data ) ) {
                                $obj              = get_queried_object();
                                $current_term_id = !empty($obj)? $obj->term_id : '';
                                $current_taxonomy = !empty($obj)? $obj->taxonomy : '';
                                $current_id = get_the_ID();
                                $taxs_post_type = [];

                                if( $current_id ){
                                    $post_obj = get_post( $current_id );
                                    $post_obj_post_type = $post_obj->post_type;
                                    $taxonomies = get_object_taxonomies( $post_obj_post_type, 'objects' );
                                    
                                    if( !empty( $taxonomies ) ){
                                        foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
                                            if( $taxonomy->public && $taxonomy->show_ui ){
                                                $terms = get_the_terms( $current_id , $taxonomy_slug );
                                                $terms_ids = [];
                                                if ( ! empty( $terms ) ) {
                                                    foreach ( $terms as $term ) {
                                                        $terms_ids[] = $term->term_id;
                                                    }
                                                }
                                                $taxs_post_type[$taxonomy_slug] = $terms_ids;
                                            }
                                        }
                                    }
                                }

                                foreach ( $special_data as $key => $data ) {
                                    $data_explode = explode(":", $data);
                                    $id = $data_explode[0];
                                    $tax_type = $data_explode[1];

                                    if( ($current_term_id == $id && $current_taxonomy == $tax_type) || 
                                    ( !empty( $taxs_post_type) && isset( $taxs_post_type[$tax_type] ) && in_array( $id,$taxs_post_type[$tax_type]) ) ){
                                        $display = true;
                                    }

                                }
                            }

                            break;

                        default:
                            // check taxonomy post
                            if( strpos( $rule_case, "post-tax" ) !== false ){
                                if ( ( is_tax() || is_singular() ) && !empty( $special_data ) ) {
                                    $obj              = get_queried_object();
                                    $current_term_id = !empty($obj)? $obj->term_id : '';
                                    $current_taxonomy = !empty($obj)? $obj->taxonomy : '';
                                    $current_id = get_the_ID();
                                    $taxs_post_type = [];
    
                                    if( $current_id ){
                                        $post_obj = get_post( $current_id );
                                        $post_obj_post_type = $post_obj->post_type;
                                        $taxonomies = get_object_taxonomies( $post_obj_post_type, 'objects' );
                                        
                                        if( !empty( $taxonomies ) ){
                                            foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
                                                if( $taxonomy->public && $taxonomy->show_ui ){
                                                    $terms = get_the_terms( $current_id , $taxonomy_slug );
                                                    $terms_ids = [];
                                                    if ( ! empty( $terms ) ) {
                                                        foreach ( $terms as $term ) {
                                                            $terms_ids[] = $term->term_id;
                                                        }
                                                    }
                                                    $taxs_post_type[$taxonomy_slug] = $terms_ids;
                                                }
                                            }
                                        }
                                    }
    
                                    foreach ( $special_data as $key => $data ) {
                                        $data_explode = explode(":", $data);
                                        $id = $data_explode[0];
                                        $tax_type = $data_explode[1];
    
                                        if( ($current_term_id == $id && $current_taxonomy == $tax_type) || 
                                        ( !empty( $taxs_post_type) && isset( $taxs_post_type[$tax_type] ) && in_array( $id,$taxs_post_type[$tax_type]) ) ){
                                            $display = true;
                                        }
    
                                    }
                                }
                            }
                            
                            break;
                    }

                    if ( $display ) {
                        break;
                    }
                }
            }

            return $display;
        }


        /**
         * Parse user role condition.
         *
         * @since  1.0.0
         * @param  int   $post_id Post ID.
         * @param  Array $rules   Current user rules.
         *
         * @return boolean  True = user condition passes. False = User condition does not pass.
         */
        public function parse_user_role_condition( $post_id, $rules ) {
            $display = true;

            if ( is_array( $rules ) && ! empty( $rules ) ) {
                $display = false;

                foreach ( $rules as $i => $rule ) {
                    switch ( $rule ) {
                        case '':
                        case 'all':
                            $display = true;
                            break;

                        case 'logged-in':
                            if ( is_user_logged_in() ) {
                                $display = true;
                            }
                            break;

                        case 'logged-out':
                            if ( ! is_user_logged_in() ) {
                                $display = true;
                            }
                            break;

                        default:
                            if ( is_user_logged_in() ) {
                                $current_user = wp_get_current_user();

                                if ( isset( $current_user->roles )
                                        && is_array( $current_user->roles )
                                        && in_array( $rule, $current_user->roles )
                                    ) {
                                    $display = true;
                                }
                            }
                            break;
                    }

                    if ( $display ) {
                        break;
                    }
                }
            }

            return $display;
        }

        public function get_supported_post_types() {
            $post_types = array();

            $potential_post_types = array_keys(get_post_types([
				'public'   => true,
				'_builtin' => false,
			]));

            $potential_post_types = array_values(array_diff($potential_post_types, [
                // 'post',
                'page',
                // 'product',
                'cmplz-processing',
				'cmplz-dataleak',
				'iamport_payment',
				'wpcw_achievements',
				'zoom-meetings',
				'pafe-formabandonment',
				'pafe-form-database',
				'pafe-form-booking',
				'piotnetforms',
				'piotnetforms-aban',
				'piotnetforms-data',
				'piotnetforms-book',
				'piotnetforms-fonts',
				'jet-popup',
				'jet-smart-filters',
				'jet-theme-core',
				'jet-woo-builder',
				'jet-engine',
				'jet-engine-booking',
				'jet_options_preset',
				'jet-menu',
				'adsforwp',
				'adsforwp-groups',
				'popup',
				'ct_content_block',
				'elementor_library',
				'brizy_template',
				'editor-story',
				'forum',
				'topic',
				'reply',
				'blockslider',
				'mailpoet_page',
				'ha_nav_content',
				'course',
				'lesson',
				'atbdp_orders',
				'at_biz_dir',
				'gspbstylebook',

				// tutor lms
				'tutor_quiz',
				'tutor_assignments',
				'tutor_zoom_meeting',

				// learn dash
				'ld-exam',
				'groups',

				// 'tribe_events',
				'testimonial',
				'frm_display',
				'mec_esb',
				'mec-events',

				'sfwd-assignment',
				'sfwd-essays',
				'sfwd-transactions',
				'sfwd-certificates',
				'e-landing-page',
				'zion_template',
				'pafe-fonts',
				'pgc_simply_gallery',
				'pdfviewer',
				'da_image',
            ]));

            $post_types = array_unique($potential_post_types);

            return $post_types;
        }

        public function woostify_builder_get_all_taxs_func(){
            
            $special_key = isset( $_POST['special_key'] )? sanitize_text_field( wp_unslash( $_POST['special_key'] ) ) : '';
            $search_query = isset( $_POST['search_query'] )? sanitize_text_field( wp_unslash( $_POST['search_query'] ) ) : '';

            if( empty($special_key) ){   
                wp_send_json_error();
            }
            
            $cpts[] = '';
            switch ($special_key) {
                case 'special-post_taxonomy_id':
                    $cpts[] = 'post';

                    break;

                case 'special-product_taxonomy_id':
                    $cpts[] = 'product';

                    break;
                
                default:
                    $cpts = $this->get_supported_post_types();

                    $cpts[] = 'page';

                    break;
            }

            $taxonomies = [];

            foreach ($cpts as $cpt) {
				$taxonomies = array_merge($taxonomies, array_values(array_diff(
					get_object_taxonomies($cpt),
					['post_format']
				)));
			}

            if( strpos($special_key, "post-tax") !== false ){
                $taxonomies = [];
                $taxonomies[] = str_replace("post-tax-", "", $special_key);
            }

            $terms = [];

            foreach ($taxonomies as $taxonomy) {
				$taxonomy_object = get_taxonomy($taxonomy);

				if (! $taxonomy_object->public) {
					continue;
				}

                $args = array(
                    'taxonomy' => $taxonomy,
                    'lang' => '',
                    'orderby' => 'id',
                    'order' => 'ASC',
                    'hide_empty' => true,
                    'fields' => 'all',
                );

                if( intval( $search_query ) ){
                    $args['include'] = intval( $search_query );
                }else{
                    $args['name__like'] = $search_query;
                }

				$local_terms = array_map(function ($tax) {
					return [
						'id' => $tax->term_id,
                        'taxonomy' => $tax->taxonomy,
						'name' => $tax->name,
						'group' => get_taxonomy($tax->taxonomy)->label
					];
				}, get_terms($args));

				if (empty($local_terms)) {
					continue;
				}

				$terms = array_merge($terms, $local_terms);
			}
            
            $result = array(
                'type' => 'taxonomy',
                'taxonomies' => $terms,
                'taxs' => $taxonomies,
            );

            wp_send_json_success( $result );

            wp_die();

        }

        public function woostify_builder_get_all_posts_func(){

            $special_key = isset( $_POST['special_key'] )? sanitize_text_field( wp_unslash( $_POST['special_key'] ) ) : '';
            $search_query = isset( $_POST['search_query'] )? sanitize_text_field( wp_unslash( $_POST['search_query'] ) ) : '';

            if( empty( $special_key ) ){   
                wp_send_json_error();
            }

            $post_types = 'post';
            $custom_post_types = $this->get_supported_post_types();

            switch ( $special_key ) {
                case 'special-page_id':
                    $post_types = 'page';
                    break;
                case 'special-product_id':
                    $post_types = 'product';
                    break;
                case 'special-custom_post_type_id':
                    $post_types = $custom_post_types;
                    break;
                
                default:
                    $post_types = 'post';
                    break;
            }

            $posts_result = '';

            $query_args = [
				'posts_per_page' => 10,
				'post_type' => $post_types,
                'post_status' => 'publish',
				'suppress_filters' => true,
				'lang' => '',
			];

            if( intval( $search_query ) ){
                $query_args['p'] = intval( $search_query );
            }else{
                $query_args['s'] = $search_query;
            }
  
			$query = new \WP_Query($query_args);

			$posts_result = $query->posts;

            $result = array(
                'type' => 'post',
                'posts' => $posts_result,
            ); 

            wp_send_json_success( $result );
            wp_die();
        }

        public function woostify_condition_enqueue_scripts(){

            $selection_options = $this->get_location_selections();
            $special_ids = $selection_options['special-ids']['value'];
            $special_id_keys = array();
            if($special_ids){
                foreach ($special_ids as $special_key => $value) {
                    $special_id_keys[] = $special_key;
                }
            }

            wp_localize_script( 'woostify-wp-builder-addon-editor', 'woostify_builder_rule_special_ids',
                array( 
                    'ajaxurl' => admin_url( 'admin-ajax.php' ),
                    'special_ids' => $special_id_keys,
                )
            );

        }

        public function save_wp_builder_addon_condition( $post_id, $post){

            $post_type = get_post_type( $post_id );
			if ( 'wp_builder_addon' !== $post_type ) {
				return;
			}
			
			$nonce_key = 'woostify_metabox_settings_wp_builder_addon';

			// verify nonce
			if ( !isset( $_POST[$nonce_key] ) && !wp_verify_nonce( sanitize_text_field($_POST[$nonce_key]), $nonce_key ) ) {
				return 'nonce not verified';
			}

			// check permissions
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return 'cannot edit post';
			}	

            if( isset( $_POST['woostify_builder_target_include_locations'] ) ){
				$woostify_builder_target_include_locations = $_POST['woostify_builder_target_include_locations'];
				if( $woostify_builder_target_include_locations ){
                    update_post_meta( $post_id ,'woostify_builder_target_include_locations', $woostify_builder_target_include_locations);
                }else{
                    delete_post_meta( $post_id, 'woostify_builder_target_include_locations' );
                }

                $woostify_builder_target_include_locations_special_ids = isset( $_POST['woostify_builder_target_include_locations_special_ids'] )? $_POST['woostify_builder_target_include_locations_special_ids'] : '';
                if( $woostify_builder_target_include_locations_special_ids ){
                    update_post_meta( $post_id ,'woostify_builder_target_include_locations_special_ids', $woostify_builder_target_include_locations_special_ids);
                }else{
                    delete_post_meta( $post_id, 'woostify_builder_target_include_locations_special_ids' );
                }
                
			}

			if( isset( $_POST['woostify_builder_target_exclude_locations'] ) ){
				$woostify_builder_target_exclude_locations = $_POST['woostify_builder_target_exclude_locations'];
                if( $woostify_builder_target_exclude_locations ){
                    update_post_meta( $post_id ,'woostify_builder_target_exclude_locations', $woostify_builder_target_exclude_locations);
                }else{
                    delete_post_meta( $post_id, 'woostify_builder_target_exclude_locations' );
                }

                $woostify_builder_target_exclude_locations_special_ids = isset( $_POST['woostify_builder_target_exclude_locations_special_ids'] )? $_POST['woostify_builder_target_exclude_locations_special_ids'] : '';
                if( $woostify_builder_target_exclude_locations_special_ids ){
                    update_post_meta( $post_id ,'woostify_builder_target_exclude_locations_special_ids', $woostify_builder_target_exclude_locations_special_ids);
                }else{
                    delete_post_meta( $post_id, 'woostify_builder_target_exclude_locations_special_ids' );
                }

			}

            if( isset( $_POST['woostify_builder_target_users_rule'] ) ){
				$woostify_builder_target_users_rule = $_POST['woostify_builder_target_users_rule'];
                $woostify_builder_target_users_rule = array_unique(array_filter($woostify_builder_target_users_rule));
                if( $woostify_builder_target_users_rule ){
                    update_post_meta( $post_id ,'woostify_builder_target_users_rule', $woostify_builder_target_users_rule);
                }else{
                    delete_post_meta( $post_id, 'woostify_builder_target_users_rule' );
                }
            }
        }



    }

    Woostify_Theme_Builder_Addons_Condition::instance();
}