<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.NamingConventions.PrefixAllGlobals -- Frontend rendering uses plugin-owned tables and established public hooks.

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * The public-facing functionality of the plugin.
 *
 * @link       https://example.com
 * @since      1.0.0
 *
 * @package    Instant_Popup_Builder
 * @subpackage Instant_Popup_Builder/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @package    Instant_Popup_Builder
 * @subpackage Instant_Popup_Builder/public
 * @author     7th Sky Software's <example@gmail.com>
 */
class Instant_Popup_Builder_Public
{

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	static $ipb_popups = array();

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $fontawesom = 'fontawesome';

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of the plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct($plugin_name, $version)
	{

		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Instant_Popup_Builder_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Instant_Popup_Builder_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_register_style($this->fontawesom, plugin_dir_url(dirname(__FILE__)) . 'admin/css/fontawesome.css', array(), $this->version, 'all');
		wp_register_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/instant-popup-builder-public.css', array(), $this->version, 'all');

		wp_enqueue_style($this->fontawesom);
		wp_enqueue_style($this->plugin_name);
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 * @return   void
	 */
	public function enqueue_scripts()
	{

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Instant_Popup_Builder_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Instant_Popup_Builder_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/instant-popup-builder-public.js', array('jquery'), $this->version, true);
		wp_script_add_data($this->plugin_name, 'strategy', 'defer');
		wp_localize_script($this->plugin_name, 'instant_ajax_handler', [
			'ajax_url' => admin_url('admin-ajax.php'),
			'view_count' => wp_create_nonce('view_count_action'),
			'redirect_message' => esc_html__('You will be redirected to the link below.', 'instant-popup-builder'),
		]);
		$active_license = get_option('subscription_license_active');
		$ipd_active_plugin = get_option('instant_popup_subscription_activated');
        if($active_license != 'yes' || $ipd_active_plugin == 'no'){
		wp_localize_script($this->plugin_name, 'instnat_ajax_subscriber', [
				'ajaxurl' => admin_url('admin-ajax.php'),
				'ajax_url' => admin_url('admin-ajax.php'), // Alternative naming for compatibility
				'nonce' => wp_create_nonce('instant_popup_subscriber_ajax_action'),
				'subscription_check_nonce' => wp_create_nonce('instant_popup_subscription_check'),
				'verification_nonce' => wp_create_nonce('instant_popup_verification_action'),
			]);
        }

	}

	/**
	 * Add popups for frontend
	 * @param mixed $popup
	 * @return void
	 */
	public static function add_ipb_popup($popup)
    {
        self::$ipb_popups[] = $popup;
    }

	/**
	 * Get popups
	 */
    public static function get_ipb_popups()
    {
        return self::$ipb_popups;
    }

	/**
	 * Render frontend popups
	 * @return string
	 *
	 */
	public function ipb_create_popups(string $type){

		 $method = 'ipb_create_popup_' . $type;
        foreach (self::get_ipb_popups() as $popup) {
            if (method_exists($popup, $method)) {
                return $popup->$method(); // call dynamically
            }
        }
        return false;
	}

	/**
	 * Announcement bars queued for wp_body_open (top) / wp_footer (bottom) instead of wp_head.
	 *
	 * @var array<int, array{row: object, position: string}>
	 */
	private static $ipb_ann_bar_deferred_queue = array();

	/** @var bool */
	private static $ipb_ann_bar_hooks_registered = false;

	/** @var self|null */
	private static $ipb_ann_bar_renderer = null;

	private function ipb_safe_json_decode_row( $json_string, $default = null ) {
		if ( empty( $json_string ) ) {
			return $default;
		}
		$decoded = json_decode( $json_string );
		if ( json_last_error() !== JSON_ERROR_NONE ) {
			return $default;
		}
		return $decoded;
	}

	/**
	 * Populate frontend transients for one popup row (used by main display pass and deferred announcement bars).
	 *
	 * @param object $r Database row.
	 */
	public function ipb_hydrate_popup_transients_from_row( $r ) {
		$id = $r->id;
		$views = $r->views;
		$class = $r->class;
		$key_clas = 'instant_popup_builder_popup_class' . $id;
		set_transient( 'instant_popup_builder_popup_id', $id, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_popup_views', $views, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( $key_clas, $class, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );

		$triggerJson = '';
		if ( isset( $r->ipb_trigger ) && $r->ipb_trigger !== '' ) {
			$triggerJson = $r->ipb_trigger;
		} elseif ( isset( $r->triger ) && $r->triger !== '' ) {
			$triggerJson = $r->triger;
		}
		if ( $triggerJson !== '' ) {

			$triger = json_decode( $triggerJson );
			if ( json_last_error() !== JSON_ERROR_NONE || ! is_object( $triger ) && ! is_array( $triger ) ) {
				$triger = (object) array();
			}
			if ( ! is_array( $triger ) && ! is_object( $triger ) ) {
				$triger = (object) array();
			}
			foreach ( $triger as $key => $value ) {

				if ( $key == 'trigger_option' ) {

					$key_name = 'instant_popup_builder_trigger' . $id;

					set_transient( $key_name, $value, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );

					if ( is_array( $value ) && isset( $value[0] ) ) {
						do_action( 'ipb_trigger_activated', $value[0], $id );

						if ( $value[0] == 'onload' ) {

							$key1 = 'instant_popup_builder_class_hover' . $id;
							$key2 = 'instant_popup_builder_class_click' . $id;
							set_transient( $key1, '', INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
							set_transient( $key2, '', INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
						}
					}
				}
				if ( preg_match( '/_trigger_settings$|_settings$/', $key ) && is_object( $value ) ) {
					$safe_key = is_string( $key ) ? $key : '';
					$trigger_id = str_replace( array( '_trigger_settings', '_settings' ), '', $safe_key );
					$trigger_id = is_string( $trigger_id ) ? str_replace( '_', '-', $trigger_id ) : '';

					do_action( 'ipb_process_trigger_frontend_settings', $id, $value, $trigger_id );
					do_action( "ipb_process_trigger_frontend_settings_{$trigger_id}", $id, $value );
				}
				if ( $key == 'trigger_delay' ) {

					set_transient( 'instant_popup_builder_delay', is_array( $value ) && isset( $value[0] ) ? $value[0] : 0, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}

				if ( $key == 'target_device' ) {

					$key_name = 'instant_popup_builder_target_device' . $id;
					set_transient( $key_name, json_encode( $value ), INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}
				if ( $key == 'exit_sensivity' ) {
					$key_name = 'exit_sensivity' . $id;
					set_transient( $key_name, json_encode( $value ), INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}
				if ( $key == 'exit_intent_options' ) {
					$key_name = 'exit_intent_options' . $id;
					set_transient( $key_name, json_encode( $value ), INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}

				$key_name = 'instant_popup_builder_class_hover' . $id;
				$key_name2 = 'instant_popup_builder_class_click' . $id;

				if ( $key == 'trigger_class_click' && is_array( $value ) && isset( $value[0] ) ) {

					set_transient( $key_name2, $value[0], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
					set_transient( $key_name, '', INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}

				if ( $key == 'trigger_class_hover' && is_array( $value ) && isset( $value[0] ) ) {

					set_transient( $key_name, $value[0], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
					set_transient( $key_name2, '', INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}
			}
		} else {

			set_transient( 'instant_popup_builder_delay', 0, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		}

		$closing_raw = isset( $r->closing ) ? (string) $r->closing : '';
		$ipb_closing_parsed = function_exists( 'ipb_parse_closing_settings_from_json' )
			? ipb_parse_closing_settings_from_json( $closing_raw )
			: array(
				'position' => 'top-right',
				'escape'   => 'no',
				'outside'  => 'no',
				'hide'     => 'no',
			);
		set_transient( 'instant_popup_builder_close_position_' . $id, $ipb_closing_parsed['position'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_close_escape_' . $id, $ipb_closing_parsed['escape'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_box_outside_' . $id, $ipb_closing_parsed['outside'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_hide_close_' . $id, $ipb_closing_parsed['hide'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		// Extension shortcodes (PDF, video, subscription, …) still read unprefixed transients populated on prepare.
		set_transient( 'instant_popup_builder_close_position', $ipb_closing_parsed['position'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_close_escape', $ipb_closing_parsed['escape'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_box_outside', $ipb_closing_parsed['outside'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		set_transient( 'instant_popup_builder_hide_close', $ipb_closing_parsed['hide'], INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );

		$position = isset( $r->position ) ? $this->ipb_safe_json_decode_row( $r->position, '' ) : '';
		$design = isset( $r->design ) ? $this->ipb_safe_json_decode_row( $r->design, '' ) : '';
		$advance = isset( $r->advance ) ? $this->ipb_safe_json_decode_row( $r->advance, '' ) : '';

		if ( $position ) {

			set_transient( 'instant_popup_builder_limit_count', $position->limit_count, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
			set_transient( 'instant_popup_builder_limit_expiry', $position->limit_expiry, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
			set_transient( 'instant_popup_builder_popup_position', $position->popup_position, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
		}

		if ( isset( $design ) && ( is_array( $design ) || is_object( $design ) ) ) {

			foreach ( $design as $key => $des ) {

				if ( $key == 'design_percentage' || $key == 'design_percentage_toggle' ||
					$key == 'design_width' || $key == 'design_height' ) {
					$keyname = $key . $id;
					set_transient( $keyname, $des, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				} else {

					set_transient( $key, $des, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
				}
			}
		}
		if ( isset( $advance ) && ( is_array( $advance ) || is_object( $advance ) ) ) {

			foreach ( $advance as $key => $adv ) {

				set_transient( $key, $adv, INSTANT_POPUP_BUILDER_TRANSIENT_EXPIRATION );
			}
		}
	}

	/**
	 * @return void
	 */
	public static function ipb_output_deferred_ann_bars_top() {
		self::ipb_output_deferred_ann_bars_for_position( 'top' );
	}

	/**
	 * @return void
	 */
	public static function ipb_output_deferred_ann_bars_bottom() {
		self::ipb_output_deferred_ann_bars_for_position( 'bottom' );
	}

	/**
	 * @param string $position top|bottom.
	 * @return void
	 */
	private static function ipb_output_deferred_ann_bars_for_position( $position ) {
		$renderer = self::$ipb_ann_bar_renderer;
		if ( ! $renderer instanceof Instant_Popup_Builder_Public ) {
			return;
		}
		foreach ( self::$ipb_ann_bar_deferred_queue as $item ) {
			if ( ! isset( $item['row'], $item['position'] ) || $item['position'] !== $position ) {
				continue;
			}
			$renderer->ipb_hydrate_popup_transients_from_row( $item['row'] );
			$renderer->ipb_create_popups( 'announcement_bar' );
		}
	}

	/**
	 * @return void
	 */
	private static function ipb_register_ann_bar_deferred_hooks() {
		if ( self::$ipb_ann_bar_hooks_registered ) {
			return;
		}
		self::$ipb_ann_bar_hooks_registered = true;
		add_action( 'wp_body_open', array( __CLASS__, 'ipb_output_deferred_ann_bars_top' ), 1 );
		add_action( 'wp_footer', array( __CLASS__, 'ipb_output_deferred_ann_bars_bottom' ), 999 );
	}

	/**
	 * Return Content for All Popups menu
	 *
	 * @since    1.0.0
	 * @return string
	 */

	public function instant_popup_builder_html()
	{
		self::$ipb_ann_bar_renderer = $this;

		global $wp_query;
		global $wpdb;
		$table_name = $wpdb->prefix . 'instant_popup_builder';
		$row = $wpdb->get_results($wpdb->prepare("SELECT * FROM  {$wpdb->prefix}instant_popup_builder where status=%s", 'publish'));

		/**
		 * Allow extensions (e.g., Smart Popup) to filter which popups are processed/displayed.
		 * Expected to return an array of popup objects.
		 */
		$row = apply_filters('ipb_filter_popups_before_display', $row);

		foreach ($row as $r) {

			// Safety: do not render popups whose required extension is deactivated or missing.
			$popup_type = isset( $r->type ) ? $r->type : '';
			if ( $popup_type !== '' && class_exists( 'Instant_Popup_Builder_Extension_Dependency', false ) ) {
				$popup_advance = isset( $r->advance ) ? $r->advance : '';
				if ( Instant_Popup_Builder_Extension_Dependency::is_extension_required_for_type( $popup_type, $popup_advance )
					&& ! Instant_Popup_Builder_Extension_Dependency::is_extension_active_for_type( $popup_type, $popup_advance ) ) {
					// Edge case: extension was removed without deactivation; set popup inactive in DB.
					if ( ! empty( $r->class ) && isset( $r->id ) ) {
						// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
						$wpdb->update(
							$wpdb->prefix . 'instant_popup_builder',
							array( 'class' => '' ),
							array( 'id' => (int) $r->id ),
							array( '%s' ),
							array( '%d' )
						);
						delete_transient( 'instant_popup_builder_popup_class' . $r->id );
					}
					continue;
				}
			}

			$id = isset( $r->id ) ? (int) $r->id : 0;
			$this->ipb_hydrate_popup_transients_from_row( $r );

			$type = $r->type;
			// Safe JSON decode with error handling
			$display_json = isset($r->display) ? $r->display : '';
			$display = json_decode($display_json);
			if (json_last_error() !== JSON_ERROR_NONE || !is_object($display)) {
				$display = (object)[];
			}
			$selected = isset($display->selected) ? $display->selected : [];
			$is_display = isset($display->is_display) ? $display->is_display : false;
			$place = isset($display->place) ? $display->place : '';

			// Convert $selected to array if it's an object (json_decode can return objects)
			if (is_object($selected)) {
				$selected = json_decode(json_encode($selected), true);
			}
			if (!is_array($selected)) {
				$selected = [];
			}

			// Convert $is_display to array if it's an object
			if (is_object($is_display)) {
				$is_display = json_decode(json_encode($is_display), true);
			}
			if (!is_array($is_display)) {
				$is_display = [];
			}

			// Convert $place to array if it's an object (json_decode can return objects)
			if (is_object($place)) {
				$place = json_decode(json_encode($place), true);
			}
			// Ensure $place is an array
			if (!is_array($place)) {
				$place = [];
			}

			// Strip stale "everywhere" entries when specific rules also exist (legacy data defense).
			if (count($selected) > 1) {
				$f_sel = [];
				$f_dis = [];
				$f_plc = [];
				foreach ($selected as $idx => $opt) {
					if ($opt === 'everywhere') {
						continue;
					}
					$f_sel[] = $opt;
					$f_dis[] = isset($is_display[$idx]) ? $is_display[$idx] : 'yes';
					$f_plc[] = isset($place[$idx]) ? $place[$idx] : [];
				}
				if (!empty($f_sel)) {
					$selected = $f_sel;
					$is_display = $f_dis;
					$place = $f_plc;
				}
			}

			// Process all display conditions and determine if popup should show
			$should_show_popup = false;
			$blocked_by_negative = false;

			if (is_array($selected)) {
				// First pass: Check all "Is Not" conditions - if any match, block showing
				foreach ($selected as $index => $select) {
					$is_disp = isset($is_display[$index]) ? $is_display[$index] : 'yes';

					// Handle "Is Not" conditions - these block showing
					if ($is_disp == 'no') {
						// Check if current page/post matches the "Is Not" condition
						if ($select == 'selected-post' && is_single()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							if ($page_val && is_array($page_val)) {
								foreach ($page_val as $val) {
									$post_id = intval($val);
									if ($post_id == get_the_ID()) {
										// Current post is in "Is Not" list, don't show popup
										$blocked_by_negative = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'selected-page' && is_page()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							$page = get_post();
							if ($page && is_array($page_val)) {
								foreach ($page_val as $val) {
									$slug = $val;
									if ($slug == $page->post_name) {
										// Current page is in "Is Not" list, don't show popup
										$blocked_by_negative = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'all-pages' && is_page()) {
							// "Is Not" all pages - don't show on any page
							$blocked_by_negative = true;
							break;
						} elseif ($select == 'all-posts' && is_single() && !is_page()) {
							// "Is Not" all posts - don't show on any post (but allow pages)
							$blocked_by_negative = true;
							break;
						} elseif ($select == 'everywhere') {
							// "Is Not" everywhere - don't show anywhere
							$blocked_by_negative = true;
							break;
						} elseif ($select == 'selected-tags' && isset(get_queried_object()->term_id) && !is_category()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							$tag_id = get_queried_object()->term_id;
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if (intval($val) == $tag_id) {
										// Current tag is in "Is Not" list, don't show popup
										$blocked_by_negative = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'post-type' && is_single()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if (get_post_type() == $val) {
										// Current post type is in "Is Not" list, don't show popup
										$blocked_by_negative = true;
										break 2;
									}
								}
							}
						} elseif ($select == 'post-category' && is_category()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							$category_id = $wp_query->get_queried_object_id();
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if ($category_id == intval($val)) {
										// Current category is in "Is Not" list, don't show popup
										$blocked_by_negative = true;
										break 2;
									}
								}
							}
						}
					}
				}

				// If blocked by negative condition, don't proceed
				if ($blocked_by_negative) {
					return;
				}

				// Second pass: Check "Is" conditions - these can trigger showing
				foreach ($selected as $index => $select) {
					$is_disp = isset($is_display[$index]) ? $is_display[$index] : 'yes';

					// Handle "Is" conditions - these can trigger showing
					if ($is_disp == 'yes') {
						if ($select == 'selected-post' && is_single()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							if ($page_val && is_array($page_val)) {
								foreach ($page_val as $val) {
									$post_id = intval($val);
									if ($post_id == get_the_ID()) {
										$should_show_popup = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'selected-page' && is_page()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							$page = get_post();
							if ($page && is_array($page_val)) {
								foreach ($page_val as $val) {
									$slug = $val;
									if ($slug == $page->post_name) {
										$should_show_popup = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'all-pages' && is_page()) {
							$should_show_popup = true;
							break;
						} elseif ($select == 'all-posts' && is_single() && !is_page()) {
							$should_show_popup = true;
							break;
						} elseif ($select == 'everywhere') {
							$should_show_popup = true;
							break;
						} elseif ($select == 'selected-tags' && isset(get_queried_object()->term_id) && !is_category()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							$tag_id = get_queried_object()->term_id;
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if (intval($val) == $tag_id) {
										$should_show_popup = true;
										break 2; // Break out of both loops
									}
								}
							}
						} elseif ($select == 'all_products' && is_product()) {
							if ($is_disp == 'yes') {
								$should_show_popup = true;
								break;
							} elseif ($is_disp == 'no') {
								return;
							}
						} elseif ($select == 'archive_products' && (is_shop() || is_product_category() || is_product_tag())) {
							if ($is_disp == 'yes') {
								$should_show_popup = true;
								break;
							} elseif ($is_disp == 'no') {
								return;
							}
						} elseif ($select == 'selected_products' && is_product()) {
							$select_products = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($select_products)) {
								$select_products = json_decode(json_encode($select_products), true);
							}
							global $post;
							$current_product_id = $post->ID;

							if ($is_disp == 'yes' && is_array($select_products) && in_array($current_product_id, $select_products)) {
								$should_show_popup = true;
								break;
							} elseif ($is_disp == 'no' && in_array($current_product_id, $select_products)) {
								return;
							}
						} elseif ($select == 'product_categories' && is_product_category()) {
							$select_categories = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($select_categories)) {
								$select_categories = json_decode(json_encode($select_categories), true);
							}
							global $product;
							$product_category_ids = $product ? $product->get_category_ids() : [];

							if ($is_disp == 'yes' && is_array($select_categories) && array_intersect($product_category_ids, $select_categories)) {
								$should_show_popup = true;
								break;
							} elseif ($is_disp == 'no' && is_array($select_categories) && array_intersect($product_category_ids, $select_categories)) {
								return;
							}
						} elseif ($select == 'post-type' && is_single()) {
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if (get_post_type() == $val) {
										$should_show_popup = true;
										break 2;
									}
								}
							}
						} elseif ($select == 'post-category' && is_category()) {
							$category_id = $wp_query->get_queried_object_id();
							$page_val = isset($place[$index]) ? $place[$index] : [];
							// Convert to array if it's an object
							if (is_object($page_val)) {
								$page_val = json_decode(json_encode($page_val), true);
							}
							if (is_array($page_val)) {
								foreach ($page_val as $val) {
									if ($category_id == intval($val)) {
										$should_show_popup = true;
										break 2;
									}
								}
							}
						}

					}
				}
			}

			// Let extensions apply per-popup display checks, such as device, OS, browser, geo, or language targeting.
			$should_show_popup = apply_filters( 'instant_popup_builder_display_popup', $should_show_popup, $id );
			$should_show_popup = apply_filters( 'instant_popup_should_display', $should_show_popup, $id );

			// Only create popup once if any condition matches and no negative condition blocks it
			if ($should_show_popup) {
				if ( $type === 'announcement_bar' ) {
					$adv_raw = isset( $r->advance ) ? $r->advance : '';
					$adv_tmp = json_decode( (string) $adv_raw, true );
					$ab_pos  = ( is_array( $adv_tmp ) && isset( $adv_tmp['iab_position'] ) && (string) $adv_tmp['iab_position'] === 'bottom' ) ? 'bottom' : 'top';
					self::$ipb_ann_bar_deferred_queue[] = array(
						'row'      => $r,
						'position' => $ab_pos,
					);
					self::ipb_register_ann_bar_deferred_hooks();
				} else {
					$this->ipb_create_popups( $type );
				}
			}
		}
	}
	/**
	 * Return response after inser count into database
	 *
	 * @since 1.0.0
	 * @return string
	 */
	public function instant_view_count()
	{
		if (isset($_POST['id']) && !empty($_POST['id']) &&  isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'view_count_action')) {
			global $wpdb;
			$id = sanitize_text_field(wp_unslash($_POST['id']));
			$table_name = $wpdb->prefix . 'instant_popup_builder';

			// Check if popup exists
			$row = $wpdb->get_row($wpdb->prepare("SELECT views FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $id));

			if ($row) {
				// Only track in analytics system - let analytics handle the main table update
				if (class_exists('Instant_Popup_Builder_Analytics')) {
					$event_data = array(
						'page_url' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '',
						'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
						'timestamp' => current_time('mysql')
					);

					$result = Instant_Popup_Builder_Analytics::track_event($id, 'view', $event_data);

					if ($result) {
						echo "views count updated for popup " . esc_html( $id );
					} else {
						echo "views count update failed for popup " . esc_html( $id );
					}
				} else {
					// Fallback: Update main table directly if analytics class doesn't exist
					$count = $row->views ? intval($row->views) : 0;
					$count = $count + 1;

					$data = [
						'views' => strval($count)
					];
					$where = ['id' => $id];

					$update_result = $wpdb->update($table_name, $data, $where);

					if ($update_result !== false) {
						echo "views count updated for popup " . esc_html( $id );
					} else {
						echo "views count update failed for popup " . esc_html( $id );
					}
				}
			} else {
				echo "Popup not found with ID: " . esc_html( $id );
			}
		} else {
			echo "Invalid request - missing ID or nonce verification failed";
		}
		die();
	}

	/**
	 * Popup Count on click
	 *
	 */
	public function instant_click_count()
	{
		if (isset($_POST['id']) && !empty($_POST['id']) &&  isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'view_count_action')) {
			global $wpdb;
			$id = sanitize_text_field(wp_unslash($_POST['id']));
			$table_name = $wpdb->prefix . 'instant_popup_builder';

			// Check if popup exists
			$row = $wpdb->get_row($wpdb->prepare("SELECT clicks FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $id));

			if ($row !== null) {
				// Only track in analytics system - let analytics handle the main table update
				if (class_exists('Instant_Popup_Builder_Analytics')) {
					$event_data = array(
						'page_url' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '',
						'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
						'timestamp' => current_time('mysql')
					);

					$result = Instant_Popup_Builder_Analytics::track_event($id, 'click', $event_data);

					if ($result) {
						echo "click count updated for popup " . esc_html( $id );
					} else {
						echo "click count update failed for popup " . esc_html( $id );
					}
				} else {
					// Fallback: Update main table directly if analytics class doesn't exist
					$clicks = isset($row->clicks) && !empty($row->clicks) ? intval($row->clicks) : 0;
					$new_clicks = $clicks + 1;

					$data = [
						'clicks' => strval($new_clicks)
					];
					$where = ['id' => $id];

					$update_result = $wpdb->update($table_name, $data, $where);

					if ($update_result !== false) {
						echo "click count updated for popup " . esc_html($id);
					} else {
						echo "click count update failed for popup " . esc_html($id);
					}
				}
			} else {
				echo "Popup not found with ID: " . esc_html($id);
			}
		} else {
			echo "Invalid request - missing ID or nonce verification failed";
		}
		die();
	}

	/**
	 * Popup Conversion Count
	 * Tracks when a popup converts (e.g., successful subscription, form submission, etc.)
	 *
	 * @since 1.0.6.3
	 * @return void
	 */
	public function instant_conversion_count()
	{
		if (isset($_POST['id']) && !empty($_POST['id']) && isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'view_count_action')) {
			global $wpdb;
			$id = sanitize_text_field(wp_unslash($_POST['id']));
			$table_name = $wpdb->prefix . 'instant_popup_builder';

			// Check if popup exists
			$row = $wpdb->get_row($wpdb->prepare("SELECT clicks FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $id));

			if ($row !== null) {
				// Track in analytics system - conversions are tracked as clicks in the main table
				// but as 'conversion' events in the analytics table
				$result = false;
				if (class_exists('Instant_Popup_Builder_Analytics')) {
					$event_data = array(
						'page_url' => isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '',
						'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
						'timestamp' => current_time('mysql'),
						'conversion_type' => isset($_POST['conversion_type']) ? sanitize_text_field(wp_unslash($_POST['conversion_type'])) : 'subscription'
					);

					$result = Instant_Popup_Builder_Analytics::track_event($id, 'conversion', $event_data);
				}

				if ($result) {
					echo "conversion count updated for popup " . esc_html($id);
				} else {
					// Fallback: Update main table directly if analytics class doesn't exist
					$clicks = isset($row->clicks) && !empty($row->clicks) ? intval($row->clicks) : 0;
					$new_clicks = $clicks + 1;

					$data = [
						'clicks' => strval($new_clicks)
					];
					$where = ['id' => $id];

					$update_result = $wpdb->update($table_name, $data, $where);

					if ($update_result !== false) {
						echo "conversion count updated for popup " . esc_html($id);
					} else {
						echo "conversion count update failed for popup " . esc_html($id);
					}
				}
			} else {
				echo "Popup not found with ID: " . esc_html($id);
			}
		} else {
			echo "Invalid request - missing ID or nonce verification failed";
		}
		die();
	}

	/**
	 * Track analytics event using improved system
	 *
	 * @since 1.0.6.3
	 * @return void
	 */
	public function track_analytics_event() {
		// Verify nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ipb_analytics_action')) {
			wp_die('Security check failed');
		}

		$popup_id = isset($_POST['popup_id']) ? intval($_POST['popup_id']) : 0;
		$event_type = isset($_POST['event_type']) ? sanitize_text_field(wp_unslash($_POST['event_type'])) : '';
		$event_data = isset($_POST['event_data']) ? sanitize_text_field(wp_unslash($_POST['event_data'])) : array();

		// Sanitize event data
		$event_data = array_map('sanitize_text_field', $event_data);

		if ($popup_id && $event_type) {
			$result = Instant_Popup_Builder_Analytics::track_event($popup_id, $event_type, $event_data);

			if ($result) {
				wp_send_json_success(array(
					'message' => 'Analytics event tracked successfully',
					'event_type' => $event_type,
					'popup_id' => $popup_id
				));
			} else {
				wp_send_json_error('Failed to track analytics event');
			}
		} else {
			wp_send_json_error('Invalid popup ID or event type');
		}

		wp_die();
	}

	/**
	 * Get analytics data for popups
	 *
	 * @since 1.0.6.3
	 * @return void
	 */
	public function get_analytics_data() {
		// Verify nonce and admin access
		if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ipb_analytics_action')) {
			wp_die('Security check failed');
		}

		if (!current_user_can('manage_options')) {
			wp_die('Insufficient permissions');
		}

		$popup_id = isset($_POST['popup_id']) ? intval($_POST['popup_id']) : 0;
		$days = isset($_POST['days']) ? intval($_POST['days']) : 30;

		if ($popup_id) {
			$analytics = Instant_Popup_Builder_Analytics::get_popup_summary($popup_id, $days);
		} else {
			$analytics = Instant_Popup_Builder_Analytics::get_all_popups_summary($days);
		}

		wp_send_json_success($analytics);
		wp_die();
	}

	/**
	 * Get trigger option of the popup
	 *
	 * @return array | object
	 */

	// public function trigger_option()
	// {

	// 	global $wpdb;
	// 	$table_name = $wpdb->prefix . 'instant_popup_builder';
	// 	$row = $wpdb->prepare("SELECT id, triger FROM {$wpdb->prefix}instant_popup_builder");
	// 	$query = $wpdb->get_results($row);
	// 	// $query = $wpdb->get_results("SELECT id, triger from $table_name");
	// 	$trigger = [];
}

// Text Popup

class IpbTextPopup extends Instant_Popup_Builder_Public
{
 public function __construct($popup_name, $version)
    {
        parent::__construct($popup_name, $version);
        self::add_ipb_popup($this);
    }
    /**
     * Create text popup
     * @return string
     */
    public function ipb_create_popup_text()
    {

        return  include plugin_dir_path(__FILE__) . 'partials/shortcode-text.php';
    }
}

new IpbTextPopup("Instant Popup Builder", INSTANT_POPUP_BUILDER_VERSION);

// Image popup

class IpbImagePopup extends Instant_Popup_Builder_Public
{
 public function __construct($popup_name, $version)
    {
        parent::__construct($popup_name, $version);
        self::add_ipb_popup($this);
    }
    /**
     * Create text popup
     * @return string
     */
    public function ipb_create_popup_image()
    {

        return  include plugin_dir_path(__FILE__) . 'partials/shortcode-image.php';
    }
}

new IpbImagePopup("Instant Popup Builder", INSTANT_POPUP_BUILDER_VERSION);

// Html Popup popup

class IpbHtmlPopup extends Instant_Popup_Builder_Public
{
 public function __construct($popup_name, $version)
    {
        parent::__construct($popup_name, $version);
        self::add_ipb_popup($this);
    }

	/**
     * Create text popup
     * @return string
     */
    public function ipb_create_popup_html()
    {

        return  include plugin_dir_path(__FILE__) . 'partials/shortcode-html.php';
    }
}

new IpbHtmlPopup("Instant Popup Builder", INSTANT_POPUP_BUILDER_VERSION);

// Subscription Popup

class IpbSubscriptionPopup extends Instant_Popup_Builder_Public
{
 public function __construct($popup_name, $version)
    {
        parent::__construct($popup_name, $version);
        self::add_ipb_popup($this);
    }

	/**
     * Create text popup
     * @return string
     */
    public function ipb_create_popup_subscription()
    {

        return  include plugin_dir_path(__FILE__) . 'partials/shortcode-subscription.php';
    }
}

new IpbSubscriptionPopup("Instant Popup Builder", INSTANT_POPUP_BUILDER_VERSION);

// Feedback popup (extension)

if ( class_exists('Instant_Popup_Builder_Public') ) {
class IpbFeedbackPopup extends Instant_Popup_Builder_Public
{
 public function __construct($popup_name, $version)
    {
        parent::__construct($popup_name, $version);
        self::add_ipb_popup($this);
    }
    /**
     * Create feedback popup
     * @return string
     */
    public function ipb_create_popup_feedback()
    {
        $feedback_dir = defined( 'INSTANT_POPUP_FEEDBACK_DIR' )
            ? INSTANT_POPUP_FEEDBACK_DIR
            : WP_PLUGIN_DIR . '/instant-popup-feedback/';
        $shortcode_path = $feedback_dir . 'public/partials/shortcode-feedback.php';

        return file_exists( $shortcode_path ) ? include $shortcode_path : false;
    }
}

new IpbFeedbackPopup("Instant Popup Builder", INSTANT_POPUP_BUILDER_VERSION);
}
