<?php

// Helper class for Wing Popup
class WDPOP_Helper
{
    // Static variable
    private static $wdpops;
    private static $wdpop_settings;
    private static $mc_list;
    private static $mc_settings;
    private static $eLog = false;
    public static $mc_list_key = 'wdpops_mc_list';
    
    private $popup_key = 'wdpop_popup';
    private $mc_key = 'wdpop_mc';
    
    
    
    public function __construct() {
        self::$eLog = defined( 'WP_DEBUG' ) && WP_DEBUG;

        add_action( 'save_post_wdpop_template', [ __CLASS__, 'clear_template_css_cache' ], 10, 1 );
        add_action( 'trashed_post',             [ __CLASS__, 'clear_template_css_cache' ] );
        add_action( 'deleted_post',             [ __CLASS__, 'clear_template_css_cache' ] );
    }

    static function get_template_content( $id ) {
        $template_post = get_post( $id );
        if ( ! $template_post || $template_post->post_type !== 'wdpop_template' ) return '';

        // Elementor-built template
        if (
            class_exists( '\Elementor\Plugin' ) &&
            \Elementor\Plugin::$instance->documents->get( $id )->is_built_with_elementor()
        ) {
            \Elementor\Plugin::$instance->frontend->enqueue_styles();
            return \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $id );
        }

        $inline_css = self::get_critical_block_css( $template_post->post_content, $id );

        global $post;
        $original_post = $post;
        $post          = $template_post;
        setup_postdata( $post );

        $content = apply_filters( 'the_content', $post->post_content );

        $post = $original_post;
        wp_reset_postdata();

        return $inline_css . $content;
    }

    static function get_critical_block_css( $content, $template_id = 0 ) {
        self::$eLog && error_log( 'WDPOP get_critical_block_css called for template ID: ' . $template_id );

        // Return from cache if available
        if ( $template_id ) {
            $cached = get_transient( 'wdpop_critical_css_' . $template_id );
            if ( $cached !== false ) {
                self::$eLog && error_log( 'WDPOP: Returning cached CSS for template ID: ' . $template_id );
                return $cached;
            }
        }

        if ( ! function_exists( 'parse_blocks' ) ) {
            require_once ABSPATH . 'wp-includes/blocks.php';
        }

        if ( ! function_exists( 'parse_blocks' ) ) {
            self::$eLog && error_log( 'WDPOP: parse_blocks() unavailable, using full fallback.' );
            return self::get_fallback_css( $template_id );
        }

        $blocks      = parse_blocks( $content );
        $block_names = [];
        self::collect_block_names( $blocks, $block_names );
        $block_names = array_unique( $block_names );

        self::$eLog && error_log( 'WDPOP blocks found: ' . implode( ', ', $block_names ) );

        $css    = self::get_css_from_disk( $block_names );
        $output = $css
            ? '<style id="wdpop-critical-css-' . intval( $template_id ) . '">' . $css . '</style>'
            : '';

        self::$eLog && error_log( 'WDPOP total CSS output length: ' . strlen( $output ) );

        if ( $template_id ) {
            set_transient( 'wdpop_critical_css_' . $template_id, $output, DAY_IN_SECONDS );
        }

        return $output;
    }

    static function get_css_from_disk( $block_names ) {
        $css = '';

        foreach ( $block_names as $block_name ) {
            $slug = explode( '/', $block_name );
            $slug = end( $slug );

            $candidates = [
                ABSPATH . "wp-includes/blocks/{$slug}/style.min.css",
                ABSPATH . "wp-includes/blocks/{$slug}/style.css",
                ABSPATH . "wp-includes/css/dist/block-library/blocks/{$slug}/style.min.css",
            ];

            $found = false;
            foreach ( $candidates as $path ) {
                $file_css = self::safe_file_get_contents( $path );
                if ( $file_css !== '' ) {
                    $css .= $file_css;
                    self::$eLog && error_log( 'WDPOP loaded CSS for ' . $block_name . ' from: ' . $path );
                    $found = true;
                    break;
                }
            }

            if ( ! $found ) {
                self::$eLog && error_log( 'WDPOP no CSS file found for: ' . $block_name );
            }
        }

        // Full bundle fallback if nothing loaded
        if ( empty( trim( $css ) ) ) {
            self::$eLog && error_log( 'WDPOP: All per-block files empty, loading full bundle.' );
            $css = self::get_fallback_css_string();
        }

        return $css;
    }

    static function get_fallback_css( $template_id = 0 ) {
        $css = self::get_fallback_css_string();
        $output = $css
            ? '<style id="wdpop-critical-css-' . intval( $template_id ) . '">' . $css . '</style>'
            : '';

        if ( $template_id && $output ) {
            set_transient( 'wdpop_critical_css_' . $template_id, $output, DAY_IN_SECONDS );
        }

        return $output;
    }

    static function get_fallback_css_string() {
        $candidates = [
            ABSPATH . 'wp-includes/css/dist/block-library/style.min.css',
            ABSPATH . 'wp-includes/css/dist/block-library/style.css',
        ];

        foreach ( $candidates as $path ) {
            $css = self::safe_file_get_contents( $path );
            if ( $css !== '' ) {
                self::$eLog && error_log( 'WDPOP using fallback bundle: ' . $path );
                return $css;
            }
        }

        self::$eLog && error_log( 'WDPOP: No fallback CSS file found.' );
        return '';
    }

    static function safe_file_get_contents( $path ) {
        if ( ! file_exists( $path ) || ! is_readable( $path ) ) return '';
        $css = @file_get_contents( $path );
        return ( $css !== false ) ? $css : '';
    }

    static function collect_block_names( $blocks, &$names = [] ) {
        foreach ( $blocks as $block ) {
            if ( ! empty( $block['blockName'] ) ) {
                $names[] = $block['blockName'];
            }
            if ( ! empty( $block['innerBlocks'] ) ) {
                self::collect_block_names( $block['innerBlocks'], $names );
            }
        }
        return $names;
    }

    static function clear_template_css_cache( $post_id ) {
        delete_transient( 'wdpop_critical_css_' . $post_id );
        self::$eLog && error_log( 'WDPOP: Cleared CSS cache for post ID: ' . $post_id );
    }
    
    
    static function get_active_mc_form_ids() {
        $forms = self::get_mc_forms();
        $active_ids = [];

        foreach ($forms as $form) {
            $status = $form['mc_form_status'] ?? '';
            $id = $form['__group_id'] ?? '';

            if ($status == '1' && $id !== '') { // adjust 'active' if needed
                $active_ids[] = $id;
            }
        }

        return $active_ids;
    }

    
    // Here item format in $forms is like this: id => title(ID:id)
    static function get_active_mc_form_list(){
        $active_forms = self::get_active_mc_forms();
        $form_list = [];

        foreach ($active_forms as $form) {
            $form_list[$form['__group_id']] = $form['mc_form_name']. ' (ID: ' .$form['__group_id'].')';
        }

        return $form_list;
    }
    static function get_active_mc_forms(){
        $forms = self::get_mc_forms();
        $active_forms = [];

        foreach ($forms as $form) {
            $status = $form['mc_form_status'] ?? '';
            $id = $form['__group_id'] ?? '';

            if ($status == '1' && $id !== '') {
                $active_forms[$id] = $form;
            }
        }

        return $active_forms;
    }
    static function get_mc_forms(){
        $settings = self::get_mc_settings();
        if(empty($settings)) return [];
        
        $forms = $settings['mc_form_item'] ?? [];
        return $forms;
    }
    static function get_mc_form_by_id($id){
        $forms = self::get_mc_forms();
        if(empty($forms)) return [];
        
        foreach ($forms as $form) {
            if (isset($form['__group_id']) && $form['__group_id'] == $id) {
                return $form;
            }
        }
        return [];
    }    
    static function get_mc_settings_here(){
        if (self::$mc_settings === null) {
            self::$mc_settings = get_option( 'wdpop_mc' );
        }
    }
    static function get_settings_here(){
        if (self::$wdpop_settings === null) {
            self::$wdpop_settings = get_option( 'wdpop_settings' );
        }
    }
    public static function get_settings(){
        self::get_settings_here();
        return self::$wdpop_settings;
    }
    public static function get_mc_settings(){
        self::get_mc_settings_here();
        return self::$mc_settings;
    }
    
    static function get_mc_api_key(){

        $settings = self::get_mc_settings();
        
        if(empty($settings)) return '';
        $key = $settings['mailchimp_api_key'] ?? '';
        return $key;
    }
    static function mc_get_lists() {
        self::init_mc_lists();
        return self::$mc_list;
    }
    
    static function init_mc_lists(){
        if (self::$mc_list === null) {
            self::$mc_list = self::mc_get_lists_here();
        }
    }
    static function get_mc_list(){
        return get_option( self::$mc_list_key );
    }
    static function sync_mc_list(){
        $mc_list = self::mc_get_lists_here();
        
        $updated = update_option( self::$mc_list_key, $mc_list );
        return $mc_list;
    }
    
    static function mc_get_lists_here() {
        
        $api_key = self::get_mc_api_key();
        if(empty($api_key)) return [];
        
        // Extract datacenter
        if ( ! strpos( $api_key, '-' ) ) {
            return new WP_Error( 'invalid_key', 'Invalid API key format.' );
        }
        list( , $dc ) = explode( '-', $api_key );

        $url = "https://{$dc}.api.mailchimp.com/3.0/lists";

        $response = wp_remote_get( $url, array(
            'headers' => array(
                'Authorization' => 'apikey ' . $api_key,
            ),
        ));

        if ( is_wp_error( $response ) ) {
            return $response;
        }

        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( empty( $body['lists'] ) ) {
            return array();
        }

        // Return ID + name
        $lists = array();
        foreach ( $body['lists'] as $list ) {
            $lists[ $list['id'] ] = $list['name'];
        }

        return $lists;
    }
    static function mc_get_first_list() {
        $mc_list = self::mc_get_lists();
        if(empty($mc_list) || !is_array($mc_list) ){
            return '';
        }
        $first_key = array_key_first($mc_list);
        // $first_value = $mc_list[$first_key];
        return $first_key;
    }
    static function get_mc_data() {
        $mc_list = self::get_mc_list();
        if(empty($mc_list) || !is_array($mc_list) ){
            return [
                'lists' => [],
                'first_list' => '',
            ];
        }
        $first_key = array_key_first($mc_list);
        
        return [
            'lists' => $mc_list,
            'first_list' => $first_key,
        ];

    }
    
    // Static initialization method
    private static function get_popups() {
        if (self::$wdpops === null) {
            self::$wdpops = self::get_all_active_popups_privately();
        }
    }
    // Function to simulate fetching a value
    private static function get_all_active_popups_privately() {
        $popups = [];
        $wdpops = get_option( 'wdpop_popup' );
        
        if(empty($wdpops) || empty($wdpops['wdpop_item'])) return $popups;
        
        foreach ($wdpops['wdpop_item'] as $key => $this_popup) {
            if($this_popup['popup_status'] == "0") continue;
            $popups[$key+1] = $this_popup; // Increase the index by 1 to match with the UI ID
        }
        return $popups;
    }
    public static function get_custom_post_types () {
        return  get_post_types(
			[
				'public'   => true,
				'_builtin' => false,
			],
			'objects'
		);
    }
    public static function get_custom_taxonomies () {
        return get_taxonomies(
			[
				'public'   => true,
				'_builtin' => false,
			],
			'objects'
		);
    }
    public static function get_display_options() {
	
		$top_level_items = [];
		$general = array(
			'home_page' => 'Home Page',
			'search_result_page' => 'Search Result Page',
			'404_error_page' => '404 Error Page',
            'archive_page' => 'Archive Page',
            'posts_page' => 'Posts Page',
            'single_page' => 'Single Page(All Post Types)',
		);
		$pages = array(
            'all_pages' => 'All Pages',
            'pages_selected' => 'Pages: Selected',
            'pages_id' => 'Pages: ID',
        );
		$posts = array(
            'all_posts' => 'All Posts',
            'posts_selected' => 'Posts: Selected',
            'posts_id' => 'Posts: ID',
            'posts_with_category' => 'Posts: With Category',
            'posts_with_tag' => 'Posts: With Tag',
            'posts_with_format' => 'Posts: With Format',
        );
		
        $categories = array(
            'all_categories' => 'All Categories',
            'categories_selected' => 'Categories: Selected',
            'categories_id' => 'Categories: ID',
        );
        $tags = array(
            'all_tags' => 'All Tags',
            'tags_selected' => 'Tags: Selected',
            'tags_id' => 'Tags: ID',
        );
        
		$default_items = [
			'General' => $general,
			'Pages' => $pages,
			'Posts' => $posts,
		];
		
		$top_level_items = $default_items;
		
		$post_types = self::get_custom_post_types();
		foreach ($post_types as $name => $post_type ) {
			$post_type_items = [
				'all_' . $post_type->name => 'All ' . $post_type->label,
				$post_type->name . '_selected' => $post_type->label . ': Selected',
				$post_type->name . '_id' => $post_type->label . ': With ID',
			];
			if($post_type->has_archive) {
				$post_type_items[$post_type->name . '_archive'] = $post_type->label . ' Archive';
			}
            
            $cpt_taxonomies = get_object_taxonomies($post_type->name, 'objects');
            foreach ( $cpt_taxonomies as $tax_name => $taxonomy ) {
                $post_type_items[$post_type->name . '_with_'. $taxonomy->name] = $post_type->label . ': With ' . $taxonomy->label;
            }
            
            $top_level_items[$post_type->label] = $post_type_items;
		}
        $top_level_items['Categories'] = $categories;
        $top_level_items['Tags'] = $tags;
        
        
        $taxonomies = self::get_custom_taxonomies();
		foreach ( $taxonomies as $tax_name => $taxonomy ) {
			$tax_items = [
				'all_' . $taxonomy->name => 'All ' . $taxonomy->label,
				$taxonomy->name . '_selected' => $taxonomy->label . ' Selected',
				$taxonomy->name . '_id' => $taxonomy->label . ' With ID',
			];
			$top_level_items[$taxonomy->labels->name] = $tax_items;
		}

        return $top_level_items;
    }
    public static function get_display_options_fields(){
        $display_options = self::get_display_options();
        
        $ajax_select = true;
        
        $fileds = array(
            array(
                'id'          => 'popup_display_options',
                'type'        => 'select',
                'placeholder' => 'Select an Option',
                'chosen'      => true,
                'options'     => $display_options,
                'class'     => 'popup_display_options_root',
            ),
            array(
                'id'          => 'pages_selected',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'options'     => 'pages',
                'placeholder' => 'Select pages',
                'dependency' => array( 'popup_display_options', '==', 'pages_selected' ),
            ),
            array(
                'id'    => 'pages_id',
                'type'  => 'text',
                'placeholder' => 'Page IDs. Ex: 15, 26, 33',
                'dependency' => array( 'popup_display_options', '==', 'pages_id' ),
            ),
            array(
                'id'          => 'posts_selected',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'options'     => 'posts',
                'placeholder' => 'Select Posts',
                'dependency' => array( 'popup_display_options', '==', 'posts_selected' ),
            ),
            array(
                'id'    => 'posts_id',
                'type'  => 'text',
                'placeholder' => 'Post IDs. Ex: 15, 26, 33',
                'dependency' => array( 'popup_display_options', '==', 'posts_id' ),
            ),
            array(
                'id'          => 'posts_with_category',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'options'     => 'categories',
                'placeholder' => 'Select Categories',
                'dependency' => array( 'popup_display_options', '==', 'posts_with_category' ),
            ),
            array(
                'id'          => 'posts_with_tag',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'options'     => 'tags',
                'placeholder' => 'Select Tags',
                'dependency' => array( 'popup_display_options', '==', 'posts_with_tag' ),
            ),
            array(
                'id'          => 'posts_with_format',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'options'     => 'categories',
                'query_args'  => array(
                    'taxonomy'  => 'post_format',
                ),
                'placeholder' => 'Select Formats',
                'dependency' => array( 'popup_display_options', '==', 'posts_with_format' ),
            ),
        );
        
        $post_types = self::get_custom_post_types();
		foreach ($post_types as $name => $post_type ) {
            
            $this_selected = array(
                'id'          => $post_type->name . '_selected',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'options'     => 'pages',
                'placeholder' => 'Select '.$post_type->label,
                'options'     => 'posts',
                'query_args'  => array(
                    'post_type' => $post_type->name,
                ),
                'dependency' => array( 'popup_display_options', '==', $post_type->name . '_selected' ),
            );
            $this_ids = array(
                'id'    => $post_type->name . '_id',
                'type'  => 'text',
                'placeholder' => $post_type->label.' IDs. Ex: 15, 26, 33',
                'dependency' => array( 'popup_display_options', '==', $post_type->name . '_id' ),
            );
            
            $cpt_taxonomies = get_object_taxonomies($post_type->name, 'objects');
            foreach ( $cpt_taxonomies as $tax_name => $taxonomy ) {
                $this_ctx_selected = array(
                    'id'          => $post_type->name . '_with_'. $taxonomy->name,
                    'type'        => 'select',
                    'chosen'      => true,
                    'multiple'    => true,
                    'sortable'    => true,
                    'ajax'        => $ajax_select,
                    'placeholder' => 'Select '.$taxonomy->label,
                    'options'     => 'categories',
                    'query_args'  => array(
                        'taxonomy'  => $taxonomy->name,
                    ),
                    'dependency' => array( 'popup_display_options', '==', $post_type->name . '_with_'. $taxonomy->name ),
                );
                $fileds[] = $this_ctx_selected;
            }

            
            
            
            $fileds[] = $this_selected;
            $fileds[] = $this_ids;
            
		}
        
        $categories_selected = array(
            'id'          => 'categories_selected',
            'type'        => 'select',
            'chosen'      => true,
            'multiple'    => true,
            'sortable'    => true,
            'ajax'        => $ajax_select,
            'options'     => 'categories',
            'placeholder' => 'Select Categories',
            'dependency' => array( 'popup_display_options', '==', 'categories_selected' ),
        );
        $categories_id = array(
            'id'    => 'categories_id',
            'type'  => 'text',
            'placeholder' => 'Category IDs. Ex: 15, 26, 33',
            'dependency' => array( 'popup_display_options', '==', 'categories_id' ),
        );

        $tags_selected = array(
            'id'          => 'tags_selected',
            'type'        => 'select',
            'chosen'      => true,
            'multiple'    => true,
            'sortable'    => true,
            'ajax'        => $ajax_select,
            'options'     => 'tags',
            'placeholder' => 'Select Tags',
            'dependency' => array( 'popup_display_options', '==', 'tags_selected' ),
        );
        $tags_id = array(
            'id'    => 'tags_id',
            'type'  => 'text',
            'placeholder' => 'Tag IDs. Ex: 15, 26, 33',
            'dependency' => array( 'popup_display_options', '==', 'tags_id' ),
        );
        
        $fileds[] = $categories_selected;
        $fileds[] = $categories_id;
        $fileds[] = $tags_selected;
        $fileds[] = $tags_id;

        $taxonomies = self::get_custom_taxonomies();
		foreach ( $taxonomies as $tax_name => $taxonomy ) {
            
            $this_selected = array(
                'id'          => $taxonomy->name . '_selected',
                'type'        => 'select',
                'chosen'      => true,
                'multiple'    => true,
                'sortable'    => true,
                'ajax'        => $ajax_select,
                'placeholder' => 'Select '.$taxonomy->label,
                'options'     => 'categories',
                'query_args'  => array(
                    'taxonomy'  => $taxonomy->name,
                ),
                'dependency' => array( 'popup_display_options', '==', $taxonomy->name . '_selected' ),
            );
            $this_ids = array(
                'id'    => $taxonomy->name . '_id',
                'type'  => 'text',
                'placeholder' => $taxonomy->label.' IDs. Ex: 15, 26, 33',
                'dependency' => array( 'popup_display_options', '==', $taxonomy->name . '_id' ),
            );
            
            $fileds[] = $this_selected;
            $fileds[] = $this_ids;
            
		}
        
        return $fileds;
        
    }
    public static function get_all_active_popups(){
        self::get_popups();
        return self::$wdpops;
    }
    public static function hide_by_excludes($excludes) {
        if(empty($excludes) || !is_array($excludes)) return false;
    
        foreach ($excludes as $exclude) {
            $key = $exclude["popup_display_options"];
            if(self::check_page_conditions($key, $exclude)) return true;            
            if(self::check_post_conditions($key, $exclude)) return true;
            if(self::check_custom_post_types($key, $exclude)) return true;
            if(self::check_category_and_tag_conditions($key, $exclude)) return true;
            if(self::check_custom_taxonomies($key, $exclude)) return true;
        }
    
        return false;
    }
    public static function hide_by_includes($includes) {
        if(empty($includes) || !is_array($includes)) return false;
        foreach ($includes as $include) {
            $key = $include["popup_display_options"];
            if(self::check_page_conditions($key, $include)) return false;
            if(self::check_post_conditions($key, $include)) return false;
            if(self::check_custom_post_types($key, $include)) return false;
            if(self::check_category_and_tag_conditions($key, $include)) return false;
            if(self::check_custom_taxonomies($key, $include)) return false;
        }
        return true;
    }
    public static function should_show_popup($popup) {
        if($popup['wdpop_item_tab']['popup_display_type'] == "everywhere") return true;
        
        $includes = $popup['wdpop_item_tab']['popup_display_accordions']['popup_display_includes'] ?? null;
        $excludes = $popup['wdpop_item_tab']['popup_display_accordions']['popup_display_excludes'] ?? null;
        if(empty($includes) && empty($excludes)) return true;
        
        if(self::hide_by_excludes($excludes)) return false;
        
        if(self::hide_by_includes($includes)) return false;
        
        return true;
    }
    private static function check_page_conditions($key, $item) {
        $con = [
            "home_page" => is_front_page(),
            "posts_page" => is_home(),
            "search_result_page" => is_search(),
            "404_error_page" => is_404(),
            "archive_page" => is_archive(),
            "single_page" => is_singular(),
            "all_pages" => is_page(),
            "pages_selected" => isset($item["pages_selected"]) && is_page($item["pages_selected"]),
            "pages_id" => is_page(explode(",", $item["pages_id"])),
        ];
        return isset($con[$key]) && $con[$key];
    }
    private static function check_post_conditions($key, $item) {
        $con = [
            "all_posts" => is_single(),
            "posts_selected" => isset($item["posts_selected"]) && is_single($item["posts_selected"]),
            "posts_id" => is_single(explode(",", $item["posts_id"])),
            "posts_with_category" => isset($item["posts_with_category"]) && is_single(self::get_posts_by_categories($item["posts_with_category"])),
            "posts_with_tag" => isset($item["posts_with_tag"]) && is_single(self::get_posts_by_tags($item["posts_with_tag"])),
            "posts_with_format" => isset($item["posts_with_format"]) && is_single(self::get_posts_by_terms('post', 'post_format', $item["posts_with_format"])),
        ];
        return isset($con[$key]) && $con[$key];
    }
    private static function check_category_and_tag_conditions($key, $item) {
        $con = [
            "all_categories" => is_category(),
            "categories_selected" => isset($item["categories_selected"]) && is_category($item["categories_selected"]),
            "categories_id" => is_category(explode(",", $item["categories_id"])),
            "all_tags" => is_tag(),
            "tags_selected" => isset($item["tags_selected"]) && is_tag($item["tags_selected"]),
            "tags_id" => is_tag(explode(",", $item["tags_id"]))
        ];
        return isset($con[$key]) && $con[$key];
    }
    private static function check_custom_taxonomies($key, $item) {
        $taxonomies = self::get_custom_taxonomies();
    
        foreach ($taxonomies as $tax_name => $taxonomy) {
            if(self::check_single_tax($key, $taxonomy->name, $item)) return true;
        }
    
        return false;
    }
    private static function check_single_tax($key, $name, $item) {
        $con = [
            "all_" . $name => is_tax($name),
            $name . '_selected' => isset($item[$name . '_selected']) && is_tax($name, $item[$name . '_selected']),
            $name . '_id' => is_tax($name, explode(",", $item[$name . '_id'])),
        ];
        return isset($con[$key]) && $con[$key];
    }
    private static function check_custom_post_types($key, $item) {
        $post_types = self::get_custom_post_types();
    
        foreach ($post_types as $name => $post_type) {
            if(self::check_single_cpt($key, $post_type->name, $item)) return true;
        }
    
        return false;
    }
    private static function check_single_cpt($key, $name, $item) {
        $con = [
            "all_" . $name => is_singular($name),
            $name . '_selected' => is_singular($name) && in_array(get_the_ID(), $item[$name . '_selected']),
            $name . '_id' => is_singular($name) && in_array(get_the_ID(), explode(",", $item[$name . '_id'])),
            $name . '_archive' => is_post_type_archive($name),
        ];
        
        if(isset($con[$key]) && $con[$key]) return true;
        
        $cpt_taxonomies = get_object_taxonomies($name, 'objects');
        foreach ($cpt_taxonomies as $tax_name => $taxonomy) {
            if ($key == $name . '_with_' . $taxonomy->name) {
                $cpt_term_ids = $item[$name . '_with_' . $taxonomy->name];
                $cpt_post_ids = self::get_posts_by_terms($name, $taxonomy->name, $cpt_term_ids);
                if (is_singular($name) && in_array(get_the_ID(), $cpt_post_ids)) {
                    return true;
                }
            }
        }
    
        return false;
    }
    private static function get_posts_by_terms($post_type, $taxonomy, $terms) {
        $args = array(
            'posts_per_page' => 100,
            'fields' => 'ids',
            'post_type' => $post_type,
        );
    
        $tax_q_name = 'tax_query';
        $tax_q_val = array(
            'taxonomy' => $taxonomy,
            'field' => 'term_id',
            'terms' => $terms,
            'operator' => 'IN'
        );
        $args[$tax_q_name] = $tax_q_val;
        
        $query = new WP_Query($args);
    
        return $query->posts;
    }
    public static function get_posts_by_tags($tags) {
        $args = array(
            'tag__in' => $tags, // Tags to include
            'posts_per_page' => -1, // Retrieve all posts
            'fields' => 'ids' // Only get post IDs
        );
    
        $query = new WP_Query($args);
    
        return $query->posts;
    }
    public static function get_posts_by_categories($categories) {
        $args = array(
            'category__in' => $categories,
            'posts_per_page' => -1,
            'fields' => 'ids'
        );
    
        $query = new WP_Query($args);
    
        return $query->posts;
    }
    public static function get_all_popups() {
        $popups = [];
        $wdpops = get_option( 'wdpop_popup' );
        foreach ($wdpops['wdpop_item'] as $key => $this_popup) {
            $popups[$key+1] = $this_popup;
        }
        return $popups;
    }
    public static function if_popups_active() {
        $wdpops = WDPOP_Helper::get_all_active_popups();
        
        foreach ($wdpops as $key => $this_popup) {
            if(WDPOP_Helper::should_show_popup($this_popup)) return true;
        }
        return false;
    }
	/**
	 * Returns a file's last modification time formatted with a version prefix.
	 * The version is included as a prefix in the format: "version.ymdGis".
	 *
	 * @param string $dir The directory path of the file.
	 * @return string A string representing the last modification time of the file
	 *                formatted according to the version and date format "ymdGis".
	 * @since 1.0.0
	 */
	public static function wing_filemtime( $dir ){
		return gmdate(WDPOP_VER .".ymdGis", filemtime( $dir ));
	}
	
	/**
	 * Enqueues a stylesheet with a versioned URL to avoid caching problems.
	 * The version is dynamically generated based on the file's last modification time.
	 *
	 * @param string $handle The handle name for the stylesheet.
	 * @param string $src    The source URL of the stylesheet relative to WDPOP_URL.
	 * @since 1.0.0
	 */
	public static function wing_add_dynamic_style( $handle = '', $src ='' ){
		wp_enqueue_style( $handle, WDPOP_URL.$src, array(), self::wing_filemtime(WDPOP_DIR.$src), 'all' );
	}
	/**
	 * Enqueues a script with a versioned URL to avoid caching problems.
	 * The version is dynamically generated based on the file's last modification time.
	 *
	 * @param string $handle  The handle name for the script.
	 * @param string $src     The source URL of the script relative to WDPOP_URL.
	 * @param array  $dep     (Optional) An array of registered script handles this script depends on. Default is array('jquery').
	 * @param bool   $footer  (Optional) Whether to enqueue the script before </body> instead of in the <head>. Default is true.
	 * @since 1.0.0
	 */
	public static function wing_add_dynamic_script( $handle = '', $src ='', $dep = array('jquery'), $footer = true ){
        $args = array( 
            'in_footer' => $footer,
            'strategy'  => 'defer',
        );
		wp_enqueue_script( $handle, WDPOP_URL.$src, $dep, self::wing_filemtime(WDPOP_DIR.$src), $args );	
	}


}


