<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.NamingConventions.PrefixAllGlobals -- Uses plugin-owned tables and legacy extension hooks.

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

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

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

if (!class_exists('Instant_Popup_Builder_Admin_Request')) {
    class Instant_Popup_Builder_Admin_Request
    {

        /**
         * Plugin Name
         * @since 1.0.0
         * @access private
         * @var string
         */
        private $plugin_name = "Instant Popup Builder";

        /**
         * Undocumented variable
         *
         * @since 1.0.0
         * @access private
         * @var string
         */

        private $version = "2.0.1.12";

        static $popups = array();

        /**
         * Constructor for admin request
         *
         */

        public function __construct($plugin_name, $version)
        {

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

        public static function add_popup($popup)
        {
            self::$popups[] = $popup;
        }

        public static function get_popups()
        {
            return self::$popups;
        }

        /**
         * Return Content for All Popups menu
         *
         * @since    1.0.0
         * @return string
         */
        public function ipb_check_popup_submt_request()
        {
            // Verify user capability
            if (!current_user_can('manage_options')) {
                return '';
            }

            if (!isset($_POST['instant_popup_builder_submit'])) {
                return '';
            }

            if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
                return '';
            }

            $type = isset($_POST['popup_temp_type']) ? sanitize_text_field(wp_unslash($_POST['popup_temp_type'])) : '';

            $handler_method = 'handle_' . $type;

            foreach (self::get_popups() as $popup) {
                if (method_exists($popup, $handler_method)) {
                    return $popup->$handler_method(); // call dynamically
                }
            }
            return false;
        }

        public function get_common_fields()
        {
            // Verify user capability
            if (!current_user_can('manage_options')) {
                return array();
            }

            if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
                return array();
            }
            // Validate and sanitize trigger options
            $trigger_options = isset($_POST['trigger_option']) ? sanitize_text_field(wp_unslash($_POST['trigger_option'])) : '';
            if (!is_string($trigger_options)) {
                $trigger_options = '';
            }

            /**
             * Sanitize multidimensional array recursively
             *
             * @since    1.0.0
             * @param array $data The array to sanitize
             * @return array Sanitized array
             */
            $sanitize_multidimensional_array = function($data) use (&$sanitize_multidimensional_array) {
                if (!is_array($data)) {
                    return sanitize_text_field($data);
                }

                $sanitized = [];
                foreach ($data as $key => $value) {
                    if (is_array($value)) {
                        $sanitized[$key] = $sanitize_multidimensional_array($value);
                    } else {
                        $sanitized[$key] = sanitize_text_field($value);
                    }
                }

                return $sanitized;
            };

            // Preserve the multi-dimensional structure of spec_val (display rule targets).
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- map_deep( sanitize_text_field ) on next statement sanitizes the tree; helper below is defense-in-depth.
            $spec_val_raw = isset($_POST['spec_val']) ? wp_unslash($_POST['spec_val']) : [];
            $spec_val_raw = is_array($spec_val_raw) ? map_deep($spec_val_raw, 'sanitize_text_field') : sanitize_text_field((string) $spec_val_raw);

            // Build base trigger data
            $trigger_data = [
                'trigger_option' => isset($_POST['trigger_option']) ? sanitize_text_field(wp_unslash($_POST['trigger_option'])) : '',
                'trigger_delay' => isset($_POST['trigger_delay']) ? array_map('sanitize_text_field', wp_unslash($_POST['trigger_delay'])) : [],
                'trigger_class_hover' => isset($_POST['trigger_class']) ? array_map('sanitize_text_field', wp_unslash($_POST['trigger_class'])) : [],
                'trigger_class_click' => isset($_POST['trigger_class_click']) ? array_map('sanitize_text_field', wp_unslash($_POST['trigger_class_click'])) : [],
                'target_device' => ['desktop', 'tablet', 'mobile'], // Universal device targeting
            ];

            /**
             * Filter to allow extensions to add their trigger settings
             *
             * Extensions should hook into this filter to add their settings
             * under their own key (e.g., 'adblock_trigger_settings')
             *
             * @since 1.1.4
             * @param array  $trigger_data   Base trigger data array
             * @param string $trigger_option Selected trigger option
             * @param array  $post_data      Raw POST data
             */
            $trigger_data = apply_filters('ipb_trigger_settings', $trigger_data, $trigger_options, $_POST);

            $spec_val_sanitized = $sanitize_multidimensional_array($spec_val_raw);
            // Normalize keys so spec_val indices always align with selected_option/is_display order.
            $spec_val_sanitized = is_array($spec_val_sanitized) ? array_values($spec_val_sanitized) : [];

            $select_option_arr = isset($_POST['selected_option']) ? array_map('sanitize_text_field', wp_unslash($_POST['selected_option'])) : [];
            $is_display_arr = isset($_POST['is_display']) ? array_map('sanitize_text_field', wp_unslash($_POST['is_display'])) : [];

            // Strip stale "everywhere" entries when specific rules also exist.
            if (count($select_option_arr) > 1) {
                $f_sel = [];
                $f_dis = [];
                $f_spec = [];
                foreach ($select_option_arr as $idx => $opt) {
                    if ($opt === 'everywhere') {
                        continue;
                    }
                    $f_sel[] = $opt;
                    $f_dis[] = isset($is_display_arr[$idx]) ? $is_display_arr[$idx] : 'yes';
                    $f_spec[] = isset($spec_val_sanitized[$idx]) ? $spec_val_sanitized[$idx] : [];
                }
                if (!empty($f_sel)) {
                    $select_option_arr = $f_sel;
                    $is_display_arr = $f_dis;
                    $spec_val_sanitized = $f_spec;
                }
            }

            $ipb_background_selection_req = isset($_POST['background_selection']) ? sanitize_text_field(wp_unslash($_POST['background_selection'])) : '';
            $ipb_background_image_url_req = isset($_POST['background_image_url']) ? sanitize_text_field(wp_unslash($_POST['background_image_url'])) : '';
            $ipb_back_image_toggle_req      = '';
            if ('image' === $ipb_background_selection_req) {
                if (!empty($_POST['back_image_toggle'])) {
                    $ipb_back_image_toggle_req = sanitize_text_field(wp_unslash($_POST['back_image_toggle']));
                } elseif (!empty($ipb_background_image_url_req)) {
                    $ipb_back_image_toggle_req = 'yes';
                }
            }

            return [
                'title' => isset($_POST['popup_title']) ? sanitize_text_field(wp_unslash($_POST['popup_title'])) : 'New Popup',
                'status' => (isset($_POST['instant_popup_builder_submit']) && $_POST['instant_popup_builder_submit'] === 'Publish') ? 'publish' : 'draft',
                'select_option' => $select_option_arr,
                'is_display' => $is_display_arr,
                'spec_val' => $spec_val_sanitized,
                'trigger' => $trigger_data,
                'closing' => [
                    'close_option' => function_exists( 'ipb_sanitize_closing_from_request' )
                        ? ipb_sanitize_closing_from_request()
                        : ( isset( $_POST['ipb_closing'] )
                            ? ( is_array( $_POST['ipb_closing'] )
                                ? array_map( 'sanitize_text_field', wp_unslash( $_POST['ipb_closing'] ) )
                                : array( sanitize_text_field( wp_unslash( (string) $_POST['ipb_closing'] ) ) ) )
                            : ( isset( $_POST['closing'] )
                                ? ( is_array( $_POST['closing'] )
                                    ? array_map( 'sanitize_text_field', wp_unslash( $_POST['closing'] ) )
                                    : array( sanitize_text_field( wp_unslash( (string) $_POST['closing'] ) ) ) )
                                : array() ) ),
                    'close_position' => isset($_POST['close_position']) ? sanitize_text_field(wp_unslash($_POST['close_position'])) : ''
                ],
                'limit' => [
                    'limit_count' => isset($_POST['limit_count']) ? sanitize_text_field(wp_unslash($_POST['limit_count'])) : '',
                    'limit_expiry' => isset($_POST['limit_expiry']) ? sanitize_text_field(wp_unslash($_POST['limit_expiry'])) : '',
                    'popup_position' => isset($_POST['position']) ? sanitize_text_field(wp_unslash($_POST['position'])) : ''
                ],
                'design' => [
                    'popup_theme' => isset($_POST['theme']) ? sanitize_text_field(wp_unslash($_POST['theme'])) : '',
                    'background_selection' => isset($_POST['background_selection']) ? sanitize_text_field(wp_unslash($_POST['background_selection'])) : '',
                    'back_color_toggle' => (isset($_POST['popup_temp_type']) && $_POST['popup_temp_type'] === 'popup_text') ? 'yes' : ((isset($_POST['back_color_toggle']) && $_POST['background_selection'] == 'color') ? sanitize_text_field(wp_unslash($_POST['back_color_toggle'])) : ''),
                    'background_color' => (isset($_POST['popup_temp_type']) && $_POST['popup_temp_type'] === 'popup_text') ? (isset($_POST['background_color']) ? sanitize_text_field(wp_unslash($_POST['background_color'])) : '#ffffff') : (( isset( $_POST['background_selection'], $_POST['background_color'] ) && 'color' === $_POST['background_selection'] ) ? sanitize_text_field( wp_unslash( $_POST['background_color'] ) ) : ''),
                    'back_image_toggle' => $ipb_back_image_toggle_req,
                    'background_image' => ( 'image' === $ipb_background_selection_req && !empty($ipb_background_image_url_req) ) ? $ipb_background_image_url_req : '',
                    // Keep existing z-index unless explicitly posted (field may be removed from UI).
                    'back_zindex' => isset($_POST['popup_zindex']) ? sanitize_text_field(wp_unslash($_POST['popup_zindex'])) : ( isset($_GET['edit_id']) ? (function () {
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                        $edit_id = absint(sanitize_text_field(wp_unslash($_GET['edit_id'] ?? 0)));
                        if (!$edit_id) return 1999999;
                        global $wpdb;
                        $row = $wpdb->get_row($wpdb->prepare("SELECT design FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $edit_id));
                        if (!$row || empty($row->design)) return 1999999;
                        $d = json_decode($row->design, true);
                        return isset($d['back_zindex']) && $d['back_zindex'] !== '' ? $d['back_zindex'] : 1999999;
                    })() : 1999999 ),
                    'border_enabled' => isset($_POST['border_enabled']) ? sanitize_text_field(wp_unslash($_POST['border_enabled'])) : 'no',
                    'border_width' => isset($_POST['border_width']) ? absint($_POST['border_width']) : 1,
                    'border_color' => isset($_POST['border_color']) ? sanitize_text_field(wp_unslash($_POST['border_color'])) : '#111827',
                    'back_image_pos_toggle' => isset($_POST['back_image_pos_toggle']) ? sanitize_text_field(wp_unslash($_POST['back_image_pos_toggle'])) : '',
                    'back_img_position' => isset($_POST['back_img_position']) ? sanitize_text_field(wp_unslash($_POST['back_img_position'])) : '',
                    'back_image_size' => isset($_POST['back_image_size']) ? sanitize_text_field(wp_unslash($_POST['back_image_size'])) : '',
                    'backcolor_opacity' => (isset($_POST['popup_temp_type']) && $_POST['popup_temp_type'] === 'popup_text') ? (isset($_POST['backcolor_opacity']) ? sanitize_text_field(wp_unslash($_POST['backcolor_opacity'])) : '1.0') : (isset($_POST['backcolor_opacity']) ? sanitize_text_field(wp_unslash($_POST['backcolor_opacity'])) : ''),
                    'backimage_opacity' => isset($_POST['backimage_opacity']) ? sanitize_text_field(wp_unslash($_POST['backimage_opacity'])) : '',
                    'design_width' => isset($_POST['design_width']) ? sanitize_text_field(wp_unslash($_POST['design_width'])) : '',
                    'design_height' => isset($_POST['design_height']) ? sanitize_text_field(wp_unslash($_POST['design_height'])) : '',
                    'design_percentage' => isset($_POST['design_percentage']) ? sanitize_text_field(wp_unslash($_POST['design_percentage'])) : '',
                    'design_percentage_toggle' => isset($_POST['design_percentage_toggle']) ? sanitize_text_field(wp_unslash($_POST['design_percentage_toggle'])) : '',
                    'animate_type' => isset($_POST['animate_type']) ? sanitize_text_field(wp_unslash($_POST['animate_type'])) : '',
                    'animate_speed' => isset($_POST['animate_speed']) ? sanitize_text_field(wp_unslash($_POST['animate_speed'])) : '',
                    'animate_origin' => isset($_POST['animate_origin']) ? sanitize_text_field(wp_unslash($_POST['animate_origin'])) : '',
                    'text_padding_top' => isset($_POST['text_padding_top']) ? min(100, absint($_POST['text_padding_top'])) : 20,
                    'text_padding_right' => isset($_POST['text_padding_right']) ? min(100, absint($_POST['text_padding_right'])) : 25,
                    'text_padding_bottom' => isset($_POST['text_padding_bottom']) ? min(100, absint($_POST['text_padding_bottom'])) : 20,
                    'text_padding_left' => isset($_POST['text_padding_left']) ? min(100, absint($_POST['text_padding_left'])) : 25,
                    'text_border_radius' => isset($_POST['text_border_radius']) ? min(30, absint($_POST['text_border_radius'])) : 12,
                    'text_color' => isset($_POST['text_color']) && sanitize_hex_color(wp_unslash($_POST['text_color'])) ? sanitize_hex_color(wp_unslash($_POST['text_color'])) : '#333333',
                    'text_font_size' => isset($_POST['text_font_size']) ? min(24, max(12, absint($_POST['text_font_size']))) : 16,
                    'text_line_height' => isset($_POST['text_line_height']) ? min(2.0, max(1.2, (float) $_POST['text_line_height'])) : 1.5
                ],
            ];
        }

        public function get_advance_fields()
        {
             if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
                return '';
            }
            $redirect_delay_mode = isset($_POST['redirect_delay_seconds']) ? sanitize_text_field(wp_unslash($_POST['redirect_delay_seconds'])) : '0';
            if ($redirect_delay_mode === 'custom') {
                $redirect_delay_value = isset($_POST['redirect_delay_custom_seconds']) ? absint($_POST['redirect_delay_custom_seconds']) : 3;
                if ($redirect_delay_value < 1) $redirect_delay_value = 1;
                if ($redirect_delay_value > 60) $redirect_delay_value = 60;
            } else {
                $redirect_delay_value = 0;
            }

            return [
                'action' => isset($_POST['action_click']) ? sanitize_text_field(wp_unslash($_POST['action_click'])) : '',
                'action_type' => isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : 'redirect',
                'url' => isset($_POST['redirect_url']) ? sanitize_text_field(wp_unslash($_POST['redirect_url'])) : '',
                'redirect_delay_seconds' => $redirect_delay_value,
                'tab' => isset($_POST['action_new_tab']) ? sanitize_text_field(wp_unslash($_POST['action_new_tab'])) : '',
                'action_popup_id' => isset($_POST['action_popup_id']) ? absint($_POST['action_popup_id']) : 0,
                'sound_open' => isset($_POST['sound_open']) ? sanitize_text_field(wp_unslash($_POST['sound_open'])) : '',
                'sound_close' => isset($_POST['sound_close']) ? sanitize_text_field(wp_unslash($_POST['sound_close'])) : '',
                'sound_open_file' => isset($_POST['sound_open_url']) ? sanitize_text_field(wp_unslash($_POST['sound_open_url'])) : '',
                'sound_close_file' => isset($_POST['sound_closing_url']) ? sanitize_text_field(wp_unslash($_POST['sound_closing_url'])) : ''
            ];
        }
    }

    new Instant_Popup_Builder_Admin_Request(
        "Instant Popup Builder",
        defined('INSTANT_POPUP_BUILDER_VERSION') ? INSTANT_POPUP_BUILDER_VERSION : '2.0.1.12'
    );
}

class TextRequest extends Instant_Popup_Builder_Admin_Request
{

    public function __construct($plugin_name, $version)
    {
        parent::__construct($plugin_name, $version);
        self::add_popup($this);
    }

    public function handle_popup_text()
    {
        if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
            return '';
        }
        // For text popups, we need to preserve TinyMCE formatting, so don't use sanitize_text_field
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Rich HTML/TinyMCE; sanitized by ipb_sanitize_text_popup_content() (wp_kses-based) immediately below.
        $popup_type_value_raw = isset($_POST['popup_type_value']) ? wp_unslash($_POST['popup_type_value']) : '';
        $popup_type_value_unslashed = is_string($popup_type_value_raw) ? $popup_type_value_raw : '';
        // Use custom sanitization function that preserves all TinyMCE formatting including inline styles
        $text = ipb_sanitize_text_popup_content($popup_type_value_unslashed);
        if (empty($text))
            return false;
        $fields = $this->get_common_fields();
        $advance = $this->get_advance_fields();
        $all_args = array_values($fields);
        $all_args[] = $advance;

        return $this->ipb_query_popup_text($text, ...$all_args);
        // return $this->ipb_query_popup_text($text, ...array_values($fields), $advance);
    }

    /**
     * Return Content for All Popups menu
     *
     * @since    1.0.0
     * @return string
     */
        public function ipb_query_popup_text($text, $title, $status, $select_option, $is_display, $spec_val, $trigger, $closing, $limit, $design, $advance)
    {

        global $wpdb;
        $table_name = $wpdb->prefix . 'instant_popup_builder';
        $all_popup_url = menu_page_url('instant-popup-builder', false);
        $display = [

            'selected' => $select_option,
            'is_display' => $is_display,
            'place' => $spec_val
        ];
        $data = [
            'title' => $title,
            'type' => 'text',
            'status' => $status,
            'content' => wp_json_encode($text),
            'display' => wp_json_encode($display),
            'ipb_trigger' => wp_json_encode($trigger),
            'closing' => wp_json_encode($closing),
            'position' => wp_json_encode($limit),
            'design' => wp_json_encode($design),
            'advance' => wp_json_encode($advance),
            'class' => ( $status === 'publish' ? 'yes' : '' )
        ];
        $format = ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert($table_name, $data, $format);
        $id = $wpdb->insert_id;

        // Save extension trigger data via Extension API
        if (class_exists('Instant_Popup_Builder_Extension_API') && isset($trigger['trigger_option'])) {
            $trigger_option = is_string($trigger['trigger_option']) ? $trigger['trigger_option'] : '';
            $safe_trigger_option = (string) ( $trigger_option ?? '' );
            $trigger_settings_key = str_replace('-', '_', $safe_trigger_option) . '_settings';
            $trigger_settings = isset($trigger[$trigger_settings_key])
                ? $trigger[$trigger_settings_key]
                : [];
            Instant_Popup_Builder_Extension_API::save_trigger_data($id, $trigger['trigger_option'], $trigger_settings);
        }

        if(class_exists('Instant_Popup_Custom_Targeting_Admin')){
        $custom_trigger_Cls = new Instant_Popup_Custom_Targeting_Admin;
         $custom_trigger_Cls->save_custom_targeting_settings($id);

        }
        // add_query_arg( 'popup_id', $id );

        if ($wpdb->last_error) {
            return "Error: " . $wpdb->last_error;
        } else {

            // Determine what to do after publishing based on global setting.
            $post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');
            $dashboard_url         = $all_popup_url . '&edit_id=' . $id . '&type=text';
            $redirect_url          = $all_popup_url;

            // Build a human friendly success message.
            $success_message = ('publish' === $status)
                ? __('The popup has been published.', 'instant-popup-builder')
                : __('The popup has been saved as a draft.', 'instant-popup-builder');

        ?>
            <?php if ('stay' === $post_publish_behavior) : ?>
                <?php
                // Redirect immediately to the edit page so user stays on the editor
                // Add success parameter to show toast on the edit page
                $edit_url_with_success = $dashboard_url . '&published=1';
                ?>
                <script>
                    // Redirect immediately to edit page
                    window.location.href = '<?php echo esc_js( esc_url( $edit_url_with_success ) ); ?>';
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $edit_url_with_success ); ?>">
                </noscript>
            <?php else : ?>
                <div id="ipb-popup-success-modal" style="position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55); display:flex; align-items:center; justify-content:center; z-index:99999;">
                    <div style="padding:24px 28px; background:#ffffff; border-radius:10px; max-width:420px; width:100%; box-shadow:0 18px 45px rgba(15,23,42,0.25); text-align:left; font-family:inherit;">
                        <div style="display:flex; align-items:flex-start; gap:12px;">
                            <span style="display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:999px; background:#16a34a1a; color:#16a34a; font-size:16px;">&#10003;</span>
                            <div>
                                <h2 style="margin:0 0 4px; font-size:16px; font-weight:600; color:#111827;">
                                    <?php esc_html_e('Popup saved successfully', 'instant-popup-builder'); ?>
                                </h2>
                                <p style="margin:0; font-size:13px; color:#6b7280;">
                                    <?php esc_html_e('You will now be redirected to the Popups dashboard.', 'instant-popup-builder'); ?>
                                </p>
                            </div>
                        </div>
                        <div style="margin-top:16px; display:flex; justify-content:flex-end; gap:8px;">
                            <button type="button" id="ipb-popup-success-modal-close" style="padding:6px 14px; border-radius:6px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:13px; cursor:pointer;">
                                <?php esc_html_e('Close', 'instant-popup-builder'); ?>
                            </button>
                        </div>
                    </div>
                </div>
                <script>
                    (function() {
                        var redirectUrl = '<?php echo esc_js( esc_url( $redirect_url ) ); ?>';
                        var redirectToDashboard = function() {
                            window.location.assign(redirectUrl);
                        };

                        window.setTimeout(redirectToDashboard, 2000);

                        var closeButton = document.getElementById('ipb-popup-success-modal-close');
                        if (closeButton) {
                            closeButton.addEventListener('click', redirectToDashboard);
                        }
                    })();
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $redirect_url ); ?>">
                </noscript>
            <?php endif; ?>
        <?php
            exit;
        }
    }
}

new TextRequest(
    'Instant Popup Builder',
    defined('INSTANT_POPUP_BUILDER_VERSION') ? INSTANT_POPUP_BUILDER_VERSION : '2.0.1.12'
);

class ImageRequest extends Instant_Popup_Builder_Admin_Request
{

    public function __construct($plugin_name, $version)
    {
        parent::__construct($plugin_name, $version);
        self::add_popup($this);
    }

    /**
     * Return Content for All Popups menu
     *
     * @since    1.0.0
     * @return array | string
     */
    public function ipb_query_popup_image($image, $title, $status, $select_option, $is_display, $spec_val, $trigger, $closing, $limit, $design, $advance)
    {

        global $wpdb;
        $table_name = $wpdb->prefix . 'instant_popup_builder';
        $all_popup_url = menu_page_url('instant-popup-builder', false);
        $display = [

            'selected' => $select_option,
            'is_display' => $is_display,
            'place' => $spec_val
        ];
        $data = [
            'title' => $title,
            'type' => 'image',
            'status' => $status,
            'content' => wp_json_encode($image),
            'display' => wp_json_encode($display),
            'ipb_trigger' => wp_json_encode($trigger),
            'closing' => wp_json_encode($closing),
            'position' => wp_json_encode($limit),
            'design' => wp_json_encode($design),
            'advance' => wp_json_encode($advance),
            'class' => ( $status === 'publish' ? 'yes' : '' )
        ];
        $format = ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert($table_name, $data, $format);
        $id = $wpdb->insert_id;

        // Save extension trigger data via Extension API
        if (class_exists('Instant_Popup_Builder_Extension_API') && isset($trigger['trigger_option'])) {
            $trigger_option = is_string($trigger['trigger_option']) ? $trigger['trigger_option'] : '';
            $safe_trigger_option = (string) ( $trigger_option ?? '' );
            $trigger_settings_key = str_replace('-', '_', $safe_trigger_option) . '_settings';
            $trigger_settings = isset($trigger[$trigger_settings_key])
                ? $trigger[$trigger_settings_key]
                : [];
            Instant_Popup_Builder_Extension_API::save_trigger_data($id, $trigger['trigger_option'], $trigger_settings);
        }

        if ($wpdb->last_error) {

            return "Error: " . $wpdb->last_error;
        } else {

            // Determine what to do after publishing based on global setting.
            $post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');
            $dashboard_url         = $all_popup_url . '&edit_id=' . $id . '&type=image';
            $redirect_url          = $all_popup_url;

            // Build a human friendly success message.
            $success_message = ('publish' === $status)
                ? __('The popup has been published.', 'instant-popup-builder')
                : __('The popup has been saved as a draft.', 'instant-popup-builder');

        ?>
            <?php if ('stay' === $post_publish_behavior) : ?>
                <?php
                // Redirect immediately to the edit page so user stays on the editor
                // Add success parameter to show toast on the edit page
                $edit_url_with_success = $dashboard_url . '&published=1';
                ?>
                <script>
                    // Redirect immediately to edit page
                    window.location.href = '<?php echo esc_js( esc_url( $edit_url_with_success ) ); ?>';
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $edit_url_with_success ); ?>">
                </noscript>
            <?php else : ?>
                <div id="ipb-popup-success-modal" style="position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55); display:flex; align-items:center; justify-content:center; z-index:99999;">
                    <div style="padding:24px 28px; background:#ffffff; border-radius:10px; max-width:420px; width:100%; box-shadow:0 18px 45px rgba(15,23,42,0.25); text-align:left; font-family:inherit;">
                        <div style="display:flex; align-items:flex-start; gap:12px;">
                            <span style="display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:999px; background:#16a34a1a; color:#16a34a; font-size:16px;">&#10003;</span>
                            <div>
                                <h2 style="margin:0 0 4px; font-size:16px; font-weight:600; color:#111827;">
                                    <?php esc_html_e('Popup saved successfully', 'instant-popup-builder'); ?>
                                </h2>
                                <p style="margin:0; font-size:13px; color:#6b7280;">
                                    <?php esc_html_e('You will now be redirected to the Popups dashboard.', 'instant-popup-builder'); ?>
                                </p>
                            </div>
                        </div>
                        <div style="margin-top:16px; display:flex; justify-content:flex-end; gap:8px;">
                            <button type="button" id="ipb-popup-success-modal-close" style="padding:6px 14px; border-radius:6px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:13px; cursor:pointer;">
                                <?php esc_html_e('Close', 'instant-popup-builder'); ?>
                            </button>
                        </div>
                    </div>
                </div>
                <script>
                    (function() {
                        var redirectUrl = '<?php echo esc_js( esc_url( $redirect_url ) ); ?>';
                        var redirectToDashboard = function() {
                            window.location.assign(redirectUrl);
                        };

                        window.setTimeout(redirectToDashboard, 2000);

                        var closeButton = document.getElementById('ipb-popup-success-modal-close');
                        if (closeButton) {
                            closeButton.addEventListener('click', redirectToDashboard);
                        }
                    })();
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $redirect_url ); ?>">
                </noscript>
            <?php endif; ?>
        <?php
            exit;
        }
    }

    public function handle_popup_image()
    {
        if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
            return '';
        }
        $imageUrl = isset($_POST['popu_image_url']) ? sanitize_text_field(wp_unslash($_POST['popu_image_url'])) : '';
        $fields = $this->get_common_fields();
        $advance = $this->get_advance_fields();
        $all_args = array_values($fields);
        $all_args[] = $advance;
        return $this->ipb_query_popup_image($imageUrl, ...$all_args);
        // return $this->ipb_query_popup_image($imageUrl, ...array_values($fields), $advance);
    }
}

new ImageRequest(
    'Instant Popup Builder',
    defined('INSTANT_POPUP_BUILDER_VERSION') ? INSTANT_POPUP_BUILDER_VERSION : '2.0.1.12'
);

// Html popup

class HtmlRequest extends Instant_Popup_Builder_Admin_Request
{

    public function __construct($plugin_name, $version)
    {
        parent::__construct($plugin_name, $version);
        self::add_popup($this);
    }

    /**
     * Return Content for All Popups menu
     *
     * @since    1.0.0
     * @return string | array
     */
    public function ipb_query_popup_html($text, $title, $status, $select_option, $is_display, $spec_val, $trigger, $closing, $limit, $design, $advance)
    {

        global $wpdb;
        $table_name = $wpdb->prefix . 'instant_popup_builder';
        $all_popup_url = menu_page_url('instant-popup-builder', false);
        $display = [

            'selected' => $select_option,
            'is_display' => $is_display,
            'place' => $spec_val
        ];
        $data = [
            'title' => $title,
            'type' => 'html',
            'status' => $status,
            'content' => wp_json_encode($text),
            'display' => wp_json_encode($display),
            'ipb_trigger' => wp_json_encode($trigger),
            'closing' => wp_json_encode($closing),
            'position' => wp_json_encode($limit),
            'design' => wp_json_encode($design),
            'advance' => wp_json_encode($advance),
            'class' => ( $status === 'publish' ? 'yes' : '' )
        ];
        $format = ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert($table_name, $data, $format);
        $id = $wpdb->insert_id;

        // Save extension trigger data via Extension API
        if (class_exists('Instant_Popup_Builder_Extension_API') && isset($trigger['trigger_option'])) {
            $trigger_option = is_string($trigger['trigger_option']) ? $trigger['trigger_option'] : '';
            $safe_trigger_option = (string) ( $trigger_option ?? '' );
            $trigger_settings_key = str_replace('-', '_', $safe_trigger_option) . '_settings';
            $trigger_settings = isset($trigger[$trigger_settings_key])
                ? $trigger[$trigger_settings_key]
                : [];
            Instant_Popup_Builder_Extension_API::save_trigger_data($id, $trigger['trigger_option'], $trigger_settings);
        }

        if ($wpdb->last_error) {

            return "Error: " . $wpdb->last_error;
        } else {

            // Determine what to do after publishing based on global setting.
            $post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');
            $dashboard_url         = $all_popup_url . '&edit_id=' . $id . '&type=html';
            $redirect_url          = $all_popup_url;

            // Build a human friendly success message.
            $success_message = ('publish' === $status)
                ? __('The popup has been published.', 'instant-popup-builder')
                : __('The popup has been saved as a draft.', 'instant-popup-builder');

             ?>
            <?php if ('stay' === $post_publish_behavior) : ?>
                <?php
                // Redirect immediately to the edit page so user stays on the editor
                // Add success parameter to show toast on the edit page
                $edit_url_with_success = $dashboard_url . '&published=1';
                ?>
                <script>
                    // Redirect immediately to edit page
                    window.location.href = '<?php echo esc_js( esc_url( $edit_url_with_success ) ); ?>';
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $edit_url_with_success ); ?>">
                </noscript>
            <?php else : ?>
                <div id="ipb-popup-success-modal" style="position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55); display:flex; align-items:center; justify-content:center; z-index:99999;">
                    <div style="padding:24px 28px; background:#ffffff; border-radius:10px; max-width:420px; width:100%; box-shadow:0 18px 45px rgba(15,23,42,0.25); text-align:left; font-family:inherit;">
                        <div style="display:flex; align-items:flex-start; gap:12px;">
                            <span style="display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:999px; background:#16a34a1a; color:#16a34a; font-size:16px;">&#10003;</span>
                            <div>
                                <h2 style="margin:0 0 4px; font-size:16px; font-weight:600; color:#111827;">
                                    <?php esc_html_e('Popup saved successfully', 'instant-popup-builder'); ?>
                                </h2>
                                <p style="margin:0; font-size:13px; color:#6b7280;">
                                    <?php esc_html_e('You will now be redirected to the Popups dashboard.', 'instant-popup-builder'); ?>
                                </p>
                            </div>
                        </div>
                        <div style="margin-top:16px; display:flex; justify-content:flex-end; gap:8px;">
                            <button type="button" id="ipb-popup-success-modal-close" style="padding:6px 14px; border-radius:6px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:13px; cursor:pointer;">
                                <?php esc_html_e('Close', 'instant-popup-builder'); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <script>
                    (function() {
                        var redirectUrl = '<?php echo esc_js( esc_url( $redirect_url ) ); ?>';
                        var redirectToDashboard = function() {
                            window.location.assign(redirectUrl);
                        };

                        window.setTimeout(redirectToDashboard, 2000);

                        var closeButton = document.getElementById('ipb-popup-success-modal-close');
                        if (closeButton) {
                            closeButton.addEventListener('click', redirectToDashboard);
                        }
                    })();
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $redirect_url ); ?>">
                </noscript>
            <?php endif; ?>
        <?php
            exit;
        }
    }

    public function handle_popup_html()
    {
        if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
            return '';
        }
        // For HTML popups, we need to preserve HTML structure, so don't use sanitize_text_field
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Custom HTML popup content; sanitized by ipb_sanitize_html_popup_content() (wp_kses-based) immediately below.
        $popup_type_value_raw = isset($_POST['popup_type_value']) ? wp_unslash($_POST['popup_type_value']) : '';
        $popup_type_value_unslashed = is_string($popup_type_value_raw) ? $popup_type_value_raw : '';
        // Use custom sanitization function that allows more HTML tags and attributes for HTML popups
        $html = ipb_sanitize_html_popup_content($popup_type_value_unslashed);
        if (empty($html))
            return false;
        $fields = $this->get_common_fields();
        $advance = $this->get_advance_fields();
        $all_args = array_values($fields);
        $all_args[] = $advance;
        return $this->ipb_query_popup_html($html, ...$all_args);
        // return $this->ipb_query_popup_html($html, ...array_values($fields), $advance);
    }
}

new HtmlRequest(
    'Instant Popup Builder',
    defined('INSTANT_POPUP_BUILDER_VERSION') ? INSTANT_POPUP_BUILDER_VERSION : '2.0.1.12'
);

// Html popup

class SubscriptionRequest extends Instant_Popup_Builder_Admin_Request
{

    public function __construct($plugin_name, $version)
    {
        parent::__construct($plugin_name, $version);
        self::add_popup($this);
    }

    /**
     * Return Content for All Popups menu
     *
     * @since    1.0.0
     * @return string | array
     */
    public function ipb_query_popup_subscription($text, $title, $status, $select_option, $is_display, $spec_val, $trigger, $closing, $limit, $design, $advance)
    {

        global $wpdb;
        $table_name = $wpdb->prefix . 'instant_popup_builder';
        $all_popup_url = menu_page_url('instant-popup-builder', false);
        $display = [

            'selected' => $select_option,
            'is_display' => $is_display,
            'place' => $spec_val
        ];
        $data = [
            'title' => $title,
            'type' => 'subscription',
            'status' => $status,
            'content' => wp_json_encode($text),
            'display' => wp_json_encode($display),
            'ipb_trigger' => wp_json_encode($trigger),
            'closing' => wp_json_encode($closing),
            'position' => wp_json_encode($limit),
            'design' => wp_json_encode($design),
            'advance' => wp_json_encode($advance),
            'class' => ( $status === 'publish' ? 'yes' : '' )
        ];
        $format = ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'];
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $wpdb->insert($table_name, $data, $format);
        $id = $wpdb->insert_id;

        // Save extension trigger data via Extension API
        if (class_exists('Instant_Popup_Builder_Extension_API') && isset($trigger['trigger_option'])) {
            $trigger_option = is_string($trigger['trigger_option']) ? $trigger['trigger_option'] : '';
            $safe_trigger_option = (string) ( $trigger_option ?? '' );
            $trigger_settings_key = str_replace('-', '_', $safe_trigger_option) . '_settings';
            $trigger_settings = isset($trigger[$trigger_settings_key])
                ? $trigger[$trigger_settings_key]
                : [];
            Instant_Popup_Builder_Extension_API::save_trigger_data($id, $trigger['trigger_option'], $trigger_settings);
        }

        if(class_exists('Instant_Popup_Builder_Admin')){
        $subscription_save_settings = new Instant_Popup_Builder_Admin();
        $subscription_save_settings->save_popup_subscription_settings($id);

        }
        if ($wpdb->last_error) {

            return "Error: " . $wpdb->last_error;
        } else {

            // Determine what to do after publishing based on global setting.
            $post_publish_behavior = get_option('instant_popup_builder_post_publish_behavior', 'dashboard');
            $dashboard_url         = $all_popup_url . '&edit_id=' . $id . '&type=subscription';
            $redirect_url          = $all_popup_url;

            // Build a human friendly success message.
            $success_message = ('publish' === $status)
                ? __('The popup has been published.', 'instant-popup-builder')
                : __('The popup has been saved as a draft.', 'instant-popup-builder');

             ?>
            <?php if ('stay' === $post_publish_behavior) : ?>
                <?php
                // Redirect immediately to the edit page so user stays on the editor
                // Add success parameter to show toast on the edit page
                $edit_url_with_success = $dashboard_url . '&published=1';
                ?>
                <script>
                    // Redirect immediately to edit page
                    window.location.href = '<?php echo esc_js( esc_url( $edit_url_with_success ) ); ?>';
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $edit_url_with_success ); ?>">
                </noscript>
            <?php else : ?>
                <div id="ipb-popup-success-modal" style="position: fixed; inset: 0; background: rgba(15, 23, 42, 0.55); display:flex; align-items:center; justify-content:center; z-index:99999;">
                    <div style="padding:24px 28px; background:#ffffff; border-radius:10px; max-width:420px; width:100%; box-shadow:0 18px 45px rgba(15,23,42,0.25); text-align:left; font-family:inherit;">
                        <div style="display:flex; align-items:flex-start; gap:12px;">
                            <span style="display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:999px; background:#16a34a1a; color:#16a34a; font-size:16px;">&#10003;</span>
                            <div>
                                <h2 style="margin:0 0 4px; font-size:16px; font-weight:600; color:#111827;">
                                    <?php esc_html_e('Popup saved successfully', 'instant-popup-builder'); ?>
                                </h2>
                                <p style="margin:0; font-size:13px; color:#6b7280;">
                                    <?php esc_html_e('You will now be redirected to the Popups dashboard.', 'instant-popup-builder'); ?>
                                </p>
                            </div>
                        </div>
                        <div style="margin-top:16px; display:flex; justify-content:flex-end; gap:8px;">
                            <button type="button" id="ipb-popup-success-modal-close" style="padding:6px 14px; border-radius:6px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:13px; cursor:pointer;">
                                <?php esc_html_e('Close', 'instant-popup-builder'); ?>
                            </button>
                        </div>
                    </div>
                </div>

                <script>
                    (function() {
                        var redirectUrl = '<?php echo esc_js( esc_url( $redirect_url ) ); ?>';
                        var redirectToDashboard = function() {
                            window.location.assign(redirectUrl);
                        };

                        window.setTimeout(redirectToDashboard, 2000);

                        var closeButton = document.getElementById('ipb-popup-success-modal-close');
                        if (closeButton) {
                            closeButton.addEventListener('click', redirectToDashboard);
                        }
                    })();
                </script>
                <noscript>
                    <meta http-equiv="refresh" content="0;url=<?php echo esc_url( $redirect_url ); ?>">
                </noscript>
            <?php endif; ?>
        <?php
            exit;
        }
    }

    public function handle_popup_subscription()
    {
        if (!isset($_POST['_wpnonce']) || empty($_POST['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'instant_popup_nonce')) {
            return '';
        }
        $imageUrl = isset($_POST['popu_image_url']) ? sanitize_text_field(wp_unslash($_POST['popu_image_url'])) : '';
                $advance = $this->get_advance_fields();
                $advance = array_merge($advance, [
                    'template_style' => isset($_POST['template_style']) ? sanitize_text_field(wp_unslash($_POST['template_style'])) : 'basic',
                    'popup_main_title' => isset($_POST['popup_main_title']) ? sanitize_text_field(wp_unslash($_POST['popup_main_title'])) : '',
                    'popup_description' => isset($_POST['popup_description']) ? sanitize_textarea_field(wp_unslash($_POST['popup_description'])) : '',
                    'first_label' => isset($_POST['first_label']) ? sanitize_text_field(wp_unslash($_POST['first_label'])) : '',
                    'first_placeholder' => isset($_POST['first_placeholder']) ? sanitize_text_field(wp_unslash($_POST['first_placeholder'])) : '',
                    'email_label' => isset($_POST['email_label']) ? sanitize_text_field(wp_unslash($_POST['email_label'])) : '',
                    'email_placeholder' => isset($_POST['email_placeholder']) ? sanitize_text_field(wp_unslash($_POST['email_placeholder'])) : '',
                    'button_text' => isset($_POST['button_text']) ? sanitize_text_field(wp_unslash($_POST['button_text'])) : '',
                    'privacy_label' => isset($_POST['privacy_label']) ? sanitize_text_field(wp_unslash($_POST['privacy_label'])) : '',
                    'pricacy_url' => isset($_POST['pricacy_url']) ? sanitize_text_field(wp_unslash($_POST['pricacy_url'])) : '',
                    'terms_url' => isset($_POST['terms_url']) ? sanitize_text_field(wp_unslash($_POST['terms_url'])) : '',
                    // Basic Newsletter specific fields
                    'image_position' => isset($_POST['image_position']) ? sanitize_text_field(wp_unslash($_POST['image_position'])) : 'right',
                    // Newsletter Horizontal specific fields
                    'button_color' => isset($_POST['button_color']) ? sanitize_text_field(wp_unslash($_POST['button_color'])) : '',
                    'use_custom_icon' => isset($_POST['use_custom_icon']) ? sanitize_text_field(wp_unslash($_POST['use_custom_icon'])) : 'no',
                    'custom_icon_url' => isset($_POST['custom_icon_url']) ? sanitize_url(wp_unslash($_POST['custom_icon_url'])) : '',
                    // Exit Intent specific fields
                    'gradient_start' => isset($_POST['gradient_start']) ? sanitize_text_field(wp_unslash($_POST['gradient_start'])) : '',
                    'gradient_end' => isset($_POST['gradient_end']) ? sanitize_text_field(wp_unslash($_POST['gradient_end'])) : '',
                    'icon_color' => isset($_POST['icon_color']) ? sanitize_text_field(wp_unslash($_POST['icon_color'])) : ''
                ]);
                $fields = $this->get_common_fields();
                $all_args = array_values($fields);
                $all_args[] = $advance;
                return $this->ipb_query_popup_subscription($imageUrl, ...$all_args);
    }
}

new SubscriptionRequest(
    'Instant Popup Builder',
    defined('INSTANT_POPUP_BUILDER_VERSION') ? INSTANT_POPUP_BUILDER_VERSION : '2.0.1.12'
);
