<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Subscriber management uses plugin-owned tables and template-scope variables.

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

global $wpdb;
$instant_popup_builder_table_name = $wpdb->prefix . 'instant_popup_subscriber';
$instant_popup_builder_table_popup = $wpdb->prefix . 'instant_popup_builder';
$instant_popup_builder_item_per_page = get_option('ipb_subscribers_per_page', 10); // Use user setting
$instant_popup_builder_paged = isset($_GET['pages']) ? intval($_GET['pages']) : 1;

// Enhanced filtering
// Define allowed WHERE conditions as static strings with placeholders
// These are whitelisted static strings - not user input
$instant_popup_builder_where_conditions = array();
$instant_popup_builder_where_values = array();

// Whitelist of allowed WHERE condition patterns (static strings only)
$instant_popup_builder_allowed_conditions = array(
    'campaign' => 'campaign = %d',
    'status' => 'status = %s',
    'privacy' => 'privacy = %s',
    'date_from' => 'DATE(created) >= %s',
    'date_to' => 'DATE(created) <= %s',
    'subscriber_search' => '(emailaddress LIKE %s OR firstname LIKE %s OR lastname LIKE %s)',
);

// Verify nonce for filter form processing
$instant_popup_builder_filter_nonce_verified = false;
if (isset($_POST['ipb_filter_nonce'])) {
    $instant_popup_builder_filter_nonce_verified = wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ipb_filter_nonce'])), 'ipb_filter_action');
}

// Campaign filter
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['filter_campaign']) && !empty($_POST['filter_campaign']) && $_POST['filter_campaign'] !== 'all') {
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['campaign'];
    $instant_popup_builder_where_values[] = intval($_POST['filter_campaign']);
}

// Status filter
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['filter_status']) && !empty($_POST['filter_status']) && $_POST['filter_status'] !== 'all') {
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['status'];
    $instant_popup_builder_where_values[] = sanitize_text_field(wp_unslash($_POST['filter_status']));
}

// Privacy Policy filter
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['filter_privacy']) && !empty($_POST['filter_privacy']) && $_POST['filter_privacy'] !== 'all') {
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['privacy'];
    $instant_popup_builder_where_values[] = sanitize_text_field(wp_unslash($_POST['filter_privacy']));
}

// Date range filter
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['filter_date_from']) && !empty($_POST['filter_date_from'])) {
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['date_from'];
    $instant_popup_builder_where_values[] = sanitize_text_field(wp_unslash($_POST['filter_date_from']));
}
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['filter_date_to']) && !empty($_POST['filter_date_to'])) {
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['date_to'];
    $instant_popup_builder_where_values[] = sanitize_text_field(wp_unslash($_POST['filter_date_to']));
}

// Subscriber search by email, first name, or last name.
if ($instant_popup_builder_filter_nonce_verified && isset($_POST['search_subscribers']) && !empty($_POST['search_subscribers'])) {
    $instant_popup_builder_search_term = '%' . sanitize_text_field(wp_unslash($_POST['search_subscribers'])) . '%';
    $instant_popup_builder_where_conditions[] = $instant_popup_builder_allowed_conditions['subscriber_search'];
    $instant_popup_builder_where_values[] = $instant_popup_builder_search_term;
    $instant_popup_builder_where_values[] = $instant_popup_builder_search_term;
    $instant_popup_builder_where_values[] = $instant_popup_builder_search_term;
}

// Build the WHERE clause from whitelisted static condition strings
$instant_popup_builder_where_clause = '';
if (!empty($instant_popup_builder_where_conditions)) {
    $instant_popup_builder_where_clause = 'WHERE ' . implode(' AND ', is_array($instant_popup_builder_where_conditions) ? $instant_popup_builder_where_conditions : []);
}

// Count total records with filters
$instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
if (!empty($instant_popup_builder_where_values)) {
    // Build query directly - WHERE clause uses whitelisted static condition strings from $instant_popup_builder_allowed_conditions array
    // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
    // The WHERE clause is built from a whitelist of static condition strings (see $instant_popup_builder_allowed_conditions above)
    // All values are properly sanitized and passed to prepare() separately
    $instant_popup_builder_count_query = "SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_table_name}` {$instant_popup_builder_where_clause}";
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Dynamic SQL fragments come exclusively from the static whitelist above.
    $instant_popup_builder_total = $wpdb->get_var($wpdb->prepare($instant_popup_builder_count_query, $instant_popup_builder_where_values));
    // phpcs:enable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
} else {
    $instant_popup_builder_count_query = "SELECT COUNT(*) FROM `{$instant_popup_builder_escaped_table_name}` {$instant_popup_builder_where_clause}";
    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Query contains only an escaped internal table identifier and fixed SQL.
    $instant_popup_builder_total = $wpdb->get_var($instant_popup_builder_count_query);
}

$instant_popup_builder_total_pages = ceil($instant_popup_builder_total / $instant_popup_builder_item_per_page);
$instant_popup_builder_offset = ($instant_popup_builder_paged - 1) * $instant_popup_builder_item_per_page;

// Delete subscriber request
if (isset($_GET['delete']) && !empty($_GET['delete']) && isset($_GET['delete_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['delete_nonce'])), 'delete_subscriber_action')) {
    $instant_popup_builder_id = intval($_GET['delete']);
    $instant_popup_builder_is_del = $wpdb->delete($instant_popup_builder_table_name, ['id' => $instant_popup_builder_id]);
    if ($instant_popup_builder_is_del) {
        echo '<div class="notice notice-success"><p>Subscriber deleted successfully.</p></div>';
    }
}

// Bulk actions
if (isset($_POST['bulk_action']) && isset($_POST['subscriber_ids']) && !empty($_POST['subscriber_ids']) && isset($_POST['ipb_bulk_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ipb_bulk_nonce'])), 'ipb_bulk_action')) {
    $instant_popup_builder_action = sanitize_text_field(wp_unslash($_POST['bulk_action']));
    $instant_popup_builder_ids = array_map('intval', $_POST['subscriber_ids']);

    if ($instant_popup_builder_action === 'delete') {
        $instant_popup_builder_placeholders = implode(',', array_fill(0, count($instant_popup_builder_ids), '%d'));
        $instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
        $instant_popup_builder_query = "DELETE FROM `{$instant_popup_builder_escaped_table_name}` WHERE id IN ($instant_popup_builder_placeholders)";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are generated from the validated integer ID count.
        $instant_popup_builder_deleted = $wpdb->query($wpdb->prepare($instant_popup_builder_query, $instant_popup_builder_ids));
        if ($instant_popup_builder_deleted) {
            echo '<div class="notice notice-success"><p>' . esc_html($instant_popup_builder_deleted) . ' subscribers deleted successfully.</p></div>';
        }
    } elseif ($instant_popup_builder_action === 'subscribe') {
        $instant_popup_builder_placeholders = implode(',', array_fill(0, count($instant_popup_builder_ids), '%d'));
        $instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
        $instant_popup_builder_query = "UPDATE `{$instant_popup_builder_escaped_table_name}` SET status = 'yes' WHERE id IN ($instant_popup_builder_placeholders)";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are generated from the validated integer ID count.
        $instant_popup_builder_updated = $wpdb->query($wpdb->prepare($instant_popup_builder_query, $instant_popup_builder_ids));
        if ($instant_popup_builder_updated) {
            echo '<div class="notice notice-success"><p>' . esc_html($instant_popup_builder_updated) . ' subscribers updated to subscribed.</p></div>';
        }
    } elseif ($instant_popup_builder_action === 'unsubscribe') {
        $instant_popup_builder_placeholders = implode(',', array_fill(0, count($instant_popup_builder_ids), '%d'));
        $instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
        $instant_popup_builder_query = "UPDATE `{$instant_popup_builder_escaped_table_name}` SET status = 'no' WHERE id IN ($instant_popup_builder_placeholders)";
        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are generated from the validated integer ID count.
        $instant_popup_builder_updated = $wpdb->query($wpdb->prepare($instant_popup_builder_query, $instant_popup_builder_ids));
        if ($instant_popup_builder_updated) {
            echo '<div class="notice notice-success"><p>' . esc_html($instant_popup_builder_updated) . ' subscribers updated to unsubscribed.</p></div>';
        }
    } elseif ($instant_popup_builder_action === 'assign_campaign') {
        if (isset($_POST['bulk_campaign_id']) && !empty($_POST['bulk_campaign_id'])) {
            $instant_popup_builder_campaign_id = intval($_POST['bulk_campaign_id']);

            // Verify campaign exists and is of subscription type
            $instant_popup_builder_escaped_table_popup = esc_sql($instant_popup_builder_table_popup);
            $instant_popup_builder_campaign_exists = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM `{$instant_popup_builder_escaped_table_popup}` WHERE id = %d AND type = %s",
                $instant_popup_builder_campaign_id,
                'subscription'
            ));

            if ($instant_popup_builder_campaign_exists) {
                $instant_popup_builder_placeholders = implode(',', array_fill(0, count($instant_popup_builder_ids), '%d'));
                $instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
                $instant_popup_builder_query = "UPDATE `{$instant_popup_builder_escaped_table_name}` SET campaign = %d WHERE id IN ($instant_popup_builder_placeholders)";
                $instant_popup_builder_final_values = array_merge([$instant_popup_builder_campaign_id], $instant_popup_builder_ids);
                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Placeholders are generated from the validated integer ID count.
                $instant_popup_builder_updated = $wpdb->query($wpdb->prepare($instant_popup_builder_query, $instant_popup_builder_final_values));

                if ($instant_popup_builder_updated) {
                    $instant_popup_builder_campaign_name = $wpdb->get_var($wpdb->prepare(
                        "SELECT title FROM `{$instant_popup_builder_escaped_table_popup}` WHERE id = %d",
                        $instant_popup_builder_campaign_id
                    ));
                    echo '<div class="notice notice-success"><p>' . esc_html($instant_popup_builder_updated) . ' subscribers assigned to campaign: ' . esc_html($instant_popup_builder_campaign_name) . '</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>Invalid campaign selected. Please try again.</p></div>';
            }
        } else {
            echo '<div class="notice notice-error"><p>Please select a campaign for assignment.</p></div>';
        }
    }
}

// Get filtered results with optional campaign names
$instant_popup_builder_show_campaign_names = get_option('ipb_show_campaign_names', 1);
$instant_popup_builder_show_date_created = get_option('ipb_show_date_created', 1);

// Get column visibility settings
$instant_popup_builder_show_id_column = get_option('ipb_show_id_column', 1);
$instant_popup_builder_show_name_column = get_option('ipb_show_name_column', 1);
$instant_popup_builder_show_email_column = get_option('ipb_show_email_column', 1);
$instant_popup_builder_show_campaign_column = get_option('ipb_show_campaign_column', 1);
$instant_popup_builder_show_privacy_column = get_option('ipb_show_privacy_column', 1);
$instant_popup_builder_show_status_column = get_option('ipb_show_status_column', 1);
$instant_popup_builder_show_actions_column = get_option('ipb_show_actions_column', 1);

$instant_popup_builder_escaped_table_name = esc_sql($instant_popup_builder_table_name);
$instant_popup_builder_escaped_table_popup = esc_sql($instant_popup_builder_table_popup);
if ($instant_popup_builder_show_campaign_names) {
    // Query with campaign names
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_table_name)) != $instant_popup_builder_table_name) {
        return 0;
    }
    // Build query directly - WHERE clause uses whitelisted static condition strings from $instant_popup_builder_allowed_conditions array
    // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
    // The WHERE clause is built from a whitelist of static condition strings (see $instant_popup_builder_allowed_conditions above)
    // All values are properly sanitized and passed to prepare() separately
    $instant_popup_builder_query = "
        SELECT s.*, p.title as campaign_name
        FROM `{$instant_popup_builder_escaped_table_name}` s
        LEFT JOIN `{$instant_popup_builder_escaped_table_popup}` p ON s.campaign = p.id AND p.type = 'subscription'
        {$instant_popup_builder_where_clause}
        ORDER BY s.created DESC
        LIMIT %d OFFSET %d
    ";
    // phpcs:enable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
} else {
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $instant_popup_builder_table_name)) != $instant_popup_builder_table_name) {
        return 0;
    }
    // Build query directly - WHERE clause uses whitelisted static condition strings from $instant_popup_builder_allowed_conditions array
    // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
    // The WHERE clause is built from a whitelist of static condition strings (see $instant_popup_builder_allowed_conditions above)
    // All values are properly sanitized and passed to prepare() separately
    $instant_popup_builder_query = "SELECT * FROM `{$instant_popup_builder_escaped_table_name}` {$instant_popup_builder_where_clause} ORDER BY created DESC LIMIT %d OFFSET %d";
    // phpcs:enable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare,PluginCheck.Security.DirectDB.UnescapedDBParameter
}

$instant_popup_builder_final_values = array_merge($instant_popup_builder_where_values, array($instant_popup_builder_item_per_page, $instant_popup_builder_offset));
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Dynamic SQL fragments come exclusively from the static whitelist above.
$instant_popup_builder_result = $wpdb->get_results($wpdb->prepare($instant_popup_builder_query, $instant_popup_builder_final_values));

// Get campaigns for filter dropdown
$instant_popup_builder_escaped_table_popup = esc_sql($instant_popup_builder_table_popup);
$instant_popup_builder_campaigns = $wpdb->get_results($wpdb->prepare("SELECT id, title FROM `{$instant_popup_builder_escaped_table_popup}` WHERE type = %s", 'subscription'));

$instant_popup_builder_form_url = admin_url('admin.php?page=instant-subscriber-list');
$instant_popup_builder_export_all_url = wp_nonce_url(
    add_query_arg(
        array(
            'page' => 'instant-subscriber-list',
            'export-subscriber' => 'all',
        ),
        admin_url('admin.php')
    ),
    'ipb_export_subscribers'
);
?>

<?php
if (class_exists('Instant_Popup_Builder_Admin')) {
    Instant_Popup_Builder_Admin::ipb_top_header();
}
// Add New Subscriber page is only registered by Subscription Pro when active and licensed.
$instant_popup_builder_can_add_new = (get_option('subscription_license_active') === 'yes' && get_option('instant_popup_subscription_activated') === 'yes');
$instant_popup_builder_add_new_page = $instant_popup_builder_can_add_new ? admin_url('admin.php?page=instant-subscriber-add-new') : '';
?>

<div class="wrap instant_popup ipb_subscription_wrapper">
    <div class="wrapper">
        <h1 class="wp-heading-inline"><?php esc_html_e('Subscribers', 'instant-popup-builder'); ?></h1>
        <a href="#ipb_add_subscriber_modal" rel="modal:open" class="page-title-action">
            <?php esc_html_e('Add New', 'instant-popup-builder'); ?>
        </a>
        <a href="<?php echo esc_url($instant_popup_builder_export_all_url); ?>" class="page-title-action">
            <?php esc_html_e('Export Subscribers', 'instant-popup-builder'); ?>
        </a>
        <?php do_action('ipb_subscribers_page_title_actions'); ?>
        <hr class="wp-header-end">

        <!-- Settings Success Message -->
        <?php if (isset($_GET['settings_updated']) && $_GET['settings_updated'] == '1'): ?>
            <div class="notice notice-success is-dismissible">
                <p><strong>Settings saved successfully!</strong> Your subscriber list preferences have been updated.</p>
            </div>
        <?php endif; ?>

        <!-- Enhanced Filters Section -->
        <div class="ipb_filters_section wp-filter">
            <form method="post" class="ipb_filters_form">
                <div class="ipb_filters_row ipb_filters_row_single">
                    <div class="ipb_filter_group">
                        <label for="filter_campaign">Campaign</label>
                        <select name="filter_campaign" id="filter_campaign">
                            <option value="all">All Campaigns</option>
                            <?php foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign): ?>
                                <option value="<?php echo esc_attr($instant_popup_builder_campaign->id ?? ''); ?>"
                                    <?php
                                    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                                    selected(isset($_POST['filter_campaign']) ? sanitize_text_field(wp_unslash($_POST['filter_campaign'])) : '', $instant_popup_builder_campaign->id ?? '');
                                    ?>>
                                    <?php echo esc_html($instant_popup_builder_campaign->title ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="ipb_filter_group">
                        <label for="filter_status">Status</label>
                        <select name="filter_status" id="filter_status">
                            <option value="all">All Status</option>
                            <?php
                            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                            $instant_popup_builder_filter_status = isset($_POST['filter_status']) ? sanitize_text_field(wp_unslash($_POST['filter_status'])) : '';
                            ?>
                            <option value="yes" <?php selected($instant_popup_builder_filter_status, 'yes'); ?>>Subscribed</option>
                            <option value="no" <?php selected($instant_popup_builder_filter_status, 'no'); ?>>Unsubscribed</option>
                        </select>
                    </div>

                    <div class="ipb_filter_group">
                        <label for="filter_privacy">Privacy Policy</label>
                        <select name="filter_privacy" id="filter_privacy">
                            <option value="all">All</option>
                            <?php
                            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                            $instant_popup_builder_filter_privacy = isset($_POST['filter_privacy']) ? sanitize_text_field(wp_unslash($_POST['filter_privacy'])) : '';
                            ?>
                            <option value="yes" <?php selected($instant_popup_builder_filter_privacy, 'yes'); ?>>Agreed</option>
                            <option value="no" <?php selected($instant_popup_builder_filter_privacy, 'no'); ?>>Not Agreed</option>
                        </select>
                    </div>

                    <div class="ipb_filter_group">
                        <label for="filter_date_from">Date From</label>
                        <input type="date" name="filter_date_from" id="filter_date_from"
                               value="<?php
                               // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                               echo isset($_POST['filter_date_from']) ? esc_attr(sanitize_text_field(wp_unslash($_POST['filter_date_from']))) : '';
                               ?>">
                    </div>

                    <div class="ipb_filter_group">
                        <label for="filter_date_to">Date To</label>
                        <input type="date" name="filter_date_to" id="filter_date_to"
                               value="<?php
                               // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                               echo isset($_POST['filter_date_to']) ? esc_attr(sanitize_text_field(wp_unslash($_POST['filter_date_to']))) : '';
                               ?>">
                    </div>

                    <div class="ipb_filter_group ipb_search_group">
                        <label for="search_subscribers">Search Subscribers</label>
                        <input type="search" name="search_subscribers" id="search_subscribers"
                               placeholder="Email, first name, or last name"
                               value="<?php
                               // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Display only, value is sanitized
                               echo isset($_POST['search_subscribers']) ? esc_attr(sanitize_text_field(wp_unslash($_POST['search_subscribers']))) : '';
                               ?>">
                    </div>

                    <div class="ipb_filter_actions">
                        <button type="submit" name="apply_filters" class="button button-primary">Apply Filters</button>
                        <a href="<?php echo esc_url($instant_popup_builder_form_url); ?>" class="button">Clear Filters</a>
                    </div>
                </div>
                <?php wp_nonce_field('ipb_filter_action', 'ipb_filter_nonce'); ?>
            </form>
        </div>

        <!-- Enhanced Import Modal -->
        <div id="ipb_import_modal" class="modal ipb_enhanced_modal">
            <div class="ipb_modal_content">
                <div class="ipb_modal_header">
                    <h3>Import Subscribers</h3>
                    <a href="#" rel="modal:close" class="ipb_modal_close">&times;</a>
                </div>
                <form method="post" enctype="multipart/form-data" class="ipb_import_form">
                    <div class="ipb_modal_body">
                        <div class="ipb_import_options">
                            <div class="ipb_file_upload_area">
                                <i class="fa-solid fa-cloud-arrow-up"></i>
                                <p>Choose CSV or XLSX file to upload</p>
                                <input type="file" name="sub_csv_file" accept=".csv,.xlsx" required>
                            </div>



                            <div class="ipb_import_settings">
                                <h4>Import Settings</h4>
                                <label class="ipb_checkbox_label">
                                    <input type="checkbox" name="check_duplicates" value="1" checked>
                                    <span class="checkmark"></span>
                                    Check for duplicate emails
                                </label>
                                <label class="ipb_checkbox_label">
                                    <input type="checkbox" name="skip_invalid" value="1" checked>
                                    <span class="checkmark"></span>
                                    Skip invalid email addresses
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="ipb_modal_footer">
                        <button type="button" rel="modal:close" class="ipb_btn ipb_btn_secondary">Cancel</button>
                        <button type="submit" name="sub_import_csv" class="ipb_btn ipb_btn_primary">Import Subscribers</button>
            </div>
                    <?php wp_nonce_field('ipb_import_action', 'ipb_import_nonce'); ?>
                </form>
            </div>
        </div>

        <!-- Settings Modal -->

        <!-- Bulk Actions -->
        <form method="post" id="ipb_bulk_form">
            <div class="tablenav top">
            <div class="alignleft actions bulkactions ipb_bulk_actions">
                <select name="bulk_action" id="bulk_action">
                    <option value="">Bulk Actions</option>
                    <option value="delete">Delete</option>
                    <option value="subscribe">Mark as Subscribed</option>
                    <option value="unsubscribe">Mark as Unsubscribed</option>
                    <option value="assign_campaign">Assign to Campaign</option>
                </select>

                <!-- Campaign Selection (hidden by default) -->
                <div id="campaign_selection" class="ipb_campaign_selection" style="display: none;">
                    <select name="bulk_campaign_id" id="bulk_campaign_id">
                        <option value="">Select Campaign</option>
                        <?php foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign): ?>
                            <option value="<?php echo esc_attr($instant_popup_builder_campaign->id ?? ''); ?>">
                                <?php echo esc_html($instant_popup_builder_campaign->title ?? ''); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="ipb_campaign_help">Choose the campaign to assign selected subscribers to</small>
                </div>

                <button type="submit" class="button action" onclick="return confirm('Are you sure you want to perform this action?')">Apply</button>
            </div>
            <div class="tablenav-pages one-page">
                <span class="displaying-num"><?php echo esc_html($instant_popup_builder_total); ?> <?php esc_html_e('subscribers', 'instant-popup-builder'); ?></span>
            </div>
            </div>

            <!-- Enhanced Table -->
            <div class="ipb_table_container">
                <table class="wp-list-table widefat fixed striped table-view-list ipb_subscribers_table">
                <thead>
                        <tr>
                            <th class="ipb_checkbox_column">
                                <input type="checkbox" id="select_all_subscribers">
                            </th>
                            <?php if ($instant_popup_builder_show_id_column): ?>
                                <th class="ipb_sortable" data-sort="id">ID</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_name_column): ?>
                                <th class="ipb_sortable" data-sort="name">Name</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_email_column): ?>
                                <th class="ipb_sortable" data-sort="email">Email</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_campaign_column): ?>
                                <th class="ipb_sortable" data-sort="campaign">Campaign</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_privacy_column): ?>
                                <th class="ipb_sortable" data-sort="privacy">Privacy Policy</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_status_column): ?>
                                <th class="ipb_sortable" data-sort="status">Status</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_date_created): ?>
                                <th class="ipb_sortable" data-sort="created">Date Subscribed</th>
                            <?php endif; ?>
                            <?php if ($instant_popup_builder_show_actions_column): ?>
                                <th class="ipb_actions_column">Actions</th>
                            <?php endif; ?>
                        </tr>
                </thead>
                <tbody>
                        <?php if ($instant_popup_builder_result): ?>
                            <?php foreach ($instant_popup_builder_result as $instant_popup_builder_index => $instant_popup_builder_row):
                                $instant_popup_builder_date = gmdate('M d, Y', strtotime($instant_popup_builder_row->created));
                                $safe_firstname = (string) ( $instant_popup_builder_row->firstname ?? '' );
                                $safe_lastname = (string) ( $instant_popup_builder_row->lastname ?? '' );
                                $instant_popup_builder_full_name = trim(ucfirst($safe_firstname) . ' ' . ucfirst($safe_lastname));

                                // Get campaign name based on settings
                                $instant_popup_builder_campaign_display = '';
                                if ($instant_popup_builder_show_campaign_names && isset($instant_popup_builder_row->campaign_name)) {
                                    $instant_popup_builder_campaign_display = $instant_popup_builder_row->campaign_name;
                                } elseif ($instant_popup_builder_show_campaign_names) {
                                    // Fallback if campaign_name not in query
                                    $instant_popup_builder_escaped_table_popup = esc_sql($instant_popup_builder_table_popup);
                                    $instant_popup_builder_campaign_display = $wpdb->get_var($wpdb->prepare("SELECT title FROM `{$instant_popup_builder_escaped_table_popup}` WHERE id=%d AND type='subscription'", intval($instant_popup_builder_row->campaign)));
                                } else {
                                    $instant_popup_builder_campaign_display = 'ID: ' . $instant_popup_builder_row->campaign;
                                }
                            ?>
                                <tr class="ipb_subscriber_row">
                                    <td>
                                        <input type="checkbox" name="subscriber_ids[]" value="<?php echo esc_attr($instant_popup_builder_row->id); ?>" class="subscriber_checkbox">
                                    </td>
                                    <?php if ($instant_popup_builder_show_id_column): ?>
                                        <td><?php echo esc_html($instant_popup_builder_row->id); ?></td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_name_column): ?>
                                        <td class="ipb_name_cell">
                                            <div class="ipb_subscriber_info">
                                                <div class="ipb_subscriber_avatar">
                                                    <?php
                                                    $safe_firstname_initial = is_string($instant_popup_builder_row->firstname) ? (string) $instant_popup_builder_row->firstname : '';
                                                    $safe_lastname_initial = is_string($instant_popup_builder_row->lastname) ? (string) $instant_popup_builder_row->lastname : '';
                                                    $first_initial = substr($safe_firstname_initial, 0, 1);
                                                    $last_initial = substr($safe_lastname_initial, 0, 1);
                                                    echo esc_html(strtoupper($first_initial . $last_initial));
                                                    ?>
                                                </div>
                                                <div class="ipb_subscriber_details">
                                                    <strong><?php echo esc_html($instant_popup_builder_full_name); ?></strong>
                                                </div>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_email_column): ?>
                                        <td class="ipb_email_cell">
                                            <div class="ipb_email_with_status">
                                                <?php echo esc_html($instant_popup_builder_row->emailaddress); ?>
                                                <span class="ipb_email_status <?php echo $instant_popup_builder_row->status === 'yes' ? 'ipb_active' : 'ipb_inactive'; ?>">
                                                    <i class="fa-solid <?php echo $instant_popup_builder_row->status === 'yes' ? 'fa-check-circle' : 'fa-times-circle'; ?>"></i>
                                                </span>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_campaign_column): ?>
                                        <td class="ipb_campaign_cell">
                                            <?php if ($instant_popup_builder_campaign_display): ?>
                                                <span class="ipb_campaign_badge"><?php echo esc_html($instant_popup_builder_campaign_display); ?></span>
                                            <?php else: ?>
                                                <span class="ipb_no_campaign">No Campaign</span>
                                            <?php endif; ?>
                                        </td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_privacy_column): ?>
                                        <td class="ipb_privacy_cell">
                                            <span class="ipb_privacy_status <?php echo $instant_popup_builder_row->privacy === 'yes' ? 'ipb_agreed' : 'ipb_not_agreed'; ?>">
                                                <i class="fa-solid <?php echo $instant_popup_builder_row->privacy === 'yes' ? 'fa-shield-check' : 'fa-shield-xmark'; ?>"></i>
                                                <?php echo $instant_popup_builder_row->privacy === 'yes' ? 'Yes' : 'No'; ?>
                                            </span>
                                        </td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_status_column): ?>
                                        <td class="ipb_status_cell">
                                            <span class="ipb_subscription_status <?php echo $instant_popup_builder_row->status === 'yes' ? 'ipb_subscribed' : 'ipb_unsubscribed'; ?>">
                                                <?php echo $instant_popup_builder_row->status === 'yes' ? 'Subscribed' : 'Unsubscribed'; ?>
                                            </span>
                                        </td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_date_created): ?>
                                        <td class="ipb_date_cell"><?php echo esc_html($instant_popup_builder_date); ?></td>
                                    <?php endif; ?>
                                    <?php if ($instant_popup_builder_show_actions_column): ?>
                                        <td class="ipb_actions_cell">
                                            <div class="ipb_action_buttons">
                                                <a href="#ipb_edit_subscriber_modal"
                                                   rel="modal:open"
                                                   class="ipb_action_btn ipb_edit_btn ipb_edit_subscriber_btn"
                                                   title="Edit"
                                                   data-id="<?php echo esc_attr($instant_popup_builder_row->id); ?>"
                                                   data-firstname="<?php echo esc_attr($instant_popup_builder_row->firstname); ?>"
                                                   data-lastname="<?php echo esc_attr($instant_popup_builder_row->lastname); ?>"
                                                   data-email="<?php echo esc_attr($instant_popup_builder_row->emailaddress); ?>"
                                                   data-campaign="<?php echo esc_attr($instant_popup_builder_row->campaign); ?>"
                                                   data-status="<?php echo esc_attr($instant_popup_builder_row->status); ?>"
                                                   data-privacy="<?php echo esc_attr($instant_popup_builder_row->privacy); ?>"
                                                   data-created="<?php echo esc_attr($instant_popup_builder_row->created); ?>">
                                                    <i class="fa-solid fa-edit"></i>
                                                </a>
                                                <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(array('export-subscriber' => 'single', 'id' => $instant_popup_builder_row->id), $instant_popup_builder_form_url), 'ipb_export_subscriber_' . $instant_popup_builder_row->id)); ?>"
                                                   class="ipb_action_btn ipb_export_btn" title="Export">
                                                    <i class="fa-solid fa-download"></i>
                                                </a>
                                                <a href="<?php echo esc_url(add_query_arg(array('delete' => $instant_popup_builder_row->id, 'delete_nonce' => wp_create_nonce('delete_subscriber_action')), $instant_popup_builder_form_url)); ?>"
                                                   class="ipb_action_btn ipb_delete_btn" title="Delete"
                                                   onclick="return confirm('Are you sure you want to delete this subscriber?')">
                                                    <i class="fa-solid fa-trash"></i>
                                                </a>
                                            </div>
                                        </td>
                                    <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="<?php
                                    $instant_popup_builder_visible_columns = 1; // Checkbox column is always visible
                                    if ($instant_popup_builder_show_id_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_name_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_email_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_campaign_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_privacy_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_status_column) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_date_created) $instant_popup_builder_visible_columns++;
                                    if ($instant_popup_builder_show_actions_column) $instant_popup_builder_visible_columns++;
                                    echo esc_html($instant_popup_builder_visible_columns);
                                ?>" class="ipb_no_data">
                                    <div class="ipb_empty_state">
                                        <i class="fa-solid fa-users"></i>
                                        <h3>No Subscribers Found</h3>
                                        <p>Try adjusting your filters or add your first subscriber.</p>
                                        <?php if (!empty($instant_popup_builder_add_new_page)) : ?>
                                            <a href="<?php echo esc_url($instant_popup_builder_add_new_page); ?>" class="ipb_btn ipb_btn_primary">Add First Subscriber</a>
                                        <?php else : ?>
                                            <a href="<?php echo esc_url(admin_url('admin.php?page=upgrade-instant-popup')); ?>" class="ipb_btn ipb_btn_primary">Upgrade to Pro to add subscribers</a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endif; ?>
                </tbody>
            </table>
        </div>
            <?php wp_nonce_field('ipb_bulk_action', 'ipb_bulk_nonce'); ?>
        </form>

        <!-- Enhanced Pagination -->
        <?php if ($instant_popup_builder_total_pages > 1): ?>
            <div class="tablenav bottom ipb_pagination_wrapper">
                <div class="alignleft ipb_pagination_info">
                    Showing <?php echo esc_html((($instant_popup_builder_paged - 1) * $instant_popup_builder_item_per_page + 1)); ?> to <?php echo esc_html(min($instant_popup_builder_paged * $instant_popup_builder_item_per_page, $instant_popup_builder_total)); ?> of <?php echo esc_html($instant_popup_builder_total); ?> subscribers
                </div>
                <div class="tablenav-pages ipb_pagination">
        <?php
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- paginate_links() returns safe HTML
        echo paginate_links(array(
            'base' => add_query_arg('pages', '%#%'),
            'format' => '',
                        'prev_text' => '<i class="fa-solid fa-chevron-left"></i> Previous',
                        'next_text' => 'Next <i class="fa-solid fa-chevron-right"></i>',
            'total' => $instant_popup_builder_total_pages,
                        'current' => $instant_popup_builder_paged,
                        'mid_size' => 2,
                        'end_size' => 1,
                    ));
                    ?>
                </div>
            </div>
        <?php endif; ?>
        <!-- Add Subscriber Modal -->
        <div id="ipb_add_subscriber_modal" class="modal ipb_enhanced_modal ipb_subscriber_modal">
            <div class="ipb_modal_content">
                <div class="ipb_modal_header">
                    <h3><i class="fa-solid fa-user-plus"></i> Add New Subscriber</h3>
                    <a href="#" rel="modal:close" class="ipb_modal_close">&times;</a>
                </div>
                <form id="ipb_add_subscriber_form" class="ipb_subscriber_form">
                    <div class="ipb_modal_body">
                        <div class="ipb_form_sections">
                            <!-- Basic Information Section -->
                            <div class="ipb_form_section">
                                <div class="ipb_section_header">
                                    <h4><i class="fa-solid fa-user"></i> Basic Information</h4>
                                </div>

                                <div class="ipb_form_grid">
                                    <div class="ipb_form_group">
                                        <label for="add_firstname" class="ipb_form_label">
                                            First Name <span class="required">*</span>
                                        </label>
                                        <input type="text"
                                               required
                                               name="sub_firstname"
                                               id="add_firstname"
                                               class="ipb_form_input"
                                               placeholder="Enter first name">
                                        <div class="ipb_field_error" id="add_firstname_error"></div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label for="add_lastname" class="ipb_form_label">
                                            Last Name <span class="required">*</span>
                                        </label>
                                        <input type="text"
                                               required
                                               name="sub_lastname"
                                               id="add_lastname"
                                               class="ipb_form_input"
                                               placeholder="Enter last name">
                                        <div class="ipb_field_error" id="add_lastname_error"></div>
                                    </div>

                                    <div class="ipb_form_group ipb_form_group_full">
                                        <label for="add_emailaddress" class="ipb_form_label">
                                            Email Address <span class="required">*</span>
                                        </label>
                                        <input type="email"
                                               required
                                               name="sub_emailaddress"
                                               id="add_emailaddress"
                                               class="ipb_form_input"
                                               placeholder="Enter email address">
                                        <div class="ipb_field_error" id="add_email_error"></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Campaign & Settings Section -->
                            <div class="ipb_form_section">
                                <div class="ipb_section_header">
                                    <h4><i class="fa-solid fa-bullhorn"></i> Campaign & Settings</h4>
                                </div>

                                <div class="ipb_form_grid">
                                    <div class="ipb_form_group ipb_form_group_full">
                                        <label for="add_campaign" class="ipb_form_label">
                                            Campaign <span class="required">*</span>
                                        </label>
                                        <select name="ipb_sub_campaign" id="add_campaign" class="ipb_form_select" required>
                                            <option value="" disabled selected>Choose a campaign</option>
                                            <?php foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign): ?>
                                                <option value="<?php echo esc_attr($instant_popup_builder_campaign->id ?? ''); ?>">
                                                    <?php echo esc_html($instant_popup_builder_campaign->title ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="ipb_field_error" id="add_campaign_error"></div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Subscription Status</label>
                                        <div class="ipb_toggle_container">
                                            <div class="ipb_toggle_switch">
                                                <input type="checkbox"
                                                       checked
                                                       name="popup_status_toggle"
                                                       id="add_status_toggle"
                                                       value="yes">
                                                <label for="add_status_toggle" class="ipb_toggle_label">
                                                    <span class="ipb_toggle_slider"></span>
                                                </label>
                                            </div>
                                            <span class="ipb_toggle_text">
                                                <span class="status-text">Subscribed</span>
                                            </span>
                                        </div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Privacy Policy Agreement</label>
                                        <div class="ipb_toggle_container">
                                            <div class="ipb_toggle_switch">
                                                <input type="checkbox"
                                                       name="popup_privacy_toggle"
                                                       id="add_privacy_toggle"
                                                       value="no">
                                                <label for="add_privacy_toggle" class="ipb_toggle_label">
                                                    <span class="ipb_toggle_slider"></span>
                                                </label>
                                            </div>
                                            <span class="ipb_toggle_text">
                                                <span class="privacy-text">Not Agreed</span>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="ipb_modal_footer">
                        <button type="button" rel="modal:close" class="ipb_btn ipb_btn_secondary">Cancel</button>
                        <button type="submit" class="ipb_btn ipb_btn_primary">
                            <i class="fa-solid fa-plus"></i> Add Subscriber
                        </button>
                    </div>
                    <?php wp_nonce_field('ipb_subscriber_action', 'ipb_subscriber_nonce'); ?>
                </form>
            </div>
        </div>

        <!-- Edit Subscriber Modal -->
        <div id="ipb_edit_subscriber_modal" class="modal ipb_enhanced_modal ipb_subscriber_modal">
            <div class="ipb_modal_content">
                <div class="ipb_modal_header">
                    <h3><i class="fa-solid fa-user-edit"></i> Edit Subscriber</h3>
                    <a href="#" rel="modal:close" class="ipb_modal_close">&times;</a>
                </div>
                <form id="ipb_edit_subscriber_form" class="ipb_subscriber_form">
                    <div class="ipb_modal_body">
                        <div class="ipb_form_sections">
                            <!-- Basic Information Section -->
                            <div class="ipb_form_section">
                                <div class="ipb_section_header">
                                    <h4><i class="fa-solid fa-user"></i> Basic Information</h4>
                                </div>

                                <div class="ipb_form_grid">
                                    <div class="ipb_form_group">
                                        <label for="edit_firstname" class="ipb_form_label">
                                            First Name <span class="required">*</span>
                                        </label>
                                        <input type="text"
                                               required
                                               name="sub_firstname"
                                               id="edit_firstname"
                                               class="ipb_form_input"
                                               placeholder="Enter first name">
                                        <div class="ipb_field_error" id="edit_firstname_error"></div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label for="edit_lastname" class="ipb_form_label">
                                            Last Name <span class="required">*</span>
                                        </label>
                                        <input type="text"
                                               required
                                               name="sub_lastname"
                                               id="edit_lastname"
                                               class="ipb_form_input"
                                               placeholder="Enter last name">
                                        <div class="ipb_field_error" id="edit_lastname_error"></div>
                                    </div>

                                    <div class="ipb_form_group ipb_form_group_full">
                                        <label for="edit_emailaddress" class="ipb_form_label">
                                            Email Address <span class="required">*</span>
                                        </label>
                                        <input type="email"
                                               required
                                               name="sub_emailaddress"
                                               id="edit_emailaddress"
                                               class="ipb_form_input"
                                               placeholder="Enter email address">
                                        <div class="ipb_field_error" id="edit_email_error"></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Campaign & Settings Section -->
                            <div class="ipb_form_section">
                                <div class="ipb_section_header">
                                    <h4><i class="fa-solid fa-bullhorn"></i> Campaign & Settings</h4>
                                </div>

                                <div class="ipb_form_grid">
                                    <div class="ipb_form_group ipb_form_group_full">
                                        <label for="edit_campaign" class="ipb_form_label">
                                            Campaign <span class="required">*</span>
                                        </label>
                                        <select name="ipb_sub_campaign" id="edit_campaign" class="ipb_form_select" required>
                                            <option value="" disabled>Choose a campaign</option>
                                            <?php foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign): ?>
                                                <option value="<?php echo esc_attr($instant_popup_builder_campaign->id ?? ''); ?>">
                                                    <?php echo esc_html($instant_popup_builder_campaign->title ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="ipb_field_error" id="edit_campaign_error"></div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Subscription Status</label>
                                        <div class="ipb_toggle_container">
                                            <div class="ipb_toggle_switch">
                                                <input type="checkbox"
                                                       name="popup_status_toggle"
                                                       id="edit_status_toggle"
                                                       value="yes">
                                                <label for="edit_status_toggle" class="ipb_toggle_label">
                                                    <span class="ipb_toggle_slider"></span>
                                                </label>
                                            </div>
                                            <span class="ipb_toggle_text">
                                                <span class="status-text">Subscribed</span>
                                            </span>
                                        </div>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Privacy Policy Agreement</label>
                                        <div class="ipb_toggle_container">
                                            <div class="ipb_toggle_switch">
                                                <input type="checkbox"
                                                       name="popup_privacy_toggle"
                                                       id="edit_privacy_toggle"
                                                       value="no">
                                                <label for="edit_privacy_toggle" class="ipb_toggle_label">
                                                    <span class="ipb_toggle_slider"></span>
                                                </label>
                                            </div>
                                            <span class="ipb_toggle_text">
                                                <span class="privacy-text">Not Agreed</span>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Information Section -->
                            <div class="ipb_form_section">
                                <div class="ipb_section_header">
                                    <h4><i class="fa-solid fa-info-circle"></i> Additional Information</h4>
                                </div>

                                <div class="ipb_form_grid">
                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Subscriber ID</label>
                                        <input type="text"
                                               id="edit_subscriber_id"
                                               class="ipb_form_input"
                                               readonly>
                                    </div>

                                    <div class="ipb_form_group">
                                        <label class="ipb_form_label">Date Subscribed</label>
                                        <input type="text"
                                               id="edit_date_subscribed"
                                               class="ipb_form_input"
                                               readonly>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="ipb_modal_footer">
                        <button type="button" rel="modal:close" class="ipb_btn ipb_btn_secondary">Cancel</button>
                        <button type="submit" class="ipb_btn ipb_btn_primary">
                            <i class="fa-solid fa-save"></i> Update Subscriber
                        </button>
                    </div>
                    <input type="hidden" name="sub_edit_id" id="edit_hidden_id">
                    <input type="hidden" name="sub_edit" value="sub-edit">
                    <?php wp_nonce_field('ipb_subscriber_action', 'ipb_subscriber_nonce'); ?>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Select all functionality
    $('#select_all_subscribers').change(function() {
        $('.subscriber_checkbox').prop('checked', this.checked);
    });

    // Individual checkbox change
    $('.subscriber_checkbox').change(function() {
        if (!this.checked) {
            $('#select_all_subscribers').prop('checked', false);
        }
        var total = $('.subscriber_checkbox').length;
        var checked = $('.subscriber_checkbox:checked').length;
        if (total === checked) {
            $('#select_all_subscribers').prop('checked', true);
        }
    });

    // Bulk action validation
    $('#ipb_bulk_form').submit(function(e) {
        var action = $('#bulk_action').val();
        var checked = $('.subscriber_checkbox:checked').length;

        if (!action) {
            alert('Please select a bulk action.');
            e.preventDefault();
            return false;
        }

        if (checked === 0) {
            alert('Please select at least one subscriber.');
            e.preventDefault();
            return false;
        }

        // Handle campaign assignment action
        if (action === 'assign_campaign') {
            var campaignId = $('#bulk_campaign_id').val();
            if (campaignId === '') {
                alert('Please select a campaign for assignment.');
                e.preventDefault();
                return false;
            }
        }
    });

    // Enhanced search with debounce
    let searchTimeout;
    $('#search_subscribers').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            // Auto-submit could be implemented here if desired
        }, 500);
    });

    // Handle campaign selection visibility
    $('#bulk_action').change(function() {
        var selectedAction = $(this).val();
        var campaignSelectionDiv = $('#campaign_selection');

        if (selectedAction === 'assign_campaign') {
            campaignSelectionDiv.show();
            updateSelectedCount();
        } else {
            campaignSelectionDiv.hide();
            $('#bulk_campaign_id').val(''); // Clear campaign selection if action changes
        }
    });

    // Update selected count for campaign assignment
    function updateSelectedCount() {
        var checked = $('.subscriber_checkbox:checked').length;
        var helpText = $('.ipb_campaign_help');
        if (checked > 0) {
            helpText.text('Choose the campaign to assign ' + checked + ' selected subscriber' + (checked > 1 ? 's' : '') + ' to');
        } else {
            helpText.text('Choose the campaign to assign selected subscribers to');
        }
    }

    // Update count when checkboxes change
    $('.subscriber_checkbox').change(function() {
        if ($('#bulk_action').val() === 'assign_campaign') {
            updateSelectedCount();
        }
    });
});

// Reset column visibility to defaults
function resetColumnVisibility() {
    if (confirm('Are you sure you want to reset all column visibility settings to their default values?')) {
        // Reset all column checkboxes to checked (default)
        document.querySelectorAll('input[name^="show_"]').forEach(function(checkbox) {
            checkbox.checked = true;
        });

        // Show success message
        alert('Column visibility settings have been reset to defaults. Click "Save Settings" to apply the changes.');
    }
}
</script>
