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

namespace Admin\Settings\Edit;

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

/**
 * 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-edit-popup functionality of the plugin.
 *
 * @package    Instant_Popup_Builder
 * @subpackage Instant_Popup_Builder/admin
 * @author     7th Sky Software’s <example@gmail.com>
 */

use InstantPopupBuildr\Admin\PopupBuilder\Trigger\Class_instant_popup_builder_trigger;
use InstantPopup\Settings\class_instant_setting;

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

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

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

        /**
         * Initialize the class and set its properties.
         *
         * @since    1.0.0
         * @param      string    $plugin_name       The name of this plugin.
         * @param      string    $version    The version of this plugin.
         */

        protected static $tabs = [
            "ipb_pdf" => 'PDF Settings',
            "ipb_subscription" => 'Subscription Settings',
            "ipb_text" => 'Text Popup',
            "ipb_image_gallery" => 'Image Gallery Settings',
            "ipb_age_verification" => 'Age Verification Settings',
            "ipb_recent_orders" => 'Recent Orders Settings',
            "general" => 'General',
            //"contact_form" => 'Contact Form',
            "design" => 'Design',
            // "advance" => 'Advanced',
            "condition" => 'Conditions'
        ];

        protected static array $child_tabs = [];

        public function __construct()
        {

            // add_action('general_closing_tab_edit', [$this, 'general_closing_tab_content']);
        }

        /**
         * Initialize default tabs
         */
        public static function init()
        {

            $subscription = "";
            $temp_type = "";
            $subscription_license_active = get_option('subscription_license_active');
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if(isset($_GET['type'])){
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $temp_type = isset($_GET['type']) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : '';
            }
            if ( is_plugin_active( 'instant-popup-subscription/instant-popup-subscription.php' ) && $subscription_license_active == 'yes' && $temp_type == 'subscription') {
            $subscription = 'Subscription';
            //self::addTab('general', 'subscription', 'Subscription');
            }

            $condition_tabs = [
                "targeting" =>__('Targeting', 'instant-popup-builder'),
                "language_targeting" => __('Language Targeting', 'instant-popup-builder'),
                "location" => __('Location', 'instant-popup-builder'),
                "scheduling" =>__('Scheduling', 'instant-popup-builder'),
            ];
            $contact_tabs = [
                    'form_settings' => __('Form Settings', 'instant-popup-builder'),
                    'form_design' => __('Form Design', 'instant-popup-builder'),
            ];
            self::$child_tabs = [
                'general' => [
                    "display"    => __('Display', 'instant-popup-builder'),
                    "trigger"    => __('Trigger', 'instant-popup-builder'),
                    "closing"    => __('Closing', 'instant-popup-builder'),
                    "limitation" => __('Frequency', 'instant-popup-builder'),
                    "position"   => __('Position', 'instant-popup-builder'),
                    "action" => __('Action', 'instant-popup-builder'),
                    //"subscription" => $subscription,
                ],
                'contact_form' => apply_filters('instant_popup_builder_contact_form_tabs', $contact_tabs),
                'design' => [
                    "background" => __('Background', 'instant-popup-builder'),
                    "size"       => __('Size', 'instant-popup-builder'),
                    "animation"  => __('Animation', 'instant-popup-builder'),
                    "sound"  => __('Sound', 'instant-popup-builder'),
                    "text-styling" => __('Text Popup', 'instant-popup-builder'),
                ],
                // 'advance' => [

                //     "sound"  => __('Sound', 'instant-popup-builder'),
                // ],
                'condition' => apply_filters('instant_popup_builder_condition_tabs', $condition_tabs),
            ];
        }

        /**
         * Set tabs
         *
         * @param array
         * @return void
         *
         */
        public static function setting_set_edit_tabs($tabs = [])
        {

            self::$tabs = $tabs;
        }

        /**
         * Get setting tabs
         *
         * @return array
         *
         */
        public static function setting_get_edit_tabs()
        {

            return self::$tabs;
        }

        /**
         * Set child tabs for specific category
         *
         * @param string $category
         * @param string $popup_type Optional popup type to filter tabs conditionally
         * @return array
         *
         */
        public static function getChildTabs(string $category, $popup_type = '')
        {
            // Ensure tabs are initialized
            if (empty(self::$child_tabs)) {
                self::init();
            }

            // Get base tabs for the category
            $base_tabs = self::$child_tabs[$category] ?? [];

            // For general tabs, filter based on popup type
            if ($category === 'general' && !empty($popup_type)) {
                $filtered_tabs = [];

                foreach ($base_tabs as $tab_key => $tab_label) {
                    // Always include core tabs
                    if (in_array($tab_key, ['display', 'trigger', 'closing', 'limitation', 'position'])) {
                        $filtered_tabs[$tab_key] = $tab_label;
                        continue;
                    }

                    // Conditionally include extension tabs based on popup type
                    if ($tab_key === 'pdf' && $popup_type === 'pdf') {
                        // Check if PDF extension is active and licensed
                        $pdf_license = get_option('pdf_license_active');
                        if ($pdf_license === 'yes') {
                            $filtered_tabs[$tab_key] = $tab_label;
                        }
                    } elseif ($tab_key === 'video' && $popup_type === 'video') {
                        // Check if Video extension is active and licensed
                        $video_license = get_option('video_license_active');
                        if ($video_license === 'yes') {
                            $filtered_tabs[$tab_key] = $tab_label;
                        }
                    } elseif ($tab_key === 'feedback_appearance') {
                        // Show Feedback tab only for Feedback popup type
                        if ($popup_type === 'feedback') {
                            $filtered_tabs[$tab_key] = $tab_label;
                        }
                        continue;
                    } elseif (!in_array($tab_key, ['pdf', 'video','subscription','text-styling','ipb_text'])) {
                        // Include other extension tabs regardless of popup type
                        $filtered_tabs[$tab_key] = $tab_label;

                    } elseif($tab_key === 'subscription' && $popup_type === 'subscription'){

                        $filtered_tabs[$tab_key] = $tab_label;
                        continue;

                    } elseif($tab_key === 'text-styling' && $popup_type === 'text'){

                        $filtered_tabs[$tab_key] = $tab_label;
                        continue;

                    } elseif($tab_key === 'ipb_text' && $popup_type === 'text'){

                        $filtered_tabs[$tab_key] = $tab_label;
                        continue;

                    }
                }


                return $filtered_tabs;
            }

            // For condition tabs, apply the filter to allow extensions to add their tabs
            if ($category === 'condition') {
                $filtered_condition_tabs = apply_filters('instant_popup_builder_condition_tabs', $base_tabs);

                // Ensure Custom Targeting is always available when extension is active
                $custom_targeting_active = class_exists('Instant_Popup_Custom_Targeting') ||
                                         is_plugin_active('instant-popup-custom-targeting/instant-popup-custom-targeting.php') ||
                                         defined('INSTANT_POPUP_CUSTOM_TARGETING_VERSION');

                if ($custom_targeting_active) {
                    // Ensure targeting tab is present and properly ordered
                    if (!isset($filtered_condition_tabs['targeting'])) {
                        $filtered_condition_tabs = array_merge(['targeting' => __('Targeting', 'instant-popup-builder')], $filtered_condition_tabs);
                    }
                }

                return $filtered_condition_tabs;
            }
            // For condition tabs, apply the filter to allow extensions to add their tabs
            if ($category === 'contact_form') {
                $filtered_contact_tabs = apply_filters('instant_popup_builder_contact_form_tabs', $base_tabs);

                // Ensure Custom Targeting is always available when extension is active
               if($popup_type == 'contact_form'){

                return $filtered_contact_tabs;
               }
            }

            // By default (no popup type provided), exclude Feedback-only tab
            if ($category === 'general' && empty($popup_type)) {
                if (isset($base_tabs['feedback_appearance'])) {
                    unset($base_tabs['feedback_appearance']);
                }
            }

            return $base_tabs;
        }

        /**
         * Set All Child tabs
         * @return array
         *
         */
        public static function getAllTabs()
        {
            // Ensure tabs are initialized
            if (empty(self::$child_tabs)) {
                self::init();
            }

            return  self::$child_tabs;
        }

        /**
         * Add new tabs or update existing with new one
         * @param string $group
         * @param array $tabs
         * @return void
         *
         */

        public static function addChildTabs(string $group, array $tabs)
        {

            if (!isset(self::$child_tabs[$group])) {

                self::$child_tabs[$group] = [];
            }

            self::$child_tabs[$group] = array_merge(self::$child_tabs[$group], $tabs);
        }

        /**
         * Add a single tab to a group
         *
         * @param string $group
         * @param string $key
         * @param string $label
         * @return void
         */
        public static function addTab(string $group, string $key, string $label, string $position = 'end')
        {
            self::$child_tabs[$group][$key] = $label;
        }

        /**
         * Get popup setting type
         *
         * @return string
         *
         */
        public function setting_edit_screen($data, $type = '')
        {

            $row = $data;
            if (is_object($row)) {
                $row = [$row];
            }
            if ($row && !empty($row) && isset($row[0])) {
                // Safe JSON decode helper function
                $safe_json_decode = function($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;
                };

                $display = isset($row[0]->display) ? $safe_json_decode($row[0]->display, []) : [];
                $status = isset($row[0]->status) ? $row[0]->status : '';
                $trigger_json = isset($row[0]->ipb_trigger) && $row[0]->ipb_trigger !== '' ? $row[0]->ipb_trigger : (isset($row[0]->triger) ? $row[0]->triger : '');
                $trigger = $safe_json_decode($trigger_json, (object)[]);
                $trigger_option = isset($trigger->trigger_option) ? $trigger->trigger_option : [];
                $trigger_delay =  isset($trigger->trigger_delay) ?  $trigger->trigger_delay : '';
                $trigger_class_click =  isset($trigger->trigger_class_click) ? $trigger->trigger_class_click : '';
                $target_device =  isset($trigger->target_device) ? $trigger->target_device : [];
                $trigger_class_hover =  isset($trigger->trigger_class_hover) ? $trigger->trigger_class_hover : '';
                $selected = isset($display->selected) ? $display->selected : [];
                // Convert to array if it's an object
                if (is_object($selected)) {
                    $selected = json_decode(json_encode($selected), true);
                }
                if (!is_array($selected)) {
                    $selected = [];
                }
                $is_display = isset($display->is_display) ?  $display->is_display : [];
                // Convert 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 = [];
                }
                $exit_sensivity =  isset($trigger->exit_sensivity) ? $trigger->exit_sensivity : '';
                $place = isset($display->place) ?  $display->place : [];
                // Convert to array if it's an object
                if (is_object($place)) {
                    $place = json_decode(json_encode($place), true);
                }
                if (!is_array($place)) {
                    $place = [];
                }
                $closing_json = isset($row[0]->closing) ? $row[0]->closing : '';
                $closing = $safe_json_decode($closing_json, (object)[]);
                $close_option = isset($closing->close_option) ? $closing->close_option : [];
                if ( is_object( $close_option ) ) {
                    $close_option = array_values( (array) $close_option );
                }
                if ( ! is_array( $close_option ) ) {
                    $close_option = [];
                }
                if ( function_exists( 'ipb_sanitize_closing_post_options' ) ) {
                    $close_option = ipb_sanitize_closing_post_options( $close_option );
                }
                $close_position = isset( $closing->close_position ) ? $closing->close_position : '';
                if ( is_array( $close_position ) ) {
                    $close_position = '';
                }
                $close_position = is_string( $close_position ) ? $close_position : '';
                $position_json = isset($row[0]->position) ? $row[0]->position : '';
                $limit_positon = $safe_json_decode($position_json, []);
                $limit_count = isset($limit_positon->limit_count) ? $limit_positon->limit_count : 0;
                $limit_expiry = isset($limit_positon->limit_expiry) ? $limit_positon->limit_expiry : 0;
                $popup_position = isset($limit_positon->popup_position) ?  $limit_positon->popup_position : 0;
                $design_json = isset($row[0]->design) ? $row[0]->design : '';
                $design = $safe_json_decode($design_json, []);
                $advance_json = isset($row[0]->advance) ? $row[0]->advance : '';
                $advance = $safe_json_decode($advance_json, []);
                $is_trigger = get_option('instant_popup_builder_exit');

                // Check if selected action popup is inactive
                $selected_popup_status = '';
                $selected_popup_title = '';
                if (isset($advance->action_popup_id) && $advance->action_popup_id) {
                    global $wpdb;
                    $selected_popup = $wpdb->get_row($wpdb->prepare("SELECT id, title, status FROM {$wpdb->prefix}instant_popup_builder WHERE id=%d", $advance->action_popup_id));
                    if ($selected_popup) {
                        $selected_popup_status = $selected_popup->status;
                        $selected_popup_title = $selected_popup->title;
                    }
                }
            }
            $subscription = "Subscription";
            $subscription_license_active = get_option('subscription_license_active');
            if ( is_plugin_active( 'instant-popup-subscription/instant-popup-subscription.php' ) && $subscription_license_active == 'yes') {
            $subscription = 'Subscription';
            }
            $is_actived = 'active';
            // if ($type == 'video') {

            //     self::addTab('general', 'video', 'Video');
            // }
            ob_start();
?>
            <div class="tabs_content">
                <?php if($type == 'video' || $type == 'pdf' || $type == 'subscription' || $type == 'text' || $type == 'image_gallery' || $type == 'age_verification' || $type == 'recent_orders' || $type == 'contact_form') {

                $is_actived = '';

                ?>
                <div id="ipb_<?php echo esc_attr($type); ?>" class="tab_content active">

                    <div class="ipb-settings-tabs">
                        <div class="ipb-tab-content">
                          <?php
                           if ($type === 'video') {
                                do_action('before_general_tab_content', $advance, $type);
                            } elseif ($type === 'contact_form') {
                                do_action('instant_popup_builder_edit_contact_form_tab', $row);
                            } elseif ($type === 'pdf') {
                                do_action('before_pdf_tab_content', $advance);
                            }elseif($type === 'subscription'){
                               // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter used for display/routing purposes only, value is sanitized
                               // Show subscription tab content when creating or editing subscription popups
                               // We're already inside elseif($type === 'subscription'), so we know type is subscription
                               // No need to check $_GET['type'] again - just show the content
                               ?>
                            <div id="subscription" class="ipb-tab-pane active">
                                <div class="ipb-section">

                                    <div class="ipb-section-content" data-section="display">
                                <div class="subscription_settings_editor">

                                    <?php
                                    // Get all pages for dropdowns
                                    $pages = get_pages();
                                    // Get subscription settings for this popup (fallback to global if none)
                                    $subscription_settings = array();
                                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                                    $current_popup_id = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
                                    if ($current_popup_id) {
                                        global $wpdb;
                                        $table_name = $wpdb->prefix . 'instant_popup_subscription_settings';
                                        $escaped_table_name = esc_sql($table_name);
                                        // Check if table exists and fetch settings
                                        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name))) {
                                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                                            $result = $wpdb->get_row($wpdb->prepare("SELECT settings FROM `{$escaped_table_name}` WHERE popup_id = %d", $current_popup_id));
                                            if ($result && !empty($result->settings)) {
                                                $subscription_settings = maybe_unserialize($result->settings);
                                                
                                            }
                                        }
                                    }
                                    // Only load global settings as fallback for existing popups that don't have their own settings yet
                                    // For new popups ($current_popup_id = 0), keep settings empty to avoid inheriting from other popups
                                    if ($current_popup_id && (empty($subscription_settings) || !is_array($subscription_settings))) {
                                        $subscription_settings = get_option('instant_popup_subscription_settings', array());
                                    }
                                    ?>

                                    <!-- Privacy Policy & Terms & Conditions (combined section) -->
                                    <div class="subscription_setting_group">
                                        <h3><i class="fa fa-shield-alt"></i> Privacy Policy & Terms & Conditions</h3>

                                        <div class="subscription_setting_field">
                                            <label class="subscription_setting_label">
                                                <input type="checkbox" name="subscription_show_privacy" id="subscription_show_privacy" value="1" <?php echo isset($subscription_settings['show_privacy']) && $subscription_settings['show_privacy'] == '1' ? 'checked' : ''; ?>>
                                                <span class="checkmark"></span>
                                                Show Privacy Policy checkbox
                                            </label>
                                            <p class="field_description">Display a Privacy Policy acceptance checkbox in subscription forms</p>
                                        </div>

                                        <div class="subscription_setting_field privacy_options" style="<?php echo esc_attr(!isset($subscription_settings['show_privacy']) || $subscription_settings['show_privacy'] != '1' ? 'display: none;' : ''); ?>">
                                            <div class="privacy_link_type">
                                                <label>
                                                    <input type="radio" name="privacy_link_type" value="url" <?php echo !isset($subscription_settings['privacy_link_type']) || $subscription_settings['privacy_link_type'] == 'url' ? 'checked' : ''; ?>>
                                                    Use Custom URL
                                                </label>
                                                <label>
                                                    <input type="radio" name="privacy_link_type" value="page" <?php echo isset($subscription_settings['privacy_link_type']) && $subscription_settings['privacy_link_type'] == 'page' ? 'checked' : ''; ?>>
                                                    Select from Pages
                                                </label>
                                            </div>

                                            <div class="privacy_url_field" style="<?php echo esc_attr(isset($subscription_settings['privacy_link_type']) && $subscription_settings['privacy_link_type'] == 'page' ? 'display: none;' : ''); ?>">
                                                <label for="privacy_policy_url">Privacy Policy URL:</label>
                                                <input type="url" name="privacy_policy_url" id="privacy_policy_url"
                                                       value="<?php echo isset($subscription_settings['privacy_policy_url']) ? esc_attr($subscription_settings['privacy_policy_url']) : ''; ?>"
                                                       placeholder="https://example.com/privacy-policy">
                                            </div>

                                            <div class="privacy_page_field" style="<?php echo esc_attr(!isset($subscription_settings['privacy_link_type']) || $subscription_settings['privacy_link_type'] != 'page' ? 'display: none;' : ''); ?>">
                                                <label for="privacy_policy_page">Privacy Policy Page:</label>
                                                <select name="privacy_policy_page" id="privacy_policy_page">
                                                    <option value="">Select a page...</option>
                                                    <?php foreach ($pages as $page): ?>
                                                        <option value="<?php echo esc_html($page->ID); ?>"
                                                                <?php echo isset($subscription_settings['privacy_policy_page']) && $subscription_settings['privacy_policy_page'] == $page->ID ? 'selected' : ''; ?>>
                                                            <?php echo esc_html($page->post_title ?? ''); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="privacy_text_field">
                                                <label for="agreement_prefix_text">Agreement Intro Text:</label>
                                                <input type="text" name="agreement_prefix_text" id="agreement_prefix_text"
                                                       value="<?php echo isset($subscription_settings['agreement_prefix_text']) ? esc_attr($subscription_settings['agreement_prefix_text']) : 'I agree to the'; ?>"
                                                       placeholder="I agree to the">
                                            </div>

                                            <div class="privacy_text_field">
                                                <label for="privacy_policy_label">Privacy Policy Label:</label>
                                                <input type="text" name="privacy_policy_label" id="privacy_policy_label"
                                                       value="<?php echo isset($subscription_settings['privacy_policy_label']) ? esc_attr($subscription_settings['privacy_policy_label']) : 'Privacy Policy'; ?>"
                                                       placeholder="Privacy Policy">
                                            </div>
                                        </div>

                                        <div class="subscription_setting_field" style="margin-top: 1.25em;">
                                            <label class="subscription_setting_label">
                                                <input type="checkbox" name="subscription_show_terms" id="subscription_show_terms" value="1" <?php echo isset($subscription_settings['show_terms']) && $subscription_settings['show_terms'] == '1' ? 'checked' : ''; ?>>
                                                <span class="checkmark"></span>
                                                Show Terms & Conditions checkbox
                                            </label>
                                            <p class="field_description">Display a Terms & Conditions acceptance checkbox in subscription forms</p>
                                        </div>

                                        <div class="subscription_setting_field terms_options" style="<?php echo esc_attr(!isset($subscription_settings['show_terms']) || $subscription_settings['show_terms'] != '1' ? 'display: none;' : ''); ?>">
                                            <div class="terms_link_type">
                                                <label>
                                                    <input type="radio" name="terms_link_type" value="url" <?php echo !isset($subscription_settings['terms_link_type']) || $subscription_settings['terms_link_type'] == 'url' ? 'checked' : ''; ?>>
                                                    Use Custom URL
                                                </label>
                                                <label>
                                                    <input type="radio" name="terms_link_type" value="page" <?php echo isset($subscription_settings['terms_link_type']) && $subscription_settings['terms_link_type'] == 'page' ? 'checked' : ''; ?>>
                                                    Select from Pages
                                                </label>
                                            </div>

                                            <div class="terms_url_field" style="<?php echo esc_attr(isset($subscription_settings['terms_link_type']) && $subscription_settings['terms_link_type'] == 'page' ? 'display: none;' : ''); ?>">
                                                <label for="terms_conditions_url">Terms & Conditions URL:</label>
                                                <input type="url" name="terms_conditions_url" id="terms_conditions_url"
                                                       value="<?php echo isset($subscription_settings['terms_conditions_url']) ? esc_attr($subscription_settings['terms_conditions_url']) : ''; ?>"
                                                       placeholder="https://example.com/terms-conditions">
                                            </div>

                                            <div class="terms_page_field" style="<?php echo esc_attr(!isset($subscription_settings['terms_link_type']) || $subscription_settings['terms_link_type'] != 'page' ? 'display: none;' : ''); ?>">
                                                <label for="terms_conditions_page">Terms & Conditions Page:</label>
                                                <select name="terms_conditions_page" id="terms_conditions_page">
                                                    <option value="">Select a page...</option>
                                                    <?php foreach ($pages as $page): ?>
                                                        <option value="<?php echo esc_html($page->ID); ?>"
                                                                <?php echo isset($subscription_settings['terms_conditions_page']) && $subscription_settings['terms_conditions_page'] == $page->ID ? 'selected' : ''; ?>>
                                                            <?php echo esc_html($page->post_title ?? ''); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="terms_text_field">
                                                <label for="terms_conditions_label">Terms and Conditions Label:</label>
                                                <input type="text" name="terms_conditions_label" id="terms_conditions_label"
                                                       value="<?php echo isset($subscription_settings['terms_conditions_label']) ? esc_attr($subscription_settings['terms_conditions_label']) : 'Terms and conditions'; ?>"
                                                       placeholder="Terms and conditions">
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Subscription Behavior Settings -->
                                    <div class="subscription_setting_group">
                                        <h3><i class="fa fa-cog"></i> Subscription Behavior</h3>

                                        <div class="subscription_setting_field">
                                            <label class="subscription_setting_label">
                                                <input type="checkbox" name="subscription_prevent_reshow" id="subscription_prevent_reshow" value="1" <?php echo isset($subscription_settings['prevent_reshow']) && $subscription_settings['prevent_reshow'] == '1' ? 'checked' : ''; ?>>
                                                <span class="checkmark"></span>
                                                Prevent popup from showing again if user is subscribed
                                            </label>
                                            <p class="field_description">Once a user subscribes, they won't see the popup again on future visits</p>
                                        </div>

                                        <div class="subscription_setting_field">
                                            <label class="subscription_setting_label">
                                                <input type="checkbox" name="subscription_email_verification" id="subscription_email_verification" value="1" <?php echo isset($subscription_settings['email_verification']) && $subscription_settings['email_verification'] == '1' ? 'checked' : ''; ?>>
                                                <span class="checkmark"></span>
                                                Enable Email Verification
                                            </label>
                                            <p class="field_description">Require users to verify their email address before completing subscription</p>
                                        </div>
                                    </div>

                                    <!-- Additional Options -->
                                    <div class="subscription_setting_group">
                                        <h3><i class="fa fa-envelope"></i> Email Settings</h3>

                                        <div class="subscription_setting_field">
                                            <label for="subscription_success_message">Success Message:</label>
                                            <textarea name="subscription_success_message" id="subscription_success_message" rows="3"
                                                      placeholder="Thank you for subscribing! Check your email for confirmation."><?php echo isset($subscription_settings['success_message']) ? esc_textarea($subscription_settings['success_message']) : 'Thank you for subscribing!'; ?></textarea>
                                            <p class="field_description">Message shown after successful subscription</p>
                                        </div>

                                        <div class="subscription_setting_field">
                                            <label for="subscription_error_message">Error Message:</label>
                                            <textarea name="subscription_error_message" id="subscription_error_message" rows="3"
                                                      placeholder="Something went wrong. Please try again."><?php echo isset($subscription_settings['error_message']) ? esc_textarea($subscription_settings['error_message']) : 'Something went wrong. Please try again.'; ?></textarea>
                                            <p class="field_description">Message shown if subscription fails</p>
                                        </div>
                                    </div>

                                    <?php
                                    /**
                                     * Hook: Allow extensions to add settings after Email Settings
                                     * 
                                     * @param int $current_popup_id Current popup ID (0 for new popups)
                                     * @param array $subscription_settings Current subscription settings
                                     */
                                    do_action('ipb_subscription_settings_after_email', $current_popup_id, $subscription_settings);

                                    // Check if hook-based integration is available
                                    // If hook-based integration exists, skip hardcoded version to avoid duplicates
                                    $hook_based_available = class_exists('Instant_Popup_Subscribe_To_Download_Hook_Integration');
                                    
                                    // Only show hardcoded STD section if hook-based version is not available
                                    if (!$hook_based_available) {
                                    ?>
                                    <!-- Subscribe to Download Section (Legacy - will be removed in Phase 2) -->
                                    <?php
                                    // Check if Subscribe to Download extension is installed and license is active
                                    // Use multiple methods to check plugin activation for reliability
                                    if (!function_exists('is_plugin_active')) {
                                        require_once ABSPATH . 'wp-admin/includes/plugin.php';
                                    }
                                    
                                    $std_plugin_active = false;
                                    // Method 1: Check if plugin is active via WordPress function
                                    if (function_exists('is_plugin_active')) {
                                        $std_plugin_active = is_plugin_active('instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php');
                                    }
                                    // Method 2: Check if class exists (fallback)
                                    if (!$std_plugin_active && class_exists('Instant_Popup_Subscribe_To_Download_Admin')) {
                                        $std_plugin_active = true;
                                    }
                                    // Method 3: Check if main plugin file exists and is loaded
                                    if (!$std_plugin_active) {
                                        $plugin_path = WP_PLUGIN_DIR . '/instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php';
                                        if (file_exists($plugin_path)) {
                                            // Check if it's in active plugins list
                                            $active_plugins = get_option('active_plugins', array());
                                            $plugin_file = 'instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php';
                                            $std_plugin_active = in_array($plugin_file, $active_plugins, true);
                                        }
                                    }
                                    
                                    // Check license status - check both options for reliability
                                    $std_license_active = get_option('subscribe_to_download_license_active') === 'yes';
                                    // Also check the enabled option as fallback
                                    if (!$std_license_active) {
                                        $std_license_active = get_option('ipb_subscribe_to_download_enabled') === 'yes';
                                    }
                                    $std_enabled = $std_plugin_active && $std_license_active;
                                    
                                    if ($std_enabled) {
                                        // Ensure media library is enqueued
                                        if (function_exists('wp_enqueue_media')) {
                                            wp_enqueue_media();
                                        }
                                        // Get download settings from subscription_settings or download_settings table
                                        // Initialize with defaults for new popups
                                        $std_file_id = 0;
                                        $std_file_attachment_id = 0;
                                        $std_delivery_method = 'button';
                                        $std_thank_you_message = 'Thank you for Subscribing !';
                                        $std_download_button_text = 'Click to download File';
                                        $std_file_encryption = 1;
                                        
                                        // Load from subscription_settings if available (for existing popups or global defaults)
                                        if (!empty($subscription_settings)) {
                                            $std_file_id = isset($subscription_settings['std_file_id']) ? intval($subscription_settings['std_file_id']) : 0;
                                            $std_file_attachment_id = isset($subscription_settings['std_file_attachment_id']) ? intval($subscription_settings['std_file_attachment_id']) : 0;
                                            if (isset($subscription_settings['std_delivery_method'])) {
                                                $std_delivery_method = sanitize_text_field($subscription_settings['std_delivery_method']);
                                            }
                                            if (isset($subscription_settings['std_thank_you_message'])) {
                                                $std_thank_you_message = $subscription_settings['std_thank_you_message'];
                                            }
                                            if (isset($subscription_settings['std_download_button_text'])) {
                                                $std_download_button_text = $subscription_settings['std_download_button_text'];
                                            }
                                            if (isset($subscription_settings['std_file_encryption'])) {
                                                $std_file_encryption = intval($subscription_settings['std_file_encryption']);
                                            }
                                        }
                                        
                                        // Use file_attachment_id if file_id is not set
                                        if (!$std_file_id && $std_file_attachment_id) {
                                            $std_file_id = $std_file_attachment_id;
                                        }
                                        
                                        // Get file info if file_id exists
                                        $std_file_name = '';
                                        $std_file_url = '';
                                        if ($std_file_id) {
                                            global $wpdb;
                                            $file_table = $wpdb->prefix . 'instant_popup_download_files';
                                            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $file_table)) == $file_table) {
                                                $file = $wpdb->get_row($wpdb->prepare("SELECT file_name, file_path, storage_type, external_url FROM $file_table WHERE id = %d", $std_file_id));
                                                if ($file) {
                                                    $std_file_name = $file->file_name;
                                                    if ($file->storage_type === 'external') {
                                                        $std_file_url = $file->external_url;
                                                    } else {
                                                        $std_file_url = wp_get_attachment_url($std_file_id); // Try media library first
                                                        if (!$std_file_url && file_exists($file->file_path)) {
                                                            $upload_dir = wp_upload_dir();
                                                            $std_file_url = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $file->file_path);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        
                                        // Also check download_settings table as fallback (only for existing popups)
                                        if (!$std_file_id && $current_popup_id > 0) {
                                            global $wpdb;
                                            $download_settings_table = $wpdb->prefix . 'instant_popup_download_settings';
                                            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $download_settings_table)) == $download_settings_table) {
                                                $download_settings_row = $wpdb->get_row($wpdb->prepare("SELECT settings FROM $download_settings_table WHERE popup_id = %d", $current_popup_id));
                                                if ($download_settings_row && !empty($download_settings_row->settings)) {
                                                    $download_settings = json_decode($download_settings_row->settings, true);
                                                    if (isset($download_settings['file_id'])) {
                                                        $std_file_id = intval($download_settings['file_id']);
                                                        // Map old delivery methods to new format
                                                        $old_delivery_method = isset($download_settings['delivery_method']) ? $download_settings['delivery_method'] : 'button';
                                                        // Convert email_link and email_attachment to 'email' for UI compatibility
                                                        if ($old_delivery_method === 'email_link' || $old_delivery_method === 'email_attachment') {
                                                            $std_delivery_method = 'email';
                                                        } else {
                                                            $std_delivery_method = $old_delivery_method;
                                                        }
                                                        $std_thank_you_message = isset($download_settings['thank_you_message']) ? $download_settings['thank_you_message'] : 'Thank you for Subscribing !';
                                                        $std_file_encryption = isset($download_settings['ip_restricted']) ? intval($download_settings['ip_restricted']) : 1;
                                                    }
                                                }
                                            }
                                        }
                                    ?>
                                    <div class="subscription_setting_group" id="subscribe-to-download-section">
                                        <h3><i class="fa fa-download"></i> Subscribe to Download</h3>

                                        <!-- File Upload Section -->
                                        <div class="subscription_setting_field">
                                            <label>Upload Subscribe to Download File:</label>
                                            <div class="std-file-upload-wrapper" style="margin-bottom: 10px;">
                                                <button type="button" class="button std-select-media-btn" id="std_select_media_btn">
                                                    <span class="dashicons dashicons-upload" style="vertical-align: middle;"></span> 
                                                    <span class="std-file-name-display">
                                                        <?php echo $std_file_name ? esc_html($std_file_name) : 'Select File from Media Library'; ?>
                                                    </span>
                                                </button>
                                                <input type="hidden" id="std_file_attachment_id" name="std_file_attachment_id" value="<?php echo esc_attr($std_file_attachment_id ? $std_file_attachment_id : $std_file_id); ?>">
                                                <input type="hidden" id="std_file_url" name="std_file_url" value="<?php echo esc_attr($std_file_url); ?>">
                                                <?php if ($std_file_name): ?>
                                                <button type="button" class="button std-remove-file-btn" id="std_remove_file_btn" style="margin-left: 10px;">
                                                    <span class="dashicons dashicons-dismiss"></span> Remove
                                                </button>
                                                <?php else: ?>
                                                <button type="button" class="button std-remove-file-btn" id="std_remove_file_btn" style="margin-left: 10px; display: none;">
                                                    <span class="dashicons dashicons-dismiss"></span> Remove
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                            <p class="field_description">Select a file from Media Library to be downloaded after subscription</p>
                                        </div>

                                        <!-- File Delivery Method -->
                                        <div class="subscription_setting_field">
                                            <label>File Delivery Method:</label>
                                            <div class="std-delivery-methods">
                                                <label class="subscription_setting_label">
                                                    <input type="radio" name="std_delivery_method" value="auto_download" <?php echo $std_delivery_method === 'auto_download' ? 'checked' : ''; ?>>
                                                    <span class="checkmark"></span>
                                                    Auto-download after subscription (as soon as user click on the subscribe button)
                                                </label>
                                                <label class="subscription_setting_label">
                                                    <input type="radio" name="std_delivery_method" value="email" <?php echo $std_delivery_method === 'email' ? 'checked' : ''; ?>>
                                                    <span class="checkmark"></span>
                                                    Send by Email (Send via email)
                                                </label>
                                                <label class="subscription_setting_label">
                                                    <input type="radio" name="std_delivery_method" value="button" <?php echo ($std_delivery_method === 'button' || empty($std_delivery_method)) ? 'checked' : ''; ?>>
                                                    <span class="checkmark"></span>
                                                    Show Download Button & Thank you Message
                                                </label>
                                            </div>
                                        </div>

                                        <!-- Thank You Message & Download Button Preview (shown when "button" method selected) -->
                                        <div class="subscription_setting_field std-button-preview-section" style="<?php echo ($std_delivery_method === 'button' || empty($std_delivery_method)) ? '' : 'display: none;'; ?>">
                                            <label style="display: block; margin-bottom: 10px; font-weight: 600;">Configure Thank You Message & Download Button:</label>
                                            <div class="std-preview-box" style="background: #fff; border: 1px solid #ddd; border-radius: 4px; padding: 20px; margin-top: 10px; position: relative;">
                                                    
                                                    <div class="std-thank-you-message-wrapper" style="margin-bottom: 15px;">
                                                        <label for="std_thank_you_message" style="display: block; margin-bottom: 5px; font-weight: 600;">Thank you message:</label>
                                                        <input type="text" id="std_thank_you_message" name="std_thank_you_message" 
                                                               value="<?php echo esc_attr($std_thank_you_message); ?>" 
                                                               placeholder="Thank you for Subscribing !"
                                                               style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                                    </div>
                                                    
                                                    <div class="std-download-button-wrapper">
                                                        <label for="std_download_button_text" style="display: block; margin-bottom: 5px; font-weight: 600;">Download button text:</label>
                                                        <input type="text" id="std_download_button_text" name="std_download_button_text" 
                                                               value="<?php echo esc_attr($std_download_button_text); ?>" 
                                                               placeholder="Click to download File"
                                                               style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                                                    </div>
                                                    
                                                    <div class="std-preview-display" style="margin-top: 20px; padding: 20px; background: #f9f9f9; border-radius: 4px; text-align: center;">
                                                        <h3 style="margin: 0 0 15px 0; font-size: 18px; font-weight: 600;" id="std_preview_thank_you"><?php echo esc_html($std_thank_you_message); ?></h3>
                                                        <button type="button" class="button button-primary" id="std_preview_download_btn" style="padding: 10px 20px; font-size: 14px; cursor: default;">
                                                            <span class="dashicons dashicons-download" style="vertical-align: middle;"></span>
                                                            <span id="std_preview_button_text"><?php echo esc_html($std_download_button_text); ?></span>
                                                        </button>
                                                    </div>
                                            </div>
                                        </div>

                                        <!-- File Encryption -->
                                        <div class="subscription_setting_field">
                                            <label class="subscription_setting_label">
                                                <input type="checkbox" name="std_file_encryption" id="std_file_encryption" value="1" <?php echo $std_file_encryption ? 'checked' : ''; ?>>
                                                <span class="checkmark"></span>
                                                Enable File Encryption
                                            </label>
                                            <p class="field_description">File will be encrypted and accessed via a secure, expiring download link.</p>
                                        </div>
                                    </div>
                                    <?php } ?>
                                    <?php } // End legacy STD section check ?>

                                    <?php
                                    /**
                                     * Hook: Allow extensions to add settings after Subscribe to Download section
                                     * 
                                     * @param int $current_popup_id Current popup ID (0 for new popups)
                                     * @param array $subscription_settings Current subscription settings
                                     */
                                    do_action('ipb_subscription_settings_after_extensions', $current_popup_id, $subscription_settings);
                                    ?>

                                </div>
                                </div>
                                </div>
                            </div>
                            <?php
                            }elseif($type === 'text'){
                                ?>
                            <div id="text-styling" class="ipb-tab-pane active">
                                <?php class_instant_setting::design_setting('text-styling'); ?>
                            </div>
                            <?php
                            }else if($type === 'image_gallery'){

                            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                            if(isset($_GET['type']) && $_GET['type'] == 'image_gallery'){ ?>
                            <div id="image_gallery" class="ipb-tab-pane active">

                                <div class="ipb-settings-tabs">
                                    <?php class_instant_setting::general_setting('image_gallery'); ?>
                                </div>

                            </div>
                            <?php 
                            }
                            }else{
                            do_action('before_general_tab_content', $advance);
                            }
                             ?>
                        </div>
                    </div>
                </div>
                <?php } ?>
                <div id="general" class="tab_content <?php echo ($type === 'video' || $type === 'contact_form') ? '' : esc_attr($is_actived); ?>">
                    <div class="ipb-settings-tabs">
                        <!-- <ul class="v_tabs_list">
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- renderChildHtml() outputs safe, sanitized HTML
                            //echo self::renderChildHtml($this->getChildTabs('general', $type), $type); ?>
                        </ul> -->
                        <div class="ipb-tab-content">

                            <!-- action for adding new tab -->

                            <div id="display" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-display-rules">
                                    <div class="ipb-section-header">
                                        <h3>Display Rules</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                <div class="display_wrapper">
                                    <div class="display_inner">
                                        <div class="rules">
                                            <h2>Display</h2>
                                            <div class="selection">
                                                <select name="page" id="page">
                                                    <option value="everywhere" <?php echo isset($selected[0]) && $selected[0] == 'everywhere' ? 'selected' : ''; ?>>Everywhere</option>
                                                    <option value="post" <?php echo isset($selected[0]) && ($selected[0] == 'selected-post' || $selected[0] == 'all-posts' || $selected[0] == 'post-type'  || $selected[0] == 'post-category') ? 'selected' : ''; ?>>Post</option>
                                                    <option value="page" <?php echo isset($selected[0]) && ($selected[0] == 'selected-page' || $selected[0] == 'all-pages') ? 'selected' : ''; ?>>Page</option>
                                                    <option value="tags" <?php echo isset($selected[0]) && ($selected[0] == 'selected-tags' || $selected[0] == 'all-tags') ? 'selected' : ''; ?>>Tags</option>
                                                    <?php
                                                    $woocommerce_option =  get_option('instant_popup_woocommerce');
                                                    if ($woocommerce_option == 'yes'){ ?>
                                                    <option value="woocommerce" <?php echo isset($selected[0]) && ($selected[0] == 'all_products' || $selected[0] == 'archive_products' || $selected[0] == 'selected_products' || $selected[0] == 'product_categories') ? 'selected' : ''; ?>>Woocommerce </option>
                                                    <?php }else{ ?>
                                                    <option value="woo_disable" style="color: gray;" disabled>Woocommerce 🔒</option>
                                                    <?php } ?>
                                                </select>
                                            </div>
                                            <div class="plus">
                                                <i class="fa-solid fa-circle-plus"></i>
                                            </div>
                                        </div>
                                        <p class="ipb-display-helper">Select where this popup should appear. Add multiple rules with (+).</p>
                                        <div class="form_fields">
                                            <?php
                                            // var_dump($is_display);
                                            if (is_countable($is_display)) :
                                                for ($i = 0; $i < count($is_display); $i++) :

                                                    $s_place = [];
                                                    if (isset($selected[$i]) && isset($place[$i]) && $selected[$i] == 'selected-post') {

                                                        $posts = get_posts([
                                                            'post_type' => 'post',
                                                            'post_status' => 'publish',
                                                            'post__in' => $place[$i],
                                                            'numberposts' => -1
                                                        ]);
                                            ?>
                                                        <div class="input_fields_wrap">
                                                            <div class="fields">
                                                                <select name="selected_option[]" class="selected_option">
                                                                    <option value="all-posts" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-posts' ? 'selected' : ''; ?>>All Posts</option>
                                                                    <option value="selected-post" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-post' ? 'selected' : ''; ?>> Selected Posts</option>
                                                                    <option value="post-type" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-type' ? 'selected' : ''; ?>>Post Type</option>
                                                                    <option value="post-category" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-category' ? 'selected' : ''; ?>>Post Category</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields">
                                                                <label for="">Is or is not</label>
                                                                <select name="is_display[]" class="is_display">
                                                                    <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                    <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields"><label for="">Select Post</label>
                                                                <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                    <?php if ($posts):
                                                                        foreach ($posts as $post):
                                                                    ?>
                                                                            <option selected value="<?php echo esc_attr($post->ID); ?>"><?php echo esc_html($post->post_title ?? ''); ?></option>
                                                                    <?php endforeach;
                                                                    endif; ?>
                                                                </select>
                                                            </div>
                                                            <i class="fa-solid fa-trash"></i>
                                                        </div>
                                                    <?php
                                                    }
                                                    if (isset($selected[$i]) &&  $selected[$i] == 'everywhere') {

                                                        $s_place['everywhere'] = 'Everywhere';

                                                    ?>
                                                        <input type="hidden" name="selected_option[]" value="everywhere">
                                                        <input type="hidden" name="is_display[]" value="<?php echo isset($is_display[$i]) ? esc_attr($is_display[$i]) : 'yes'; ?>">
                                                        <input type="hidden" name="spec_val[<?php echo esc_attr($i); ?>][]" value="<?php echo isset(array_keys($s_place)[0]) ? esc_attr(array_keys($s_place)[0]) : 'everywhere'; ?>">

                                                    <?php
                                                    }
                                                    if (isset($selected[$i]) && $selected[$i] == 'all-posts') {

                                                        $s_place['all-posts'] = 'All Posts';

                                                    ?>
                                                        <div class="input_fields_wrap">
                                                            <div class="fields">
                                                                <select name="selected_option[]" class="selected_option">
                                                                    <option value="all-posts" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-posts' ? 'selected' : ''; ?>>All Posts</option>
                                                                    <option value="selected-post" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-post' ? 'selected' : ''; ?>> Selected Posts</option>
                                                                    <option value="post-type" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-type' ? 'selected' : ''; ?>>Post Type</option>
                                                                    <option value="post-category" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-category' ? 'selected' : ''; ?>>Post Category</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields">
                                                                <label for="">Is or is not</label>
                                                                <select name="is_display[]" class="is_display">
                                                                    <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                    <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields">
                                                                <label for="">Select </label>
                                                                <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                    <option selected value="<?php echo isset(array_keys($s_place)[0]) ? esc_html(array_keys($s_place)[0]) :  ""; ?>"><?php echo  isset(array_values($s_place)[0]) ?  esc_html(array_values($s_place)[0]) : ''; ?></option>
                                                                </select>
                                                            </div>
                                                            <i class="fa-solid fa-trash"></i>
                                                        </div>
                                                    <?php
                                                    }
                                                    if (isset($selected[$i]) && $selected[$i] == 'post-type') {

                                                        $s_place = isset($place[$i]) ? $place[$i] : [];
                                                    ?>
                                                        <div class="input_fields_wrap">
                                                            <div class="fields">
                                                                <select name="selected_option[]" class="selected_option">
                                                                    <option value="all-posts" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-posts' ? 'selected' : ''; ?>>All Posts</option>
                                                                    <option value="selected-post" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-post' ? 'selected' : ''; ?>> Selected Posts</option>
                                                                    <option value="post-type" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-type' ? 'selected' : ''; ?>>Post Type</option>
                                                                    <option value="post-category" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-category' ? 'selected' : ''; ?>>Post Category</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields">
                                                                <label for="">Is or is not</label>
                                                                <select name="is_display[]" class="is_display">
                                                                    <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                    <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields"><label for="">Select </label>
                                                                <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">

                                                                    <?php if ($s_place):
                                                                        foreach ($s_place as $s_plac):
                                                                    ?>
                                                                            <option selected value="<?php echo esc_attr($s_plac ?? ''); ?>"><?php echo  esc_html(ucfirst(str_replace("-", ' ', $s_plac ?? ''))); ?></option>
                                                                    <?php endforeach;
                                                                    endif; ?>

                                                                </select>
                                                            </div>
                                                            <i class="fa-solid fa-trash"></i>
                                                        </div>
                                                    <?php

                                                    }
                                                    if (isset($selected[$i]) && $selected[$i] == 'post-category') {

                                                        if (isset($place[$i]) && is_array($place[$i]) && is_countable($place[$i])) {
                                                            foreach ($place[$i] as $pal) {

                                                                $term = get_term_by('term_id', $pal, 'category');
                                                                $s_place[$term->term_id] = $term->name;
                                                            }
                                                        }

                                                    ?>
                                                        <div class="input_fields_wrap">
                                                            <div class="fields">
                                                                <select name="selected_option[]" class="selected_option">
                                                                    <option value="all-posts" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-posts' ? 'selected' : ''; ?>>All Posts</option>
                                                                    <option value="selected-post" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-post' ? 'selected' : ''; ?>> Selected Posts</option>
                                                                    <option value="post-type" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-type' ? 'selected' : ''; ?>>Post Type</option>
                                                                    <option value="post-category" <?php echo  isset($selected[$i]) && $selected[$i] == 'post-category' ? 'selected' : ''; ?>>Post Category</option>

                                                                </select>
                                                            </div>
                                                            <div class="fields"><label for="">Is or is not</label>
                                                                <select name="is_display[]" class="is_display">
                                                                    <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                    <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                </select>
                                                            </div>
                                                            <div class="fields"><label for="">Select</label>
                                                                <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">

                                                                    <?php if (isset($s_place) && $s_place):
                                                                        foreach ($s_place as $index => $plac):
                                                                    ?>
                                                                            <option selected value="<?php echo esc_attr($index ?? ''); ?>"><?php echo  esc_html($plac ?? ''); ?></option>
                                                                    <?php endforeach;
                                                                    endif; ?>
                                                                </select>
                                                            </div>
                                                            <i class="fa-solid fa-trash"></i>
                                                        </div>
                                                    <?php
                                                    }
                                                    if (isset($selected[$i]) && $selected[$i] == 'all-pages') {

                                                        $s_place['all-pages'] = "All Pages";

                                                    ?>

                                                        <?php if (isset(array_keys($s_place)[0])): ?>
                                                            <div class="input_fields_wrap">
                                                                <div class="fields"><select name="selected_option[]" class="selected_option">

                                                                        <option value="all-pages" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-pages' ? 'selected' : ''; ?>>All Pages</option>
                                                                        <option value="selected-page" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-page' ? 'selected' : ''; ?>>Selected Page</option>

                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Is or is not</label>
                                                                    <select name="is_display[]" class="is_display">
                                                                        <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                        <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Select</label>
                                                                    <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                        <option selected value="<?php echo isset(array_keys($s_place)[0]) ? esc_html(array_keys($s_place)[0]) :  ""; ?>"><?php echo  isset(array_values($s_place)[0]) ?  esc_html(array_values($s_place)[0]) : ''; ?></option>
                                                                    </select>
                                                                </div>
                                                                <i class="fa-solid fa-trash"></i>
                                                            </div>
                                                        <?php endif; ?>

                                                        <?php

                                                    }

                                                    if (isset($selected[$i]) && $selected[$i] == 'selected-page') {
                                                        // var_dump($place);
                                                        if (isset($place[$i]) && is_array($place[$i]) && count($place[$i]) > 0) {
                                                            $pages = get_posts([

                                                                'post_name__in' => $place[$i],
                                                                'post_type' => 'page',
                                                                'post_status' => 'publish',
                                                                'numberposts' => -1
                                                            ]);
                                                        }
                                                        if (isset($pages) &&  $pages): ?>
                                                            <div class="input_fields_wrap">
                                                                <div class="fields"><select name="selected_option[]" class="selected_option">

                                                                        <option value="all-pages" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-pages' ? 'selected' : ''; ?>>All Pages</option>
                                                                        <option value="selected-page" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-page' ? 'selected' : ''; ?>>Selected Page</option>

                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Is or is not</label>
                                                                    <select name="is_display[]" class="is_display">
                                                                        <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                        <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Select</label>
                                                                    <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                        <?php if (isset($pages) && is_countable($pages)):
                                                                            foreach ($pages as $page):
                                                                        ?>
                                                                                <option selected value="<?php echo esc_attr($page->post_name ?? ''); ?>"><?php echo  esc_html($page->post_title ?? ''); ?></option>
                                                                        <?php endforeach;
                                                                        endif; ?>
                                                                    </select>
                                                                </div>
                                                                <i class="fa-solid fa-trash"></i>
                                                            </div>
                                                        <?php endif; ?>

                                                    <?php

                                                    }

                                                    if (isset($selected[$i]) && $selected[$i] == 'selected-tags') {

                                                        // var_dump($place);
                                                        if (is_array($place[$i]) && count($place[$i]) > 0) {
                                                            foreach ($place[$i] as $palce) {

                                                                $term = get_term_by('term_id', $palce, 'post_tag');
                                                                if ($term) {

                                                                    $s_place[$term->term_id] = $term->name;
                                                                } else {
                                                                    $s_place['no-tags'] = "No Tag Found";
                                                                }
                                                            }
                                                        }
                                                    ?>

                                                        <?php if ($s_place): ?>
                                                            <div class="input_fields_wrap">
                                                                <div class="fields"><select name="selected_option[]" class="selected_option">
                                                                        <option value="selected-tags" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-tags' ? 'selected' : ''; ?>>Selected Tags</option>
                                                                        <option value="all-tags" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-tags' ? 'selected' : ''; ?>>All Tags</option>

                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Is or is not</label>
                                                                    <select name="is_display[]" class="is_display">
                                                                        <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                        <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Select</label>
                                                                    <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                        <?php if (isset($s_place) && $s_place):
                                                                            foreach ($s_place as $index => $tag):
                                                                        ?>
                                                                                <option selected value="<?php echo esc_attr($index ?? ''); ?>"><?php echo  esc_html($tag ?? ''); ?></option>
                                                                        <?php endforeach;
                                                                        endif; ?>
                                                                    </select>

                                                                </div>
                                                                <i class="fa-solid fa-trash"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php
                                                    }
                                                    if (isset($selected[$i]) && $selected[$i] == 'all-tags') {

                                                        $s_place['all-tags'] = 'All Tags';
                                                    ?>

                                                        <?php if (isset(array_keys($s_place)[0])): ?>
                                                            <div class="input_fields_wrap">
                                                                <div class="fields"><select name="selected_option[]" class="selected_option">
                                                                        <option value="selected-tags" <?php echo  isset($selected[$i]) && $selected[$i] == 'selected-tags' ? 'selected' : ''; ?>>Selected Tags</option>
                                                                        <option value="all-tags" <?php echo  isset($selected[$i]) && $selected[$i] == 'all-tags' ? 'selected' : ''; ?>>All Tags</option>

                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Is or is not</label>
                                                                    <select name="is_display[]" class="is_display">
                                                                        <option value="yes" <?php echo  isset($is_display[$i]) && $is_display[$i] == 'yes' ? 'selected' : ''; ?>>Is</option>
                                                                        <option value="no" <?php echo  isset($is_display[$i]) &&  $is_display[$i] == 'no' ? 'selected' : ''; ?>>Is not</option>
                                                                    </select>
                                                                </div>
                                                                <div class="fields"><label for="">Select</label>
                                                                    <select name="spec_val[<?php echo esc_attr($i); ?>][]" class="spec_val" multiple="multiple">
                                                                        <option selected value="<?php echo isset(array_keys($s_place)[0]) ? esc_html(array_keys($s_place)[0]) :  ""; ?>"><?php echo  isset(array_values($s_place)[0]) ?  esc_html(array_values($s_place)[0]) : ''; ?></option>
                                                                    </select>
                                                                </div>
                                                                <i class="fa-solid fa-trash"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                    <?php
                                                    }

                                                    ?>
                                            <?php endfor;
                                            endif ?>
                                        </div>
                                        <div id="display_woocommerce">
                                            <?php
                                            $woocommerce_option =  get_option('instant_popup_woocommerce');

                                            if ($woocommerce_option == 'yes'){
                                                if ( function_exists( 'ipb_popup_woocommerce_load_footer_html' ) ) {
                                                $template_path = ipb_popup_woocommerce_load_footer_html( 'popup_woocommerce_display_html_edit.php' );

                                                if ( $template_path ) {

                                                    ob_start();
                                                    include $template_path;
                                                    $html = ob_get_clean();
                                                   // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $html contains trusted template output
                                                    echo $html;
                                                }
                                            }
                                            }
                                            ?>
                                        </div>
                                    </div>
                                </div>
                                </div>
                                </div>
                            </div>

                            <div id="trigger" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-trigger-settings">
                                    <div class="ipb-section-header">
                                        <h3>Device Targeting</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                <div class="display_wrapper">
                                    <div class="display_inner">
                                        <?php

                                        $trigger_options = Class_instant_popup_builder_trigger::get_trigger_options();
                                        $has_exit_intent = array_key_exists('exit-intent', $trigger_options);
                                        $has_scroll_intent = array_key_exists('scroll-trigger', $trigger_options);
                                        $has_woo_intent = array_key_exists('woocommerce-trigger', $trigger_options);
                                        $has_adblock = array_key_exists('adblock-trigger', $trigger_options);
                                        $has_inactivity = array_key_exists('inactivity-trigger', $trigger_options);
                                        // Advanced triggers flags
                                        $has_adv_page_depth = array_key_exists('page-depth', $trigger_options);
                                        $has_adv_visibility = array_key_exists('element-visibility', $trigger_options);
                                        $has_adv_referrer = array_key_exists('referrer-trigger', $trigger_options);
                                        $has_adv_form_abandon = array_key_exists('form-abandonment', $trigger_options);
                                        $has_adv_returning = array_key_exists('returning-visitor', $trigger_options);
                                        ?>
                                        <div class="rules">
                                            <h2>Trigger</h2>
                                            <div class="selection">
                                                <select name="trigger_option" id="trigger_option">
                                                    <?php foreach ($trigger_options as $index => $options): ?>
                                                        <option value="<?php echo  esc_attr($index ?? ''); ?>" <?php selected($trigger_option, $index);  ?>><?php echo esc_html($options ?? ''); ?></option>
                                                    <?php endforeach; ?>
                                                    <?php if (!$has_exit_intent): ?>
                                                        <option value="exit_intent" disabled>Exit Intent 🔒</option>
                                                    <?php endif; ?>
                                                    <?php if (!$has_scroll_intent): ?>
                                                        <option value="scroll_trigger" disabled>Scroll Trigger 🔒</option>
                                                    <?php endif; ?>
                                                    <?php if (!$has_woo_intent): ?>
                                                        <option value="woo_disabled" disabled>Woocommerce 🔒</option>
                                                    <?php endif; ?>
                                                    <?php if (!$has_adblock): ?>
                                                    <option value="trigger_adblock" disabled>Adblock Trigger 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_adv_page_depth): ?>
                                                    <option value="page_depth_pro" disabled>Page Depth 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_adv_visibility): ?>
                                                    <option value="element_visibility_pro" disabled>Element Visibility 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_adv_referrer): ?>
                                                    <option value="referrer_pro" disabled>URL / Referrer 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_adv_form_abandon): ?>
                                                    <option value="form_abandonment_pro" disabled>Form Abandonment 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_adv_returning): ?>
                                                    <option value="returning_visitor_pro" disabled>Returning Visitor 🔒</option>
                                                <?php endif; ?>
                                                <?php if (!$has_inactivity): ?>
                                                    <option value="inactivity_trigger" disabled>Inactivity Trigger 🔒</option>
                                                <?php endif; ?>
                                                </select>
                                            </div>

                                            <div class="trigger_options  <?php echo $trigger_option == 'exit-intent' ? 'exit_trigger' : ''; ?>">
                                                <?php
                                                if (!empty($trigger_option)) {
                                                    $selected_option = $trigger_option;

                                                    if ($selected_option === 'onload') { ?>
                                                        <div class="fields">

                                                            <input type="number" placeholder="Delay" name="trigger_delay[]" id="trigger_delay" value="<?php echo esc_attr($trigger_delay[0]); ?>">
                                                        </div>
                                                        <i class="fa-solid fa-trash"></i>
                                                    <?php }

                                                    if ($selected_option === 'onclick') { ?>
                                                        <div class="fields">
                                                            <input type="text" value="<?php echo isset($trigger_class_click[0]) ? esc_attr($trigger_class_click[0]) : ''; ?>" name="trigger_class_click[]" id="trigger_class" readonly />
                                                            <input type="hidden" name="trigger_delay[]" id="trigger_delay" value="0">
                                                        </div>
                                                        <i class="fa-solid fa-trash"></i>
                                                    <?php }

                                                    if ($selected_option === 'onhover') { ?>
                                                        <div class="fields">
                                                            <input type="text" value="<?php echo esc_attr($trigger_class_hover[0]); ?>" name="trigger_class[]" id="trigger_class" readonly>
                                                            <input type="hidden" name="trigger_delay[]" id="trigger_delay" value="0">
                                                        </div>
                                                        <i class="fa-solid fa-trash"></i>
                                                <?php }
                                                }
                                                ?>
                                            </div>

                                        </div>
                                        <p class="ipb-trigger-helper">Delay is optional (seconds). Use 0 for immediate display.</p>
                                        <?php
                                        do_action('after_trigger_option', $trigger_option, $target_device, $trigger_delay, $exit_sensivity, $trigger); ?>
                                        <?php do_action('after_trigger_option_edit',$trigger_option); ?>
                                        <?php do_action('after_woocommerce_trigger_option_edit',$trigger_option); ?>
                                        <?php
                                        if($trigger_option != 'scroll-trigger'){
                                        do_action('after_scroll_trigger_option');
                                        }

                                        if($trigger_option != 'adblock-trigger' || $trigger_option != 'exit-intent' || $trigger_option != 'page-depth' || $trigger_option != 'element-visibility' || $trigger_option != 'referrer-trigger' || $trigger_option != 'form-abandonment' || $trigger_option != 'returning-visitor' || $trigger_option != 'inactivity-trigger'){
                                        do_action('after_trigger_content', $trigger_option, $target_device, $trigger_delay, $exit_sensivity);
                                        }
                                         ?>

                                    </div>
                                </div>
                                </div>
                                </div>
                            </div>
                            <div id="closing" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-closing-settings">
                                    <div class="ipb-section-header">
                                        <h3>Closing Options</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                <div class="closing_option">
                                    <div class="inner_wrapper">
                                        <div class="form_wrapper">
                                            <div class="input_fields">
                                                <input type="hidden" name="ipb_close_opts_version" value="1" />
                                                <div class="ipb-closing-row">
                                                    <div class="ipb-closing-label"><label>Close behavior</label></div>
                                                    <div class="ipb-closing-control ipb-closing-inline">
                                                        <label class="ipb-closing-check"><input type="checkbox" name="ipb_close_escape" value="yes" <?php checked( in_array( 'escape', $close_option, true ) ); ?> /> Close by pressing ESC</label>
                                                        <label class="ipb-closing-check"><input type="checkbox" name="ipb_close_outside" value="yes" <?php checked( in_array( 'box-outside', $close_option, true ) ); ?> /> Close by clicking outside</label>
                                                    </div>
                                                </div>
                                                <div class="ipb-closing-row">
                                                    <div class="ipb-closing-label"><label>Hide close button</label></div>
                                                    <div class="ipb-closing-control">
                                                        <label class="ipb-closing-check"><input type="checkbox" name="ipb_close_hide" value="yes" <?php checked( in_array( 'hide-close', $close_option, true ) ); ?> /> Hide the X close button</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php
                                            $ipb_hide_close_checked = in_array( 'hide-close', $close_option, true );
                                            ?>
                                            <div class="ipb-closing-row ipb-close-position-row"<?php echo $ipb_hide_close_checked ? ' style="display:none;"' : ''; ?>>
                                                <div class="ipb-closing-label"><label for="close_position"><?php esc_html_e( 'Close button position', 'instant-popup-builder' ); ?></label></div>
                                                <div class="ipb-closing-control">
                                                    <select name="close_position" id="close_position">
                                                        <?php
                                                        $ipb_close_positions = array( 'top-left', 'top-right', 'bottom-left', 'bottom-right' );
                                                        $ipb_close_pos_selected = in_array( $close_position, $ipb_close_positions, true ) ? $close_position : 'top-right';
                                                        ?>
                                                        <option value="top-left" <?php selected( $ipb_close_pos_selected, 'top-left' ); ?>><?php esc_html_e( 'Top Left', 'instant-popup-builder' ); ?></option>
                                                        <option value="top-right" <?php selected( $ipb_close_pos_selected, 'top-right' ); ?>><?php esc_html_e( 'Top Right', 'instant-popup-builder' ); ?></option>
                                                        <option value="bottom-left" <?php selected( $ipb_close_pos_selected, 'bottom-left' ); ?>><?php esc_html_e( 'Bottom Left', 'instant-popup-builder' ); ?></option>
                                                        <option value="bottom-right" <?php selected( $ipb_close_pos_selected, 'bottom-right' ); ?>><?php esc_html_e( 'Bottom Right', 'instant-popup-builder' ); ?></option>
                                                    </select>
                                                </div>
                                            </div>
                                            <?php if (!class_exists('Instant_Popup_Advanced_Closing_Addon')): ?>
                                            <div class="ipb-upsell-card">
                                                <div class="ipb-upsell-card__title"><?php esc_html_e( 'Advanced Closing', 'instant-popup-builder' ); ?></div>
                                                <p class="ipb-upsell-card__desc">
                                                    <?php esc_html_e( 'Unlock advanced closing controls (custom icon, label, auto-close, and more) for a polished popup experience.', 'instant-popup-builder' ); ?>
                                                </p>
                                                <div class="ipb-upsell-card__actions">
                                                    <a href="https://instantpopupbuilder.com/extensions/advanced-closing/" target="_blank" class="button button-primary">
                                                        <?php esc_html_e( 'Upgrade to Pro', 'instant-popup-builder' ); ?>
                                                    </a>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                </div>
                                </div>
                            </div>
                            <div id="limitation" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-frequency-settings">
                                    <div class="ipb-section-header">
                                        <h3>Frequency</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                        <div class="ipb-frequency-row">
                                            <div class="ipb-frequency-label">
                                                <label>Frequency</label>
                                            </div>
                                            <div class="ipb-frequency-control">
                                                <div class="ipb-frequency-fields">
                                                    <div class="ipb-frequency-field">
                                                        <label class="ipb-frequency-field-label" for="limit_count">
                                                            <span>Show up to</span>
                                                            <div class="info">
                                                                <img src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . '/image/info.svg'); ?>" alt="">
                                                                <div class="detail" style="display: none;">Maximum number of times this popup can appear to a visitor (tracked per browser).</div>
                                                            </div>
                                                        </label>
                                                        <input type="number" name="limit_count" id="limit_count" class="regular-text" placeholder="e.g. 1 or 3" value="<?php echo esc_attr($limit_count ?? ''); ?>">
                                                    </div>
                                                    <div class="ipb-frequency-field">
                                                        <label class="ipb-frequency-field-label" for="limit_expiry">
                                                            <span>Reset after (days)</span>
                                                            <div class="info">
                                                                <img src="<?php echo esc_url(plugin_dir_url(dirname(dirname(__FILE__))) . '/image/info.svg'); ?>" alt="">
                                                                <div class="detail" style="display: none;">After this many days, the view limit resets for the visitor.</div>
                                                            </div>
                                                        </label>
                                                        <input type="number" name="limit_expiry" id="limit_expiry" class="regular-text" placeholder="e.g. 7" value="<?php echo esc_attr($limit_expiry ?? ''); ?>">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="position" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-position-settings">
                                    <div class="ipb-section-header">
                                        <h3>Position Settings</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                        <div class="ipb-position-row">
                                            <div class="ipb-position-label">
                                                <label for="position">Position</label>
                                            </div>
                                            <div class="ipb-position-control">
                                                <div class="ipb-position-grid">
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-start-start" value="start-start" <?php echo $popup_position == 'start-start' ? 'checked' : ''; ?>>
                                                        <label for="position-start-start" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-start-center" value="start-center" <?php echo $popup_position == 'start-center' ? 'checked' : ''; ?>>
                                                        <label for="position-start-center" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-start-end" value="start-end" <?php echo $popup_position == 'start-end' ? 'checked' : ''; ?>>
                                                        <label for="position-start-end" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-center-start" value="center-start" <?php echo $popup_position == 'center-start' ? 'checked' : ''; ?>>
                                                        <label for="position-center-start" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-center-center" value="center-center" <?php echo $popup_position == 'center-center' ? 'checked' : ''; ?>>
                                                        <label for="position-center-center" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-center-end" value="center-end" <?php echo $popup_position == 'center-end' ? 'checked' : ''; ?>>
                                                        <label for="position-center-end" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-end-start" value="end-start" <?php echo $popup_position == 'end-start' ? 'checked' : ''; ?>>
                                                        <label for="position-end-start" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-end-center" value="end-center" <?php echo $popup_position == 'end-center' ? 'checked' : ''; ?>>
                                                        <label for="position-end-center" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                    <div class="ipb-position-cell">
                                                        <input type="radio" name="position" id="position-end-end" value="end-end" <?php echo $popup_position == 'end-end' ? 'checked' : ''; ?>>
                                                        <label for="position-end-end" class="ipb-position-cell-label">
                                                            <span class="ipb-position-dot"></span>
                                                        </label>
                                                    </div>
                                                </div>
                                                <p class="ipb-position-helper">Choose where the popup appears on the screen.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="action" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-actions-events">
                                    <div class="ipb-section-header">
                                        <h3>Actions & Events</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                <div class="design_background">
                                    <div class="ipb_background_wrapper">

                                        <div class="background_field" id="action_wrapper">
                                            <?php
                                            $action_enabled = isset($advance->action) && $advance->action == 'yes';
                                            $action_type = isset($advance->action_type) ? $advance->action_type : 'redirect';
                                            ?>
                                            <!-- Click Action Toggle Row -->
                                            <div class="ipb-actions-row">
                                                <div class="ipb-actions-label">
                                                    <label for="action_click">Click action</label>
                                                </div>
                                                <div class="ipb-actions-control">
                                                    <div class="input toggle switch">
                                                        <!-- Submit a deterministic value even if JS doesn't run -->
                                                        <input type="hidden" name="action_click" value="no">
                                                        <input type="checkbox" name="action_click" id="action_click" value="yes" <?php echo $action_enabled ? 'checked' : ''; ?>>
                                                        <span class="slider round"></span>
                                                    </div>
                                                    <?php if (!$action_enabled): ?>
                                                    <p class="ipb-actions-helper">Enable to add a click action.</p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>

                                            <!-- Collapsed Content Wrapper -->
                                            <div class="ipb-actions-content" id="ipb_actions_content" style="display: <?php echo $action_enabled ? 'block' : 'none'; ?>;">
                                                
                                                <!-- Action Type Row -->
                                                <div class="ipb-actions-row" id="action_type_wrapper">
                                                    <div class="ipb-actions-label">
                                                        <label for="action_type">Action Type</label>
                                                    </div>
                                                    <div class="ipb-actions-control">
                                                        <select name="action_type" id="action_type" class="regular-text">
                                                            <option value="redirect" <?php echo (!isset($advance->action_type) || $advance->action_type == 'redirect') ? 'selected' : ''; ?>>Redirect to URL</option>
                                                            <option value="open_popup" <?php echo (isset($advance->action_type) && $advance->action_type == 'open_popup') ? 'selected' : ''; ?>>Open Another Popup</option>
                                                        </select>
                                                    </div>
                                                </div>

                                                <!-- Redirect URL Section -->
                                                <div class="ipb-actions-redirect-section" id="action_redirect" style="display: <?php echo ($action_enabled && (!isset($advance->action_type) || $advance->action_type == 'redirect')) ? 'block' : 'none'; ?>;">
                                                    
                                                    <!-- Redirect URL Input Row -->
                                                    <div class="ipb-actions-row">
                                                        <div class="ipb-actions-label">
                                                            <label for="redirect_url">Redirect URL</label>
                                                        </div>
                                                        <div class="ipb-actions-control">
                                                            <input type="url" name="redirect_url" id="redirect_url" class="regular-text" placeholder="https://example.com" value="<?php echo esc_attr(isset($advance->url) ? $advance->url : ''); ?>" style="height: 40px;">
                                                            <p class="ipb-actions-helper">Include https:// in the URL.</p>
                                                        </div>
                                                    </div>

                                                    <!-- Redirect Timing & New Tab Row -->
                                                    <div class="ipb-actions-row">
                                                        <div class="ipb-actions-label">
                                                            <label for="redirect_delay_seconds">When to redirect</label>
                                                        </div>
                                                        <div class="ipb-actions-control">
                                                            <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
                                                                <?php
                                                                $ipb_rds_val = isset($advance->redirect_delay_seconds) ? (int) $advance->redirect_delay_seconds : 0;
                                                                $ipb_rds_mode = ($ipb_rds_val > 0) ? 'custom' : '0';
                                                                ?>
                                                                <select name="redirect_delay_seconds" id="redirect_delay_seconds" class="regular-text" style="flex: 1; min-width: 200px;">
                                                                    <option value="0" <?php echo ($ipb_rds_mode === '0') ? 'selected' : ''; ?>><?php esc_html_e( 'Instantly', 'instant-popup-builder' ); ?></option>
                                                                    <option value="custom" <?php echo ($ipb_rds_mode === 'custom') ? 'selected' : ''; ?>><?php esc_html_e( 'Custom', 'instant-popup-builder' ); ?></option>
                                                                </select>
                                                                <div id="redirect_delay_custom_wrapper" style="display: <?php echo ($ipb_rds_mode === 'custom') ? 'flex' : 'none'; ?>; align-items: center; gap: 6px;">
                                                                    <input type="number" name="redirect_delay_custom_seconds" id="redirect_delay_custom_seconds" min="1" max="60" step="1" value="<?php echo esc_attr($ipb_rds_val > 0 ? $ipb_rds_val : 3); ?>" style="width: 80px; height: 40px;">
                                                                    <span><?php esc_html_e( 'seconds', 'instant-popup-builder' ); ?></span>
                                                                </div>
                                                                <label style="display: flex; align-items: center; gap: 6px; margin: 0; font-weight: 400;">
                                                                    <!-- Submit a deterministic value even if JS doesn't run -->
                                                                    <input type="hidden" name="action_new_tab" value="no">
                                                                    <input type="checkbox" name="action_new_tab" id="action_new_tab" value="yes" <?php echo (isset($advance->tab) && $advance->tab == 'yes') ? 'checked' : ''; ?>>
                                                                    Open in new tab
                                                                </label>
                                                            </div>
                                                            <p class="ipb-actions-helper">Choose "Instantly" to redirect immediately, or "Custom" to set a delay in seconds and show a message first.</p>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Popup Selector Section -->
                                                <div class="ipb-actions-popup-section" id="action_popup_selector" style="display: <?php echo ($action_enabled && isset($advance->action_type) && $advance->action_type == 'open_popup') ? 'block' : 'none'; ?>;">
                                                    <div class="ipb-actions-row">
                                                        <div class="ipb-actions-label">
                                                            <label for="action_popup_id">Select Popup to Open</label>
                                                        </div>
                                                        <div class="ipb-actions-control">
                                                            <select name="action_popup_id" id="action_popup_id" class="regular-text">
                                                                <option value="">-- Select a Popup --</option>
                                                                <?php
                                                                global $wpdb;
                                                                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                                                                $current_popup_id = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
                                                                $table_name = $wpdb->prefix . 'instant_popup_builder';
                                                                $escaped_table_name = esc_sql($table_name);
                                                                // Safe query - table name is escaped, status is hardcoded
                                                                $all_popups = $wpdb->get_results($wpdb->prepare("SELECT id, title, type FROM `{$escaped_table_name}` WHERE status=%s ORDER BY title ASC", 'publish'));
                                                                if ($all_popups) {
                                                                    foreach ($all_popups as $popup) {
                                                                        // Don't show current popup in the list to prevent recursion
                                                                        if ($current_popup_id > 0 && $popup->id == $current_popup_id) {
                                                                            continue;
                                                                        }
                                                                        $popup_label = esc_html($popup->title ?? '') . ' (' . esc_html(ucfirst($popup->type ?? '')) . ')';
                                                                        $selected = (isset($advance->action_popup_id) && $advance->action_popup_id == $popup->id) ? 'selected' : '';
                                                                        echo '<option value="' . esc_attr($popup->id ?? '') . '" ' . esc_attr($selected) . '>' . esc_html($popup_label) . '</option>';
                                                                    }
                                                                }
                                                                ?>
                                                            </select>
                                                            <?php if (isset($advance->action_popup_id) && $advance->action_popup_id && $selected_popup_status && $selected_popup_status !== 'publish'): ?>
                                                                <div class="ipb-warning-message" style="margin-top: 10px; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107; color: #856404;">
                                                                    <strong>⚠️ Warning:</strong> The selected popup "<?php echo esc_html($selected_popup_title ?? ''); ?>" is currently <strong><?php echo esc_html(ucfirst($selected_popup_status ?? '')); ?></strong> and will not be shown to visitors. Please publish it to make this action work.
                                                                </div>
                                                            <?php elseif (isset($advance->action_popup_id) && $advance->action_popup_id && !$selected_popup_status): ?>
                                                                <div class="ipb-error-message" style="margin-top: 10px; padding: 10px; background: #f8d7da; border-left: 4px solid #dc3545; color: #721c24;">
                                                                    <strong>❌ Error:</strong> The selected popup (ID: <?php echo esc_html($advance->action_popup_id ?? ''); ?>) no longer exists. Please select a different popup.
                                                                </div>
                                                            <?php endif; ?>
                                                            <p class="ipb-actions-helper">Only published popups will be shown to visitors. If the selected popup is inactive, the action will not work.</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                if(isset($_GET['type']) && $_GET['type'] == 'contact_form'){ ?>
                <!-- Contact Form Tab -->
                    <div id="contact_form" class="tab_content">

                        <div class="ipb-settings-tabs">

                            <div class="ipb-tab-content">
                                <div id="form_settings" class="ipb-tab-pane active">
                                     <div class="ipb-section">
                                        <div class="ipb-section-header">
                                            <h3>Contact Form Settings</h3>
                                        </div>
                                        <div class="ipb-section-content" data-section="display">
                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="form_title"><?php esc_html_e( 'Form Title', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="text" name="form_title" id="form_title" placeholder="<?php esc_attr_e( 'Contact Us', 'instant-popup-builder' ); ?>">
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="form_description"><?php esc_html_e( 'Form Description', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <textarea name="form_description" id="form_description" rows="3" placeholder="<?php esc_attr_e( 'Get in touch with us...', 'instant-popup-builder' ); ?>"></textarea>
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="submit_button_text"><?php esc_html_e( 'Submit Button Text', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="text" name="submit_button_text" id="submit_button_text" value="<?php esc_attr_e( 'Send Message', 'instant-popup-builder' ); ?>">
                                    </div>
                                    </div>
                                    </div>
                                    <div class="ipb-section">
                                        <div class="ipb-section-header">
                                            <h3>Submit Request</h3>
                                        </div>
                                        <div class="ipb-section-content" data-section="display">
                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="success_message"><?php esc_html_e( 'Success Message', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <textarea name="success_message" id="success_message" rows="3"><?php echo esc_textarea( $settings['success_message'] ?? __( 'Thank you for your message. We will get back to you soon!', 'instant-popup-builder' ) ); ?></textarea>
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label>
                                                <input type="checkbox" name="enable_redirect" id="enable_redirect" value="1">
                                                <?php esc_html_e( 'Redirect After Submit', 'instant-popup-builder' ); ?>
                                            </label>
                                        </div>
                                        <input type="url" name="redirect_url" id="redirect_url" placeholder="<?php esc_attr_e( 'https://example.com/thank-you', 'instant-popup-builder' ); ?>">
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label>
                                                <input type="checkbox" name="enable_recaptcha" id="enable_recaptcha" value="1" <?php checked( !empty($settings['enable_recaptcha']) ); ?>>
                                                <?php esc_html_e( 'Enable reCAPTCHA', 'instant-popup-builder' ); ?>
                                            </label>
                                        </div>
                                        <p class="description">
                                            <?php
                                            /* translators: 1: opening anchor tag, 2: closing anchor tag */
                                            printf( esc_html__( 'Configure reCAPTCHA keys in %1$s Contact Form Settings %2$s', 'instant-popup-builder' ),
                                                '<a href="' .esc_url( admin_url('admin.php?page=setting-instant-popup#contact-form') ) . '">', '</a>' ); ?>
                                        </p>
                                    </div>
                                </div>
                                </div>
                                </div>
                                <div class="ipb-section">
                                        <div class="ipb-section-header">
                                            <h3>Layout Settings</h3>
                                        </div>
                                        <div class="ipb-section-content" data-section="display">
                                <div id="form_design" class="ipb-tab-pane active">
                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="form_layout"><?php esc_html_e( 'Form Layout', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <select name="form_layout" id="form_layout">
                                            <option value="vertical"><?php esc_html_e( 'Vertical', 'instant-popup-builder' ); ?></option>
                                            <option value="horizontal"><?php esc_html_e( 'Horizontal (2 columns)', 'instant-popup-builder' ); ?></option>
                                        </select>
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="form_width"><?php esc_html_e( 'Form Width (px)', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="number" name="form_width" id="form_width" value="400" min="300" max="800">
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label for="button_color"><?php esc_html_e( 'Button Color', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="color" name="button_color" id="button_color" value="#3498db">
                                    </div>

                                    <div class="input_wrapper">
                                        <div class="label">
                                            <label>
                                                <input type="checkbox" name="enable_form_background" id="enable_form_background" value="1">
                                                <?php esc_html_e( 'Enable Form Background', 'instant-popup-builder' ); ?>
                                            </label>
                                        </div>
                                    </div>

                                    <div class="input_wrapper" id="form_background_type_wrapper" style="display: none;">
                                        <div class="label">
                                            <label for="form_background_type"><?php esc_html_e( 'Background Type', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <select name="form_background_type" id="form_background_type">
                                            <option value="color"><?php esc_html_e( 'Color', 'instant-popup-builder' ); ?></option>
                                            <option value="image"><?php esc_html_e( 'Image', 'instant-popup-builder' ); ?></option>
                                        </select>
                                    </div>

                                    <div class="input_wrapper" id="form_background_color_wrapper" style="display: none;">
                                        <div class="label">
                                            <label for="form_background_color"><?php esc_html_e( 'Background Color', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="color" name="form_background_color" id="form_background_color" value="#ffffff">
                                    </div>

                                    <div class="input_wrapper" id="form_background_image_wrapper" style="display: none;">
                                        <div class="label">
                                            <label for="form_background_image"><?php esc_html_e( 'Background Image URL', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="url" name="form_background_image" id="form_background_image" placeholder="https://example.com/image.jpg">
                                        <button type="button" class="button" id="upload_form_background_image"><?php esc_html_e( 'Upload Image', 'instant-popup-builder' ); ?></button>
                                    </div>

                                    <div class="input_wrapper" id="form_background_opacity_wrapper" style="display: none;">
                                        <div class="label">
                                            <label for="form_background_opacity"><?php esc_html_e( 'Background Opacity', 'instant-popup-builder' ); ?></label>
                                        </div>
                                        <input type="range" name="form_background_opacity" id="form_background_opacity"
                                               min="0" max="1" step="0.1" value="1">
                                        <span id="form_background_opacity_value">1</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </div>
                        </div>
                    </div>
                    <?php } ?>

                <div id="design" class="tab_content">
                    <div class="ipb-settings-tabs">
                        <!-- <ul class="v_tabs_list">
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $html contains trusted template output
                           // echo self::renderChildHtml($this->getChildTabs('design')); ?>
                        </ul> -->
                        <div class="ipb-tab-content">
                            <div id="background" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-background-settings">
                                    <div class="ipb-section-header">
                                        <h3>Background</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                        <?php
                                        // Determine if background is enabled (has background_selection value)
                                        $background_enabled = isset($design->background_selection) && !empty($design->background_selection);
                                        $background_selection = isset($design->background_selection) ? $design->background_selection : 'color';
                                        // Default to 'color' if background is enabled but no selection
                                        if ($background_enabled && empty($background_selection)) {
                                            $background_selection = 'color';
                                        }
                                        ?>
                                        <!-- Master Background Toggle Row -->
                                        <div class="ipb-background-row">
                                            <div class="ipb-background-label">
                                                <label for="background_enabled">Background</label>
                                            </div>
                                            <div class="ipb-background-control">
                                                <div class="input toggle switch">
                                                    <input type="checkbox" name="background_enabled" id="background_enabled" value="yes" <?php echo $background_enabled ? 'checked' : ''; ?>>
                                                    <span class="slider round"></span>
                                                </div>
                                                <p class="ipb-background-helper" style="display: <?php echo $background_enabled ? 'none' : 'block'; ?>; margin-top: 8px; color: #646970; font-size: 12px;">Enable to use a background.</p>
                                            </div>
                                        </div>

                                        <!-- Background Controls Wrapper -->
                                        <div class="ipb-background-content" id="ipb_background_content" style="display: <?php echo $background_enabled ? 'block' : 'none'; ?>;">
                                            
                                            <!-- Select Background Row -->
                                            <div class="ipb-background-row">
                                                <div class="ipb-background-label">
                                                    <label for="background_selection">Select Background</label>
                                                </div>
                                                <div class="ipb-background-control">
                                                    <select name="background_selection" id="background_selection" class="regular-text">
                                                        <option value="color" <?php selected($background_selection, 'color'); ?>>Color</option>
                                                        <option value="image" <?php selected($background_selection, 'image'); ?>>Image</option>
                                                    </select>
                                                    <p class="ipb-background-helper">Choose a solid color or an image background.</p>
                                                </div>
                                            </div>

                                            <!-- Color Background Section -->
                                            <div class="ipb-background-color-section" id="ipb_background_color_section" style="display: <?php echo $background_selection == 'color' ? 'block' : 'none'; ?>;">
                                                
                                                <!-- Background Color Row -->
                                                <div class="ipb-background-row">
                                                    <div class="ipb-background-label">
                                                        <label for="background_color">Background Color</label>
                                                    </div>
                                                    <div class="ipb-background-control">
                                                        <input type="color" name="background_color" id="background_color" value="<?php echo esc_attr(isset($design->background_color) ? $design->background_color : ($type === 'text' ? '#ffffff' : '#ffffff')); ?>" style="width: 80px; height: 40px; border: 1px solid #8c8f94; border-radius: 2px; cursor: pointer;">
                                                    </div>
                                                </div>

                                                <!-- Background Color Opacity Row -->
                                                <div class="ipb-background-row">
                                                    <div class="ipb-background-label">
                                                        <label for="backcolor_opacity">Opacity</label>
                                                    </div>
                                                    <div class="ipb-background-control">
                                                        <div style="display: flex; align-items: center; gap: 12px;">
                                                            <input type="range" name="backcolor_opacity" min="0" max="1" step="0.1" id="backcolor_opacity" value="<?php echo esc_attr(isset($design->backcolor_opacity) ? $design->backcolor_opacity : ($type === 'text' ? '1.0' : '1.0')); ?>" style="flex: 1; min-width: 0;">
                                                            <input type="number" name="backcolor_opacity_value" id="backcolor_opacity_value" min="0" max="1" step="0.1" value="<?php echo esc_attr(isset($design->backcolor_opacity) ? $design->backcolor_opacity : ($type === 'text' ? '1.0' : '1.0')); ?>" style="width: 80px; height: 40px; padding: 0 8px; border: 1px solid #8c8f94; border-radius: 2px; text-align: center;">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Image Background Section -->
                                            <div class="ipb-background-image-section" id="ipb_background_image_section" style="display: <?php echo $background_selection == 'image' ? 'block' : 'none'; ?>;">
                                                
                                                <!-- Background Image Row -->
                                                <?php
                                                $ipb_design_bg_url   = isset($design->background_image) ? $design->background_image : '';
                                                $ipb_design_bg_valid = $ipb_design_bg_url && $ipb_design_bg_url !== '#' && $ipb_design_bg_url !== '1';
                                                ?>
                                                <div class="ipb-background-row">
                                                    <div class="ipb-background-label">
                                                        <label for="ipb_background_media_btn"><?php esc_html_e( 'Background Image', 'instant-popup-builder' ); ?></label>
                                                    </div>
                                                    <div class="ipb-background-control">
                                                        <div style="display: flex; flex-direction: column; gap: 8px;">
                                                            <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                                                                <button type="button" class="button" id="ipb_background_media_btn">
                                                                    <span class="dashicons dashicons-admin-media" style="vertical-align: middle; margin-top: 3px;"></span>
                                                                    <?php esc_html_e( 'Select from Media Library', 'instant-popup-builder' ); ?>
                                                                </button>
                                                                <button type="button" class="button" id="ipb_background_remove_btn" style="<?php echo $ipb_design_bg_valid ? '' : 'display:none;'; ?>">
                                                                    <?php esc_html_e( 'Remove', 'instant-popup-builder' ); ?>
                                                                </button>
                                                                <input type="hidden" name="background_image_url" id="background_image_url" value="<?php echo esc_url($ipb_design_bg_valid ? $ipb_design_bg_url : ''); ?>">
                                                            </div>
                                                            <p class="ipb-background-helper" style="margin: 0;"><?php esc_html_e( 'Choose an existing image or upload a new one from the Media Library.', 'instant-popup-builder' ); ?></p>
                                                            <?php
                                                            $ipb_bg_summary_text = '';
                                                            if ( $ipb_design_bg_valid ) {
                                                                $ipb_bg_path = wp_parse_url( $ipb_design_bg_url, PHP_URL_PATH );
                                                                $ipb_bg_summary_text = sprintf(
                                                                    /* translators: %s: image file name */
                                                                    __( 'Selected: %s', 'instant-popup-builder' ),
                                                                    $ipb_bg_path ? basename( $ipb_bg_path ) : $ipb_design_bg_url
                                                                );
                                                            }
                                                            ?>
                                                            <p class="ipb-background-selected-summary<?php echo $ipb_design_bg_valid ? '' : ' is-empty'; ?>" id="ipb_background_selected_summary"><?php echo esc_html( $ipb_bg_summary_text ); ?></p>
                                                            <img src="<?php echo esc_url($ipb_design_bg_valid ? $ipb_design_bg_url : ''); ?>" alt="" class="ipb_back_img" style="display:<?php echo $ipb_design_bg_valid ? 'block' : 'none'; ?>; max-width: 200px; height: auto; border: 1px solid #ddd; border-radius: 4px; margin-top: 8px;" />
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Background Image Opacity Row -->
                                                <div class="ipb-background-row">
                                                    <div class="ipb-background-label">
                                                        <label for="backimage_opacity">Opacity</label>
                                                    </div>
                                                    <div class="ipb-background-control">
                                                        <div style="display: flex; align-items: center; gap: 12px;">
                                                            <input type="range" name="backimage_opacity" min="0" max="1" step="0.1" id="backimage_opacity" value="<?php echo esc_attr(isset($design->backimage_opacity) ? $design->backimage_opacity : '1.0'); ?>" style="flex: 1; min-width: 0;">
                                                            <input type="number" name="backimage_opacity_value" id="backimage_opacity_value" min="0" max="1" step="0.1" value="<?php echo esc_attr(isset($design->backimage_opacity) ? $design->backimage_opacity : '1.0'); ?>" style="width: 80px; height: 40px; padding: 0 8px; border: 1px solid #8c8f94; border-radius: 2px; text-align: center;">
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- Background Image Size Row -->
                                                <div class="ipb-background-row">
                                                    <div class="ipb-background-label">
                                                        <label for="back_image_size">Image Size</label>
                                                    </div>
                                                    <div class="ipb-background-control">
                                                        <select name="back_image_size" id="back_image_size" class="regular-text">
                                                            <option value="cover" <?php selected(isset($design->back_image_size) ? $design->back_image_size : 'cover', 'cover'); ?>>Cover</option>
                                                            <option value="contain" <?php selected(isset($design->back_image_size) ? $design->back_image_size : '', 'contain'); ?>>Contain</option>
                                                            <option value="none" <?php selected(isset($design->back_image_size) ? $design->back_image_size : '', 'none'); ?>>None</option>
                                                            <option value="unset" <?php selected(isset($design->back_image_size) ? $design->back_image_size : '', 'unset'); ?>>Unset</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="size" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-size-layout">
                                    <div class="ipb-section-header">
                                        <h3>Size & Layout</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                        <?php
                                        $size_mode = isset($design->design_percentage_toggle) ? $design->design_percentage_toggle : 'yes';
                                        $is_fixed_mode = $size_mode == 'no';
                                        $is_percentage_mode = $size_mode == 'yes';
                                        $design_percentage = isset($design->design_percentage) ? $design->design_percentage : '50';
                                        ?>
                                        <!-- Size Mode Row -->
                                        <div class="ipb-size-row">
                                            <div class="ipb-size-label">
                                                <label for="design_percentage_toggle">Size mode</label>
                                            </div>
                                            <div class="ipb-size-control">
                                                <select name="design_percentage_toggle" id="design_percentage_toggle" class="regular-text">
                                                    <option value="yes" <?php selected($size_mode, 'yes'); ?>>Percentage (%)</option>
                                                    <option value="no" <?php selected($size_mode, 'no'); ?>>Fixed Size (px)</option>
                                                </select>
                                                <p class="ipb-size-helper">Choose fixed dimensions or responsive percentage.</p>
                                            </div>
                                        </div>

                                        <!-- Fixed Size (px) Mode Section -->
                                        <div class="ipb-size-fixed-section" id="ipb_size_fixed_section" style="display: <?php echo $is_fixed_mode ? 'block' : 'none'; ?>;">
                                            
                                            <!-- Width Row -->
                                            <div class="ipb-size-row">
                                                <div class="ipb-size-label">
                                                    <label for="design_width">Width</label>
                                                </div>
                                                <div class="ipb-size-control">
                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                        <input type="number" name="design_width" id="design_width" class="regular-text" placeholder="Enter width" value="<?php echo esc_attr($design->design_width ?? '0'); ?>" min="0" max="2000" step="1" style="flex: 1; min-width: 0;">
                                                        <span style="color: #646970; font-size: 14px; white-space: nowrap;">px</span>
                                                        <button type="button" id="lock_aspect_ratio_btn" class="button button-secondary" style="padding: 6px 10px; font-size: 14px; min-width: 36px; height: 36px; border: 1px solid #8c8f94; background: #f6f7f7; cursor: pointer; border-radius: 2px; display: flex; align-items: center; justify-content: center;" title="Lock aspect ratio">
                                                            <i class="fa-solid fa-lock-open" style="color: #646970;"></i>
                                                        </button>
                                                    </div>
                                                    <input type="hidden" id="aspect_ratio_locked" value="0">
                                                    <input type="hidden" id="aspect_ratio_value" value="0">
                                                    <p class="ipb-size-helper">Leave 0 for default popup size. Recommended: 400-800px (Max: 2000px)</p>
                                                </div>
                                            </div>

                                            <!-- Height Row -->
                                            <div class="ipb-size-row">
                                                <div class="ipb-size-label">
                                                    <label for="design_height">Height</label>
                                                </div>
                                                <div class="ipb-size-control">
                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                        <input type="number" name="design_height" id="design_height" class="regular-text" placeholder="Enter height" value="<?php echo esc_attr($design->design_height ?? '0'); ?>" min="0" max="1500" step="1" style="flex: 1; min-width: 0;">
                                                        <span style="color: #646970; font-size: 14px; white-space: nowrap;">px</span>
                                                    </div>
                                                    <p class="ipb-size-helper"><?php echo $type === 'text' ? esc_html__( 'Text popups stay content-height. This value sets the maximum height before content scrolls. Leave 0 for the responsive default.', 'instant-popup-builder' ) : esc_html__( 'Leave 0 for auto-height based on content (Max: 1500px)', 'instant-popup-builder' ); ?></p>
                                                </div>
                                            </div>

                                            <!-- Detect Popup Size Button Row -->
                                            <div class="ipb-size-row">
                                                <div class="ipb-size-label">
                                                    <!-- Empty label column -->
                                                </div>
                                                <div class="ipb-size-control">
                                                    <button type="button" id="detect_popup_size_btn" class="button button-secondary" style="padding: 6px 12px; font-size: 13px;">
                                                        <i class="fa-solid fa-arrows-left-right-to-line"></i> Detect Popup Size
                                                    </button>
                                                    <span id="detect_size_status" style="margin-left: 10px; color: #10b981; display: none;">
                                                        <i class="fa-solid fa-circle-check"></i> Size detected!
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Percentage (%) Mode Section -->
                                        <div class="ipb-size-percentage-section" id="ipb_size_percentage_section" style="display: <?php echo $is_percentage_mode ? 'block' : 'none'; ?>;">
                                            <div class="ipb-size-row">
                                                <div class="ipb-size-label">
                                                    <label for="design_percentage">Size</label>
                                                </div>
                                                <div class="ipb-size-control">
                                                    <div style="display: flex; align-items: center; gap: 12px;">
                                                        <input type="range" id="design_percentage" name="design_percentage" min="0" max="100" value="<?php echo esc_attr($design_percentage); ?>" step="10" style="flex: 1; min-width: 0;">
                                                        <input type="number" id="design_percentage_value" name="design_percentage_value" min="0" max="100" value="<?php echo esc_attr($design_percentage); ?>" step="10" style="width: 80px; height: 40px; padding: 0 8px; border: 1px solid #8c8f94; border-radius: 2px; text-align: center;">
                                                        <span style="color: #646970; font-size: 14px; white-space: nowrap;">%</span>
                                                    </div>
                                                    <p class="ipb-size-helper">Set 0 for default size. Set popup width as percentage (10-100%) for responsive design.</p>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Border Row -->
                                        <div class="ipb-size-row ipb-border-settings">
                                            <div class="ipb-size-label">
                                                <label for="border_enabled"><?php esc_html_e( 'Border', 'instant-popup-builder' ); ?></label>
                                            </div>
                                            <div class="ipb-size-control">
                                                <?php $ipb_border_enabled = isset($design->border_enabled) ? (string) $design->border_enabled : 'no'; ?>
                                                <div class="ipb-border-controls">
                                                    <label class="ipb-border-toggle">
                                                        <input type="hidden" name="border_enabled" value="no">
                                                        <input type="checkbox" name="border_enabled" id="border_enabled" value="yes" <?php checked($ipb_border_enabled, 'yes'); ?>>
                                                        <?php esc_html_e( 'Enable border', 'instant-popup-builder' ); ?>
                                                    </label>
                                                    <div class="ipb-border-width-control">
                                                        <input type="number" name="border_width" id="border_width" min="0" max="40" step="1" value="<?php echo esc_attr( isset($design->border_width) ? (int) $design->border_width : 1 ); ?>" style="width:90px;">
                                                        <span><?php esc_html_e( 'px', 'instant-popup-builder' ); ?></span>
                                                    </div>
                                                    <input type="color" name="border_color" id="border_color" value="<?php echo esc_attr( isset($design->border_color) ? (string) $design->border_color : '#111827' ); ?>">
                                                </div>
                                                <p class="ipb-size-helper"><?php esc_html_e( 'Adds a border to the popup container. Choose width and color.', 'instant-popup-builder' ); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="animation" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-animation-effects">
                                    <div class="ipb-section-header">
                                        <h3>Animation Effects</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                        <?php
                                        $animate_type = isset($design->animate_type) ? $design->animate_type : 'none';
                                        $animate_speed = isset($design->animate_speed) ? $design->animate_speed : '500';
                                        $animate_origin = isset($design->animate_origin) ? $design->animate_origin : 'bottom';
                                        ?>
                                        <!-- Animate Type Row -->
                                        <div class="ipb-animation-row">
                                            <div class="ipb-animation-label">
                                                <label for="animate_type">Animate type</label>
                                            </div>
                                            <div class="ipb-animation-control">
                                                <select name="animate_type" id="animate_type" class="regular-text">
                                                    <option value="none" <?php selected($animate_type, 'none'); ?>>None</option>
                                                    <option value="fade-in" <?php selected($animate_type, 'fade-in'); ?>>Fade In</option>
                                                    <option value="slide" <?php selected($animate_type, 'slide'); ?>>Slide</option>
                                                    <option value="scale" <?php selected($animate_type, 'scale'); ?>>Scale (Zoom In)</option>
                                                    <option value="reveal" <?php selected($animate_type, 'reveal'); ?>>Expand From Trigger (Reveal)</option>
                                                </select>
                                                <p class="ipb-animation-helper">Choose how the popup appears.</p>
                                            </div>
                                        </div>

                                        <!-- Animate Speed Row -->
                                        <div class="ipb-animation-row">
                                            <div class="ipb-animation-label">
                                                <label for="animate_speed">Animate speed</label>
                                            </div>
                                            <div class="ipb-animation-control">
                                                <div style="display: flex; align-items: center; gap: 12px;">
                                                    <input type="range" name="speed_range" id="speed_range" min="0" step="100" max="1000" value="<?php echo esc_attr($animate_speed); ?>" style="flex: 1; min-width: 0;">
                                                    <input type="number" name="animate_speed" id="animate_speed" min="0" max="1000" step="100" value="<?php echo esc_attr($animate_speed); ?>" style="width: 80px; height: 40px; padding: 0 8px; border: 1px solid #8c8f94; border-radius: 2px; text-align: center;">
                                                </div>
                                                <p class="ipb-animation-helper">Lower is faster. Range: 0-1000ms. Recommended: 300-500ms for smooth effect.</p>
                                            </div>
                                        </div>

                                        <!-- Animate Origin Row -->
                                        <div class="ipb-animation-row">
                                            <div class="ipb-animation-label">
                                                <label for="animate_origin">Animate origin</label>
                                            </div>
                                            <div class="ipb-animation-control">
                                                <select name="animate_origin" id="animate_origin" class="regular-text">
                                                    <option value="bottom" <?php selected($animate_origin, 'bottom'); ?>>Bottom</option>
                                                    <option value="left" <?php selected($animate_origin, 'left'); ?>>Left</option>
                                                    <option value="right" <?php selected($animate_origin, 'right'); ?>>Right</option>
                                                    <option value="top" <?php selected($animate_origin, 'top'); ?>>Top</option>
                                                </select>
                                                <p class="ipb-animation-helper">Choose the direction from which the popup animates. For slide animations, the popup will enter from the selected direction.</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="sound" class="ipb-tab-pane active">
                                <div class="ipb-section ipb-sound-settings">
                                    <div class="ipb-section-header">
                                        <h3>Sound Effects</h3>
                                    </div>
                                    <div class="ipb-section-content" data-section="display">
                                <div class="design_background">
                                    <div class="ipb_background_wrapper ipb_sound_wrapper ">

                                        <div class="background_field sound_wrap" id="action_wrapper">
                                            <div class="toggle">
                                                <div class="sound_inputs" id="action_toggle">
                                                    <label for="sound_open">Popup opening sound</label>
                                                    <div class="input toggle switch">
                                                        <input type="checkbox" name="sound_open" id="sound_open" value="<?php echo esc_attr(isset($advance->sound_open) ? $advance->sound_open : ''); ?>" <?php echo (isset($advance->sound_open) && $advance->sound_open == 'yes') ? 'checked' : ''; ?> />
                                                        <span class="slider round"></span>
                                                    </div>
                                                </div>
                                                <p class="ipb-sound-helper">Enable to play a sound when the popup opens.</p>
                                                <div class="sound_inputs" id="action_toggle">
                                                    <label for="sound_close">Popup closing sound</label>
                                                    <div class="input toggle switch">
                                                        <input type="checkbox" name="sound_close" id="sound_close" value="<?php echo esc_attr(isset($advance->sound_close) ? $advance->sound_close : ''); ?>" <?php echo (isset($advance->sound_close) && $advance->sound_close == 'yes') ? 'checked' : ''; ?>>
                                                        <span class="slider round"></span>
                                                    </div>
                                                </div>
                                                <p class="ipb-sound-helper">Enable to play a sound when the popup closes.</p>
                                            </div>
                                            <div class="sounds">
                                                <div class="sound_input" id="sound_opening_file" style="display: none;">
                                                    <h3>Choose Opening Sound</h3>
                                                    <div class="sound_fields">
                                                        <i class="fa-solid fa-cloud-arrow-up"></i>
                                                        <input type="file" name="sound_open_file" id="sound_open_file" style="display:none;" type="/mp3">
                                                        <input type="hidden" name="sound_open_url" class="sound_hidden" id="sound_open_url" value="<?php echo esc_attr(isset($advance->sound_open_file) ? $advance->sound_open_file : ''); ?>">
                                                        <label for="">Upload</label>

                                                        <audio id="ipb_audioOpen" class="audio_file" controls style="dislay:<?php echo (isset($advance->sound_open_file) && $advance->sound_open_file != '') ? 'block' : 'none'; ?> !important;">
                                                            <source src="<?php echo esc_url(isset($advance->sound_open_file) ? $advance->sound_open_file : ''); ?>" type="audio/mp3">
                                                        </audio>
                                                    </div>
                                                    <div class="sound_fields">
                                                        <audio id="audioOpen" class="audio_file" src="<?php echo esc_attr(plugin_dir_url(dirname(dirname(dirname(__FILE__)))) . 'assets/uploads/sound.mp3'); ?>" display="none"></audio>
                                                        <div class="play">
                                                            <i class="fa-solid fa-volume-low"></i>
                                                            <div class="controls">
                                                                <i class="fa-solid fa-play"></i>
                                                            </div>
                                                        </div>
                                                        <label for="">Test</label>
                                                    </div>
                                                </div>
                                                <div class="sound_input" id="sound_close_file" style="display: none;">
                                                    <h3>Choose Closing Sound</h3>
                                                    <div class="sound_fields">
                                                        <i class="fa-solid fa-cloud-arrow-up"></i>
                                                        <input type="file" name="sound_closing_file" id="sound_closing_file" style="display:none;" type="/mp3">
                                                        <input type="hidden" name="sound_closing_url" class="sound_hidden" id="sound_closing_url" value="<?php echo esc_attr(isset($advance->sound_close_file) ? $advance->sound_close_file : ''); ?>">
                                                        <label for="">Upload</label>
                                                        <audio id="ipb_audioOpen" class="audio_file" controls style="dislay:<?php echo (isset($advance->sound_close_file) && $advance->sound_close_file != '')  ? 'block' : 'none'; ?> !important;">
                                                            <source src="<?php echo esc_url(isset($advance->sound_close_file) ? $advance->sound_close_file : ''); ?>" type="audio/mp3">
                                                        </audio>

                                                    </div>
                                                    <div class="sound_fields">
                                                        <audio id="audioClose" class="audio_file" src="<?php echo esc_attr(plugin_dir_url(dirname(dirname(dirname(__FILE__))))) . 'assets/uploads/sound.mp3'; ?>" display="none"></audio>
                                                        <div class="play">
                                                            <i class="fa-solid fa-volume-low"></i>
                                                            <div class="controls">
                                                                <i class="fa-solid fa-play"></i>
                                                            </div>
                                                        </div>
                                                        <label for="">Test</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="condition" class="tab_content">
                    <div class="ipb-settings-tabs">
                        <!-- <ul class="v_tabs_list">
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $html contains trusted template output
                           // echo self::renderChildHtml($this->getChildTabs('condition')); ?>
                        </ul> -->
                        <div class="ipb-tab-content">
                            <?php
                            // Get condition tabs dynamically
                            $condition_tabs = $this->getChildTabs('condition');
                            $first_tab = true;
                            foreach ($condition_tabs as $tab_id => $tab_name) :
                                $active_class = $first_tab ? 'active' : '';
                                $first_tab = false;
                            ?>
                            <div id="<?php echo esc_attr($tab_id); ?>" class="ipb-tab-pane active<?php //echo esc_attr($active_class); ?>">
                                <?php
                                // Handle core tabs with core logic
                                if ($tab_id === 'location') {
                                    echo '<div class="design_background">';
                                    class_instant_setting::condition_setting('location');
                                    echo '</div>';
                                } elseif ($tab_id === 'scheduling') {
                                    echo '<div class="design_background">';
                                    class_instant_setting::condition_setting('scheduling');
                                    echo '</div>';
                                } elseif ($tab_id === 'targeting') {
                                    // Check if Custom Targeting Extension is active
                                    echo '<div class="design_background">';

                                   class_instant_setting::condition_setting('targeting');
                                    echo '</div>';

                                } elseif ($tab_id === 'language_targeting') {
                                    echo '<div class="design_background">';
                                    class_instant_setting::condition_setting('language_targeting');
                                    echo '</div>';
                                }
                                ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

            </div>
            <style>
/* Subscription Settings Editor Styles - Following standard UI/UX */
.subscription_settings_editor {
    padding: 0px !important;
}

.subscription_settings_editor h2 {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 18px;
    font-weight: 600;
}

.subscription_settings_editor .tab_description {
    margin: 0 0 25px 0;
    color: #666;
    font-size: 14px;
    font-style: italic;
}

.subscription_setting_group {
    margin-bottom: 25px;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background: #f9f9f9;
}

.subscription_setting_group h3 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 14px;
    font-weight: 600;
    display: block !important;
    align-items: center;
    gap: 8px;
}

.subscription_setting_field {
    margin-bottom: 15px;
}
#subscription .ipb-section-content{
    padding: 0px !important;
    border: unset !important;
}
#subscription .ipb-section{
    padding: 0px !important;
    border: unset !important;
}
.subscription_setting_field:last-child {
    margin-bottom: 0;
}

.subscription_setting_label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #333;
    cursor: pointer;
    margin-bottom: 5px;
}

.subscription_setting_label input[type="checkbox"] {
    margin: 0;
}

.field_description {
    color: #666;
    font-size: 12px;
    margin: 5px 0 0 0;
    line-height: 1.4;
}

.privacy_link_type,
.terms_link_type {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
}

.privacy_link_type label,
.terms_link_type label {
    display: flex;
    align-items: center;
    gap: 5px;
    font-weight: normal;
    font-size: 13px;
}

.subscription_setting_field label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #333;
    font-size: 13px;
}

.subscription_setting_field input[type="text"],
.subscription_setting_field input[type="url"],
.subscription_setting_field select,
.subscription_setting_field textarea {
    width: 100%;
    max-width: 400px;
    padding: 8px 12px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 13px;
}

.subscription_setting_field textarea {
    resize: vertical;
    min-height: 60px;
}

.privacy_options,
.terms_options {
    margin-left: 15px;
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    border: 1px solid #e5e5e5;
}

#advanced_triggers_settings .fields label:first-child {
    display: none !important;
}
.background_field{
width: auto !important;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Toggle privacy options
    jQuery('[name="background_selection"]').on('change', function(){
   var bgvalue =  jQuery(this).val();
   if(bgvalue == 'color'){
       jQuery('.background_color').addClass('show');
       jQuery('.background_image').removeClass('show');
   }
   if(bgvalue == 'image'){
       jQuery('.background_color').removeClass('show');
       jQuery('.background_image').addClass('show');
   }
});
    $('#subscription_show_privacy').on('change', function() {
        if ($(this).is(':checked')) {
            $('.privacy_options').slideDown();
        } else {
            $('.privacy_options').slideUp();
        }
    });

    // Toggle terms options
    $('#subscription_show_terms').on('change', function() {
        if ($(this).is(':checked')) {
            $('.terms_options').slideDown();
        } else {
            $('.terms_options').slideUp();
        }
    });

    // Privacy link type toggle
    $('input[name="privacy_link_type"]').on('change', function() {
        if ($(this).val() === 'url') {
            $('.privacy_url_field').show();
            $('.privacy_page_field').hide();
        } else {
            $('.privacy_url_field').hide();
            $('.privacy_page_field').show();
        }
    });

    // Terms link type toggle
    $('input[name="terms_link_type"]').on('change', function() {
        if ($(this).val() === 'url') {
            $('.terms_url_field').show();
            $('.terms_page_field').hide();
        } else {
            $('.terms_url_field').hide();
            $('.terms_page_field').show();
        }
    });

    // Subscribe to Download - Media Library Integration
    // Ensure wp.media is available
    if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
        console.error('WordPress Media Library is not available. Please ensure wp_enqueue_media() is called.');
    } else {
        var std_media_frame;
        $(document).on('click', '#std_select_media_btn', function(e) {
            e.preventDefault();
            
            // If the media frame already exists, reopen it
            if (std_media_frame) {
                std_media_frame.open();
                return;
            }
            
            // Create the media frame
            std_media_frame = wp.media({
                title: 'Select File for Download',
                button: {
                    text: 'Use this file'
                },
                multiple: false,
                library: {
                    type: '' // Allow all file types
                }
            });
            
            // When a file is selected, run a callback
            std_media_frame.on('select', function() {
                var attachment = std_media_frame.state().get('selection').first().toJSON();
                var fileUrl = attachment.url;
                var fileName = attachment.filename || attachment.title;
                var attachmentId = attachment.id;
                
                $('#std_file_attachment_id').val(attachmentId);
                $('#std_file_url').val(fileUrl);
                $('.std-file-name-display').text(fileName);
                $('#std_remove_file_btn').show();
            });
            
            // Open the media frame
            std_media_frame.open();
        });
    }
    
    // Remove file
    $(document).on('click', '#std_remove_file_btn', function() {
        $('#std_file_attachment_id').val('');
        $('#std_file_url').val('');
        $('.std-file-name-display').text('Select File from Media Library');
        $(this).hide();
    });
    
    // Delivery method change handler
    $('input[name="std_delivery_method"]').on('change', function() {
        if ($(this).val() === 'button') {
            $('.std-button-preview-section').slideDown();
        } else {
            $('.std-button-preview-section').slideUp();
        }
    });
    
    // Live preview updates for thank you message
    $('#std_thank_you_message').on('input', function() {
        $('#std_preview_thank_you').text($(this).val() || 'Thank you for Subscribing !');
    });
    
    // Live preview updates for download button text
    $('#std_download_button_text').on('input', function() {
        $('#std_preview_button_text').text($(this).val() || 'Click to download File');
    });
    
});

</script>

<?php
            return ob_get_clean();
        }

        /**
         * Get setting navigation
         *
         * @return string
         *
         */
        public function setting_edit_navigation()
        {

            $html = '';
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET parameter used for tab navigation/display purposes only, value is sanitized
            $temp_type = isset( $_GET['type'] ) ? sanitize_key( wp_unslash( $_GET['type'] ) ) : '';

            // If editing, get type from database
            // phpcs:disable WordPress.Security.NonceVerification.Recommended -- GET edit_id only resolves popup type for tab navigation UI; capability checks apply on save.
            if (empty($temp_type) && isset($_GET['edit_id'])) {
                global $wpdb;
                $popup_id = intval(wp_unslash($_GET['edit_id']));
                // phpcs:enable WordPress.Security.NonceVerification.Recommended
                $popup_data = $wpdb->get_row($wpdb->prepare(
                    "SELECT type FROM {$wpdb->prefix}instant_popup_builder WHERE id = %d",
                    $popup_id
                ));
                if ($popup_data && !empty($popup_data->type)) {
                    $temp_type = $popup_data->type;
                }
            }

            $tabs = self::setting_get_edit_tabs();

            // Remove extension-specific tabs that don't match current popup type
            if($temp_type != 'pdf'){
                $remove_pdf = 'ipb_pdf';
                unset($tabs [$remove_pdf]);
            }
            if($temp_type != 'video'){
                $remove_video = 'ipb_video';
                unset($tabs [$remove_video]);
            }
            if($temp_type != 'subscription'){
                $remove_subscription = 'ipb_subscription';
                unset($tabs [$remove_subscription]);
            }
            if($temp_type != 'image_gallery'){
                $remove_image_gallery = 'ipb_image_gallery';
                unset($tabs [$remove_image_gallery]);
            }
            if($temp_type != 'age_verification'){
                $remove_age_verification = 'ipb_age_verification';
                unset($tabs [$remove_age_verification]);
            }
            if($temp_type != 'recent_orders'){
                $remove_recent_orders = 'ipb_recent_orders';
                unset($tabs [$remove_recent_orders]);
            }
            if($temp_type != 'text'){
                $remove_text = 'ipb_text';
                unset($tabs [$remove_text]);
            }

            // Add video tab if this is a video popup and extension is licensed
            // Insert it before 'general' tab as standard practice
            if ($temp_type === 'video') {
                $video_license = get_option('video_license_active');
                if ($video_license === 'yes') {
                    // Rebuild array to insert video tab before general
                    $ordered_tabs = [];
                    foreach ($tabs as $key => $value) {
                        if ($key === 'general') {
                            // Insert video tab before general
                            $ordered_tabs['ipb_video'] = 'Video Settings';
                        }
                        $ordered_tabs[$key] = $value;
                    }
                    $tabs = $ordered_tabs;
                }
            }

            // Add contact form tab when editing a contact form popup
            if ($temp_type === 'contact_form') {
                $ordered_tabs = [];
                foreach ($tabs as $key => $value) {
                    if ($key === 'general') {
                        $ordered_tabs['ipb_contact_form'] = 'Contact Form';
                    }
                    $ordered_tabs[$key] = $value;
                }
                $tabs = $ordered_tabs;
            }

            // Add feedback tab before General for Feedback popup type.
            if ($temp_type === 'feedback') {
                $ordered_tabs = [];
                foreach ($tabs as $key => $value) {
                    if ($key === 'general') {
                        $ordered_tabs['ipb_feedback'] = __('Feedback Settings', 'instant-popup-builder');
                    }
                    $ordered_tabs[$key] = $value;
                }
                $tabs = $ordered_tabs;
            }
            ///var_dump($tabs);
            $count = 0;
            $html .= '<h3>Popup Setting</h3><div class="tabs_list"><ul>';
            foreach ($tabs as $index => $tab) {
                // Set active class for video tab when type is video, contact form tab when type is contact_form
                $class = '';
                if ($count == 0 && $temp_type !== 'video' && $temp_type !== 'contact_form') {
                    $class = 'active';
                } elseif ($temp_type === 'video' && $index === 'ipb_video') {
                    $class = 'active';
                } elseif ($temp_type === 'contact_form' && $index === 'ipb_contact_form') {
                    $class = 'active';
                } elseif ($temp_type === 'feedback' && $index === 'ipb_feedback') {
                    $class = 'active';
                } elseif ($count == 0 && $temp_type === 'video' && $index !== 'ipb_video') {
                    // Don't make first tab active if video tab exists
                    $class = '';
                } elseif ($count == 0 && $temp_type === 'contact_form' && $index !== 'ipb_contact_form') {
                    $class = '';
                } elseif ($count == 0 && $temp_type === 'feedback' && $index !== 'ipb_feedback') {
                    $class = '';
                } elseif ($count == 0) {
                    $class = 'active';
                }

                $html .= '<li class="' . esc_attr($index ?? '') . ' ' . $class . '" data-id="' . esc_attr($index ?? '') . '">' . ($tab ?? '') . '</li>';
                $count += 1;
            }
            $html .= '</ul></div>';

            return $html;
        }

        /**
         * Generate html for the child tabs
         * @param array $tabs
         * @param string $popup_type Optional popup type for determining active tab
         *
         */

        public static function renderChildHtml($tabs, $popup_type = '')
        {

            $html = '';
            $count = 0;
            if (!$tabs) return false;

            foreach ($tabs as $key => $tab) {
                // Determine active class based on popup type and position
                $class = '';

                // For general tabs, make extension-specific tabs active for their popup types
                if ($popup_type === 'video' && $key === 'video') {
                    $class = 'active';
                } elseif ($popup_type === 'pdf' && $key === 'pdf') {
                    $class = 'active';
                } elseif ($count == 0 && !in_array($popup_type, ['video', 'pdf'])) {
                    // First tab is active for non-extension popup types
                    $class = 'active';
                } elseif ($count == 0 && $popup_type && !isset($tabs[$popup_type])) {
                    // Fallback: first tab active if popup type tab doesn't exist
                    $class = 'active';
                }

                $html .= '<li class="' . esc_attr($key ?? '') . ' ' . esc_attr($class ?? '') . '" data-id="' . esc_attr($key ?? '') . '">' . esc_html($tab ?? '') . '</li>';
                $count += 1;
            }

            return $html;
        }

        public function general_closing_tab_content()
        {

            // return "hello world";
        }
    }

    new Class_instant_setting_edit();
    // Hook initialization to 'init' action with priority 15 to ensure text domain is loaded first (text domain loads at priority 10)
    add_action( 'init', [ '\\Admin\\Settings\\Edit\\Class_instant_setting_edit', 'init' ], 15 );
}
