<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Template variables and plugin-owned tables are intentionally local to this partial.
/**
 * Auto Responder Tab Content
 *
 * Configure automated email responses for subscription popups
 */

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

// Handle form submissions
if (isset($_POST['submit_autoresponder'])) {
    if (isset($_POST['autoresponder_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['autoresponder_nonce'])), 'save_autoresponder_settings')) {
        // Sanitize and validate input
        $instant_popup_builder_autoresponder_data = [
            'title' => isset($_POST['autoresponder_title']) ? sanitize_text_field(wp_unslash($_POST['autoresponder_title'])) : '',
            'status' => isset($_POST['autoresponder_status']) ? 'active' : 'inactive',
            'trigger_rules' => isset($_POST['trigger_rules']) ? array_map('sanitize_text_field', wp_unslash($_POST['trigger_rules'])) : [],
            'campaign_ids' => isset($_POST['campaign_ids']) ? array_map('intval', $_POST['campaign_ids']) : [],
            'sender_name' => isset($_POST['sender_name']) ? sanitize_text_field(wp_unslash($_POST['sender_name'])) : '',
            'sender_email' => isset($_POST['sender_email']) ? sanitize_email(wp_unslash($_POST['sender_email'])) : '',
            'reply_to_email' => isset($_POST['reply_to_email']) ? sanitize_email(wp_unslash($_POST['reply_to_email'])) : '',
            'disable_reply' => isset($_POST['disable_reply']) ? '1' : '0',
            'template_id' => isset($_POST['template_id']) ? intval($_POST['template_id']) : 0,
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql')
        ];

        // Validate required fields
        $errors = [];
        if (empty($instant_popup_builder_autoresponder_data['title'])) {
            $errors[] = 'Title is required.';
        }
        if (empty($instant_popup_builder_autoresponder_data['trigger_rules'])) {
            $errors[] = 'At least one trigger rule must be selected.';
        }
        if (empty($instant_popup_builder_autoresponder_data['campaign_ids'])) {
            $errors[] = 'At least one campaign association is required.';
        }
        if (empty($instant_popup_builder_autoresponder_data['sender_name'])) {
            $errors[] = 'Sender name is required.';
        }
        if (empty($instant_popup_builder_autoresponder_data['sender_email']) || !is_email($instant_popup_builder_autoresponder_data['sender_email'])) {
            $errors[] = 'Valid sender email is required.';
        }

        if (!empty($errors)) {
            $error_message = implode('<br>', is_array($errors) ? $errors : []);
            $error_message = is_string($error_message) ? $error_message : '';
            echo '<div class="notice notice-error"><p>' . wp_kses_post($error_message) . '</p></div>';
        } else {
            // Save autoresponder data
            global $wpdb;
            $instant_popup_builder_autoresponders_table = $wpdb->prefix . 'instant_popup_autoresponders';

            // Ensure table exists
            $instant_popup_builder_autoresponder_id = isset($_POST['autoresponder_id']) ? intval($_POST['autoresponder_id']) : 0;

            if ($instant_popup_builder_autoresponder_id > 0) {
                // Update existing autoresponder
                $instant_popup_builder_result = $wpdb->update(
                    $instant_popup_builder_autoresponders_table,
                    [
                        'title' => $instant_popup_builder_autoresponder_data['title'],
                        'status' => $instant_popup_builder_autoresponder_data['status'],
                        'trigger_rules' => json_encode($instant_popup_builder_autoresponder_data['trigger_rules']),
                        'campaign_ids' => json_encode($instant_popup_builder_autoresponder_data['campaign_ids']),
                        'sender_name' => $instant_popup_builder_autoresponder_data['sender_name'],
                        'sender_email' => $instant_popup_builder_autoresponder_data['sender_email'],
                        'reply_to_email' => $instant_popup_builder_autoresponder_data['reply_to_email'],
                        'disable_reply' => $instant_popup_builder_autoresponder_data['disable_reply'],
                        'template_id' => $instant_popup_builder_autoresponder_data['template_id'],
                        'updated_at' => $instant_popup_builder_autoresponder_data['updated_at']
                    ],
                    ['id' => $instant_popup_builder_autoresponder_id],
                    ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s'],
                    ['%d']
                );

                if ($instant_popup_builder_result !== false) {
                    echo '<div class="notice notice-success"><p>Auto Responder "' . esc_html($instant_popup_builder_autoresponder_data['title']) . '" updated successfully!</p></div>';
                } else {
                    echo '<div class="notice notice-error"><p>Failed to update Auto Responder. Please try again.</p></div>';
                }
            } else {
                // Create new autoresponder
                $instant_popup_builder_result = $wpdb->insert(
                    $instant_popup_builder_autoresponders_table,
                    [
                        'title' => $instant_popup_builder_autoresponder_data['title'],
                        'status' => $instant_popup_builder_autoresponder_data['status'],
                        'trigger_rules' => json_encode($instant_popup_builder_autoresponder_data['trigger_rules']),
                        'campaign_ids' => json_encode($instant_popup_builder_autoresponder_data['campaign_ids']),
                        'sender_name' => $instant_popup_builder_autoresponder_data['sender_name'],
                        'sender_email' => $instant_popup_builder_autoresponder_data['sender_email'],
                        'reply_to_email' => $instant_popup_builder_autoresponder_data['reply_to_email'],
                        'disable_reply' => $instant_popup_builder_autoresponder_data['disable_reply'],
                        'template_id' => $instant_popup_builder_autoresponder_data['template_id'],
                        'created_by' => get_current_user_id(),
                        'created_at' => $instant_popup_builder_autoresponder_data['created_at'],
                        'updated_at' => $instant_popup_builder_autoresponder_data['updated_at']
                    ],
                    ['%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s']
                );

                if ($instant_popup_builder_result) {
                    echo '<div class="notice notice-success"><p>Auto Responder "' . esc_html($instant_popup_builder_autoresponder_data['title']) . '" created successfully!</p></div>';
                } else {
                    $instant_popup_builder_db_error = $wpdb->last_error;
                    echo '<div class="notice notice-error"><p>Failed to create Auto Responder. Database error: ' . esc_html($instant_popup_builder_db_error) . '</p></div>';
                }
            }
        }
    }
}

// Handle autoresponder deletion
if (isset($_GET['delete_autoresponder']) && isset($_GET['ar_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['ar_nonce'])), 'delete_autoresponder')) {
    $instant_popup_builder_delete_id = intval($_GET['delete_autoresponder']);
    global $wpdb;
    $instant_popup_builder_autoresponders_table = $wpdb->prefix . 'instant_popup_autoresponders';

    $instant_popup_builder_result = $wpdb->delete($instant_popup_builder_autoresponders_table, ['id' => $instant_popup_builder_delete_id], ['%d']);

    if ($instant_popup_builder_result) {
        echo '<div class="notice notice-success"><p>Auto Responder deleted successfully!</p></div>';
    } else {
        echo '<div class="notice notice-error"><p>Failed to delete Auto Responder.</p></div>';
    }
}

// Fetch existing autoresponders
global $wpdb;
$instant_popup_builder_autoresponders_table = $wpdb->prefix . 'instant_popup_autoresponders';

$instant_popup_builder_escaped_autoresponders_table = esc_sql($instant_popup_builder_autoresponders_table);
$instant_popup_builder_escaped_users_table = esc_sql($wpdb->users);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$instant_popup_builder_autoresponders = $wpdb->get_results("
    SELECT ar.*, u.display_name as created_by_name
    FROM `{$instant_popup_builder_escaped_autoresponders_table}` ar
    LEFT JOIN `{$instant_popup_builder_escaped_users_table}` u ON ar.created_by = u.ID
    WHERE ar.status != 'deleted'
    ORDER BY ar.created_at DESC
", ARRAY_A);

// Fetch available subscription campaigns (same as subscriber form)
$instant_popup_builder_campaigns = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}instant_popup_builder where type=%s", 'subscription'), ARRAY_A);

// Fetch available email templates
$instant_popup_builder_templates_table = $wpdb->prefix . 'instant_popup_templates';
$instant_popup_builder_escaped_templates_table = esc_sql($instant_popup_builder_templates_table);
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
$instant_popup_builder_templates = $wpdb->get_results($wpdb->prepare("
    SELECT id, name, category
    FROM `{$instant_popup_builder_escaped_templates_table}`
    WHERE status = %s
    ORDER BY name ASC
", 'active'), ARRAY_A);

// Handle edit mode
$instant_popup_builder_edit_mode = false;
$instant_popup_builder_edit_data = null;
if (isset($_GET['edit_autoresponder']) && intval($_GET['edit_autoresponder']) > 0) {
    $instant_popup_builder_edit_id = intval($_GET['edit_autoresponder']);
    $instant_popup_builder_escaped_autoresponders_table = esc_sql($instant_popup_builder_autoresponders_table);
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $instant_popup_builder_edit_data = $wpdb->get_row($wpdb->prepare("
        SELECT * FROM `{$instant_popup_builder_escaped_autoresponders_table}` WHERE id = %d
    ", $instant_popup_builder_edit_id), ARRAY_A);

    if ($instant_popup_builder_edit_data) {
        $instant_popup_builder_edit_mode = true;
        $instant_popup_builder_edit_data['trigger_rules'] = json_decode($instant_popup_builder_edit_data['trigger_rules'], true);
        $instant_popup_builder_edit_data['campaign_ids'] = json_decode($instant_popup_builder_edit_data['campaign_ids'], true);
    }
}
?>

<div class="autoresponder-tab-content">
    <?php if ($instant_popup_builder_edit_mode): ?>
        <!-- Edit Autoresponder Form -->
        <div class="autoresponder-form-container">
            <div class="form-header">
                <h3>Edit Auto Responder</h3>
                <p>Modify the settings for your automated email response.</p>
            </div>

            <form method="post" action="" class="autoresponder-form">
                <?php wp_nonce_field('save_autoresponder_settings', 'autoresponder_nonce'); ?>
                <input type="hidden" name="autoresponder_id" value="<?php echo esc_attr($instant_popup_builder_edit_data['id']); ?>">

                <div class="form-grid">
                    <!-- Title -->
                    <div class="form-group">
                        <label for="autoresponder_title">Title <span class="required">*</span></label>
                        <input type="text" id="autoresponder_title" name="autoresponder_title"
                               value="<?php echo esc_attr($instant_popup_builder_edit_data['title']); ?>"
                               placeholder="Enter autoresponder name" required>
                        <p class="description">Give your autoresponder a descriptive name for easy identification.</p>
                    </div>

                    <!-- Enable/Disable Toggle -->
                    <div class="form-group">
                        <label for="autoresponder_status">Status</label>
                        <div class="toggle-switch">
                            <input type="checkbox" id="autoresponder_status" name="autoresponder_status"
                                   value="active" <?php checked($instant_popup_builder_edit_data['status'], 'active'); ?>>
                            <label for="autoresponder_status" class="toggle-label">
                                <span class="toggle-inner"></span>
                                <span class="toggle-switch-text">Enable Auto Responder</span>
                            </label>
                        </div>
                    </div>

                    <!-- Trigger Rules -->
                    <div class="form-group full-width">
                        <label>Trigger Rules <span class="required">*</span></label>
                        <div class="trigger-rules-container">
                            <div class="trigger-option">
                                <input type="checkbox" id="trigger_subscription" name="trigger_rules[]"
                                       value="on_successful_subscription"
                                       <?php checked(in_array('on_successful_subscription', $instant_popup_builder_edit_data['trigger_rules'] ?? [])); ?>>
                                <label for="trigger_subscription">On Successful Subscription</label>
                            </div>
                            <div class="trigger-option">
                                <input type="checkbox" id="trigger_verification" name="trigger_rules[]"
                                       value="on_email_verification"
                                       <?php checked(in_array('on_email_verification', $instant_popup_builder_edit_data['trigger_rules'] ?? [])); ?>>
                                <label for="trigger_verification">On Email Verification</label>
                                <p class="description">Linked to subscription popup "Enable email verification" setting</p>
                            </div>
                        </div>
                    </div>

                    <!-- Campaign Association -->
                    <div class="form-group full-width">
                        <label for="campaign_ids">Associated Campaigns <span class="required">*</span></label>
                        <select id="campaign_ids" name="campaign_ids[]" multiple required style="width: 100%; min-height: 120px;">
                            <?php
                            // Load campaigns directly from database
                            global $wpdb;
                            $instant_popup_builder_campaigns = $wpdb->get_results($wpdb->prepare("
                                SELECT id, title, type, status FROM {$wpdb->prefix}instant_popup_builder
                                WHERE status = %s OR status = %s
                                ORDER BY title ASC
                            ", 'publish', 'draft'), ARRAY_A);

                            $instant_popup_builder_selected_ids = $instant_popup_builder_edit_data['campaign_ids'] ?? [];

                            if (!empty($instant_popup_builder_campaigns)) {
                                foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign) {
                                    $instant_popup_builder_selected = in_array($instant_popup_builder_campaign['id'], $instant_popup_builder_selected_ids) ? 'selected' : '';
                                    echo '<option value="' . esc_attr($instant_popup_builder_campaign['id']) . '" ' . esc_attr($instant_popup_builder_selected) . '>';
                                    echo esc_html($instant_popup_builder_campaign['title']) . ' (ID: ' . esc_html($instant_popup_builder_campaign['id']) . ', Type: ' . esc_html(ucfirst($instant_popup_builder_campaign['type'])) . ', Status: ' . esc_html(ucfirst($instant_popup_builder_campaign['status'])) . ')';
                                    echo '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>No popups found. Please create a popup first.</option>';
                            }
                            ?>
                        </select>
                        <p class="description">
                            Hold Ctrl (Windows) or Cmd (Mac) to select multiple campaigns.
                            <?php if (!empty($instant_popup_builder_campaigns)): ?>
                                Found <?php echo count($instant_popup_builder_campaigns); ?> popup(s) available.
                            <?php endif; ?>
                        </p>
                        <div class="campaigns-actions">
                            <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-builder')); ?>" target="_blank" class="button">
                                <span class="dashicons dashicons-plus-alt"></span> Create New Popup
                            </a>
                            <?php if (empty($campaigns)): ?>
                                <p class="description" style="color: #d63638; margin-top: 10px;">
                                    <strong>No popups found!</strong> You need to create at least one popup before setting up autoresponders.
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Sender Details -->
                    <div class="form-group">
                        <label for="sender_name">Sender Name <span class="required">*</span></label>
                        <input type="text" id="sender_name" name="sender_name"
                               value="<?php echo esc_attr($instant_popup_builder_edit_data['sender_name']); ?>"
                               placeholder="Your Name or Company" required>
                    </div>

                    <div class="form-group">
                        <label for="sender_email">Sender Email <span class="required">*</span></label>
                        <input type="email" id="sender_email" name="sender_email"
                               value="<?php echo esc_attr($instant_popup_builder_edit_data['sender_email']); ?>"
                               placeholder="noreply@yourdomain.com" required>
                    </div>

                    <div class="form-group">
                        <label for="reply_to_email">Reply-To Email</label>
                        <input type="email" id="reply_to_email" name="reply_to_email"
                               value="<?php echo esc_attr($instant_popup_builder_edit_data['reply_to_email']); ?>"
                               placeholder="support@yourdomain.com">
                        <p class="description">Optional: Different email for replies</p>
                    </div>

                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="disable_reply" name="disable_reply" value="1"
                                   <?php checked($instant_popup_builder_edit_data['disable_reply'], '1'); ?>>
                            <label for="disable_reply">Disable Reply Option</label>
                            <p class="description">Prevent recipients from replying to this email</p>
                        </div>
                    </div>

                    <!-- Template Selection -->
                    <div class="form-group full-width">
                        <label for="template_id">Email Template</label>
                        <select id="template_id" name="template_id">
                            <option value="0">Select a template</option>
                            <?php foreach ($instant_popup_builder_templates as $instant_popup_builder_template): ?>
                                <option value="<?php echo esc_attr($instant_popup_builder_template['id']); ?>"
                                        <?php selected($instant_popup_builder_edit_data['template_id'], $instant_popup_builder_template['id']); ?>>
                                    <?php echo esc_html($instant_popup_builder_template['name']); ?>
                                    (<?php echo esc_html(ucfirst($instant_popup_builder_template['category'])); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="template-actions">
                            <button type="button" class="button" id="preview-template">Preview Template</button>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-configuration&tab=templates')); ?>"
                               class="button">Manage Templates</a>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" name="submit_autoresponder" class="button button-primary">
                        Update Auto Responder
                    </button>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-configuration&tab=autoresponder')); ?>"
                       class="button">Cancel</a>
                </div>
            </form>
        </div>
    <?php else: ?>
        <!-- Autoresponders List -->
        <div class="autoresponders-header">
            <div class="autoresponders-title">
                <h3>Auto Responders</h3>
                <p>Configure automated email responses for your subscription popups.</p>
            </div>
            <div class="autoresponders-actions">
                <button type="button" class="hover-button button button-primary" id="create-new-autoresponder">
                   <span> <span class="dashicons dashicons-plus-alt" style="margin-top: 6px;"></span>
                    Create New</span>
                </button>
            </div>
        </div>

        <!-- Autoresponders Table -->
        <div class="autoresponders-table-container">
            <table class="wp-list-table widefat fixed striped autoresponders-table">
                <thead>
                    <tr>
                        <th scope="col" class="column-id">ID</th>
                        <th scope="col" class="column-title">Title</th>
                        <th scope="col" class="column-campaign">Campaigns</th>
                        <th scope="col" class="column-triggers">Triggers</th>
                        <th scope="col" class="column-status">Status</th>
                        <th scope="col" class="column-created">Created</th>
                        <th scope="col" class="column-actions">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td colspan="7" class="no-autoresponders">
                            <div class="empty-state">
                                <span class="dashicons dashicons-lock"></span>
                                <h4 style="margin: 15px 0 10px 32px;">Upgrade to Pro</h4>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Create New Autoresponder Modal -->
<div id="create-autoresponder-modal" class="autoresponder-modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Create New Auto Responder</h3>
            <button type="button" class="close-modal">&times;</button>
        </div>
        <div class="modal-body">
            <form method="post" action="" class="autoresponder-form">
                <?php wp_nonce_field('save_autoresponder_settings', 'autoresponder_nonce'); ?>

                <div class="form-grid">
                    <!-- Title -->
                    <div class="form-group">
                        <label for="new_autoresponder_title">Title <span class="required">*</span></label>
                        <input type="text" id="new_autoresponder_title" name="autoresponder_title"
                               placeholder="Enter autoresponder name" required>
                    </div>

                    <!-- Enable/Disable Toggle -->
                    <div class="form-group">
                        <div class="toggle-switch">
                            <input type="checkbox" id="new_autoresponder_status" name="autoresponder_status"
                                   value="active" checked>
                            <label for="new_autoresponder_status" class="toggle-label">
                                <span class="toggle-inner"></span>
                                <span class="toggle-switch-text">Enable Auto Responder</span>
                            </label>
                        </div>
                    </div>

                    <!-- Trigger Rules -->
                    <div class="form-group full-width">
                        <label>Trigger Rules <span class="required">*</span></label>
                        <div class="trigger-rules-container">
                            <div class="trigger-option">
                                <input type="checkbox" id="new_trigger_subscription" name="trigger_rules[]"
                                       value="on_successful_subscription" checked>
                                <label for="new_trigger_subscription">On Successful Subscription</label>
                            </div>
                            <div class="trigger-option">
                                <input type="checkbox" id="new_trigger_verification" name="trigger_rules[]"
                                       value="on_email_verification">
                                <label for="new_trigger_verification">On Email Verification</label>
                                <p class="description">Linked to subscription popup "Enable email verification" setting</p>
                            </div>
                        </div>
                    </div>

                    <!-- Campaign Association -->
                    <div class="form-group full-width">
                        <label for="new_campaign_ids">Associated Campaigns <span class="required">*</span></label>
                        <select id="new_campaign_ids" name="campaign_ids[]" multiple required class="ipb-campaign-select2">
                            <?php
                            if (!empty($instant_popup_builder_campaigns)) {
                                foreach ($instant_popup_builder_campaigns as $instant_popup_builder_campaign) {
                                    echo '<option value="' . esc_attr($instant_popup_builder_campaign['id']) . '">';
                                    echo esc_html($instant_popup_builder_campaign['title']) . ' (ID: ' . esc_html($instant_popup_builder_campaign['id']) . ')';
                                    echo '</option>';
                                }
                            } else {
                                echo '<option value="" disabled>No subscription popups found. Please create a subscription popup first.</option>';
                            }
                            ?>
                        </select>
                        <p class="description">
                            Select one or more campaigns to associate with this autoresponder.
                            <?php if (!empty($instant_popup_builder_campaigns)): ?>
                                Found <?php echo count($instant_popup_builder_campaigns); ?> subscription popup(s) available.
                            <?php endif; ?>
                        </p>
                        <div class="campaigns-actions">
                            <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-builder')); ?>" target="_blank" class="button">
                                <span class="dashicons dashicons-plus-alt"></span> Create New Popup
                            </a>
                            <?php if (empty($instant_popup_builder_campaigns)): ?>
                                <p class="description" style="color: #d63638; margin-top: 10px;">
                                    <strong>No subscription popups found!</strong> You need to create at least one popup before setting up autoresponders.
                                </p>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Sender Details -->
                    <div class="form-group">
                        <label for="new_sender_name">Sender Name <span class="required">*</span></label>
                        <input type="text" id="new_sender_name" name="sender_name"
                               placeholder="Your Name or Company" required>
                    </div>

                    <div class="form-group">
                        <label for="new_sender_email">Sender Email <span class="required">*</span></label>
                        <input type="email" id="new_sender_email" name="sender_email"
                               placeholder="noreply@yourdomain.com" required>
                    </div>

                    <div class="form-group">
                        <label for="new_reply_to_email">Reply-To Email</label>
                        <input type="email" id="new_reply_to_email" name="reply_to_email"
                               placeholder="support@yourdomain.com">
                    </div>

                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="new_disable_reply" name="disable_reply" value="1">
                            <label for="new_disable_reply">Disable Reply Option</label>
                        </div>
                    </div>

                    <!-- Template Selection -->
                    <div class="form-group full-width">
                        <label for="new_template_id">Email Template</label>
                        <select id="new_template_id" name="template_id">
                            <option value="0">Select a template</option>
                            <?php foreach ($instant_popup_builder_templates as $instant_popup_builder_template): ?>
                                <option value="<?php echo esc_attr($instant_popup_builder_template['id']); ?>">
                                    <?php echo esc_html($instant_popup_builder_template['name']); ?>
                                    (<?php echo esc_html(ucfirst($instant_popup_builder_template['category'])); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="template-actions">
                            <button type="button" class="button" id="preview-new-template">Preview Template</button>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=instant-popup-configuration&tab=templates')); ?>"
                               class="button" target="_blank">Manage Templates</a>
                        </div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" name="submit_autoresponder" class="button button-primary">
                        Create Auto Responder
                    </button>
                    <button type="button" class="button cancel-modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
/* Auto Responder Styles */
/*.autoresponder-tab-content {*/
/*    max-width: 1200px;*/
/*}*/

.autoresponders-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e1e1e1;
}

.autoresponders-title h3 {
    margin: 0 0 8px 0;
    font-size: 22px;
    font-weight: 600;
    color: #23282d;
}

.autoresponders-title p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.autoresponders-actions .button {
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.autoresponders-table-container {
    background: #fff;
    border: 1px solid #c3c4c7;
    border-radius: 4px;
}

.autoresponders-table {
    margin: 0;
}

.autoresponders-table th,
.autoresponders-table td {
    padding: 12px 10px;
}

.column-id { width: 60px; }
.column-title { width: 200px; }
.column-campaign { width: 150px; }
.column-triggers { width: 120px; }
.column-status { width: 100px; }
.column-created { width: 100px; }
.column-actions { width: 120px; }

.status-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-inactive {
    background: #f8d7da;
    color: #721c24;
}

.autoresponder-actions {
    display: flex;
    gap: 5px;
}

.autoresponder-actions .button {
    padding: 4px 8px;
    font-size: 12px;
    line-height: 1.2;
}

.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #666;
}

.empty-state .dashicons {
    font-size: 48px;
    color: #c3c4c7;
    margin-bottom: 15px;
}

.empty-state h4 {
    margin: 0 0 10px 0;
    font-size: 18px;
    color: #23282d;
}

.empty-state p {
    margin: 0 0 20px 0;
    font-size: 14px;
}

/* Form Styles */
.autoresponder-form-container,
.form-header {
    background: #fff;
    border: 1px solid #c3c4c7;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.form-header {
    margin-bottom: 30px;
    border-bottom: 1px solid #e1e1e1;
    padding-bottom: 20px;
}

.form-header h3 {
    margin: 0 0 8px 0;
    font-size: 22px;
    font-weight: 600;
    color: #23282d;
}

.form-header p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 30px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group.full-width {
    grid-column: 1 / -1;
}

.form-group label {
    margin-bottom: 5px;
    font-weight: 600;
    color: #23282d;
}

.form-group input,
.form-group select,
.form-group textarea {
    padding: 8px 12px;
    border: 1px solid #8c8f94;
    border-radius: 4px;
    font-size: 14px;
    line-height: 1.4;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
    border-color: #2271b1;
    box-shadow: 0 0 0 1px #2271b1;
    outline: none;
}

.form-group .description {
    margin: 5px 0 0 0;
    font-size: 12px;
    color: #666;
    font-style: italic;
}

.required {
    color: #d63638;
}

/* Toggle Switch */
.toggle-switch {
    display: flex;
    align-items: center;
    gap: 10px;
}

.toggle-switch input[type="checkbox"] {
    display: none;
}

.toggle-label {
    position: relative;
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
}

.toggle-inner {
    width: 40px;
    height: 20px;
    background: #ccc;
    border-radius: 20px;
    position: relative;
    transition: background 0.3s ease;
}

.toggle-inner:before {
    content: '';
    position: absolute;
    top: 2px;
    left: 2px;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    transition: transform 0.3s ease;
}

.toggle-switch input[type="checkbox"]:checked + .toggle-label .toggle-inner {
    background: #2271b1;
}

.toggle-switch input[type="checkbox"]:checked + .toggle-label .toggle-inner:before {
    transform: translateX(20px);
}

/* Trigger Rules */
.trigger-rules-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
    padding: 15px;
    background: #f9f9f9;
    border: 1px solid #e1e1e1;
    border-radius: 4px;
}

.trigger-option {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.trigger-option input[type="checkbox"] {
    margin-right: 8px;
}

.trigger-option label {
    font-weight: 500;
    margin-bottom: 0;
}

/* Checkbox Group */
.checkbox-group {
    display: flex;
    align-items: flex-start;
    gap: 8px;
}

.checkbox-group input[type="checkbox"] {
    margin-top: 3px;
}

.checkbox-group label {
    margin-bottom: 0;
}

/* Template Actions */
.template-actions {
    display: flex;
    gap: 10px;
    margin-top: 10px;
}

.template-actions .button {
    font-size: 12px;
    padding: 4px 8px;
}

/* Campaign Select2 Styling */
.ipb-campaign-select2 {
    width: 100% !important;
}

/* Custom Select2 Styling for Campaign Dropdown */
.form-group .select2-container {
    width: 100% !important;
}

.form-group .select2-container--default .select2-selection--multiple {
    border: 1px solid #8c8f94;
    border-radius: 6px;
    padding: 8px;
    min-height: 45px;
    background: #fff;
    transition: all 0.3s ease;
}

.form-group .select2-container--default .select2-selection--multiple:hover {
    border-color: #2271b1;
}

.form-group .select2-container--default.select2-container--focus .select2-selection--multiple {
    border-color: #2271b1;
    box-shadow: 0 0 0 2px rgba(34, 113, 177, 0.1);
    outline: none;
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__rendered {
    padding: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__choice {
    background: linear-gradient(135deg, #2271b1, #1e5a8a);
    border: none;
    color: #fff;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 500;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 6px;
    box-shadow: 0 2px 4px rgba(34, 113, 177, 0.2);
    transition: all 0.2s ease;
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__choice:hover {
    background: linear-gradient(135deg, #1e5a8a, #2271b1);
    transform: translateY(-1px);
    box-shadow: 0 3px 6px rgba(34, 113, 177, 0.3);
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__choice__display {
    color: #fff;
    padding: 0;
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
    color: rgba(255, 255, 255, 0.8);
    font-size: 16px;
    font-weight: bold;
    margin: 0;
    padding: 0;
    background: none;
    border: none;
    cursor: pointer;
    transition: color 0.2s ease;
}

.form-group .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
    color: #ff6b6b;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
}

.form-group .select2-container--default .select2-search--inline .select2-search__field {
    border: none;
    background: transparent;
    padding: 6px;
    font-size: 14px;
    color: #23282d;
    min-width: 150px;
}

.form-group .select2-container--default .select2-search--inline .select2-search__field::placeholder {
    color: #8c8f94;
    font-style: italic;
}

/* Dropdown Styling */
.select2-dropdown {
    border: 1px solid #8c8f94;
    border-radius: 6px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #fff;
    z-index: 9999;
}

.select2-dropdown .select2-search {
    padding: 12px;
    border-bottom: 1px solid #e1e1e1;
}

.select2-dropdown .select2-search .select2-search__field {
    border: 1px solid #8c8f94;
    border-radius: 4px;
    padding: 8px 12px;
    font-size: 14px;
    width: 100%;
    box-sizing: border-box;
}

.select2-dropdown .select2-search .select2-search__field:focus {
    border-color: #2271b1;
    box-shadow: 0 0 0 1px #2271b1;
    outline: none;
}

.select2-dropdown .select2-results {
    max-height: 200px;
    overflow-y: auto;
}

.select2-dropdown .select2-results__options {
    padding: 8px 0;
}

.select2-dropdown .select2-results__option {
    padding: 10px 16px;
    font-size: 14px;
    color: #23282d;
    cursor: pointer;
    transition: all 0.2s ease;
}

.select2-dropdown .select2-results__option:hover {
    background: #f0f6fc;
    color: #2271b1;
}

.select2-dropdown .select2-results__option--highlighted {
    background: #2271b1 !important;
    color: #fff !important;
}

.select2-dropdown .select2-results__option--selected {
    background: #e7f3ff;
    color: #2271b1;
    font-weight: 500;
}

.select2-dropdown .select2-results__option--selected:hover {
    background: #d0ebff;
}

/* Empty state styling */
.select2-dropdown .select2-results__option--disabled {
    color: #8c8f94;
    font-style: italic;
    cursor: not-allowed;
}

/* Custom campaign option template */
.select2-campaign-option {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.select2-campaign-option .campaign-title {
    font-weight: 500;
    color: #23282d;
    font-size: 14px;
}

.select2-campaign-option .campaign-meta {
    font-size: 12px;
    color: #8c8f94;
    font-style: italic;
}

.select2-dropdown .select2-results__option--highlighted .select2-campaign-option .campaign-title {
    color: #fff;
}

.select2-dropdown .select2-results__option--highlighted .select2-campaign-option .campaign-meta {
    color: rgba(255, 255, 255, 0.8);
}

.select2-dropdown .select2-results__option--selected .select2-campaign-option .campaign-title {
    color: #2271b1;
    font-weight: 600;
}

.select2-dropdown .select2-results__option--selected .select2-campaign-option .campaign-meta {
    color: rgba(34, 113, 177, 0.7);
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .form-group .select2-container--default .select2-selection--multiple .select2-selection__choice {
        font-size: 12px;
        padding: 4px 8px;
    }

    .form-group .select2-container--default .select2-search--inline .select2-search__field {
        min-width: 100px;
    }
}

/* Error text styling */
.error-text {
    color: #d63638 !important;
    font-weight: 500;
}

.no-campaigns {
    color: #d63638;
    font-style: italic;
}

/* Campaigns Actions */
.campaigns-actions {
    display: flex;
    gap: 10px;
    margin-top: 10px;
    align-items: center;
}

.campaigns-actions .button {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    font-size: 12px;
    padding: 4px 8px;
}

.campaigns-actions .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.campaigns-status {
    font-weight: 500;
    margin-top: 8px !important;
}

/* Form Actions */
.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    padding-top: 20px;
    border-top: 1px solid #e1e1e1;
}

/* Modal Styles */
.autoresponder-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
}

.autoresponder-modal .modal-content {
    background: #fff;
    border-radius: 4px;
    max-width: 800px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
}

.autoresponder-modal .modal-header {
    padding: 20px 30px;
    border-bottom: 1px solid #e1e1e1;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.autoresponder-modal .modal-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
}

.close-modal {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
}

.close-modal:hover {
    color: #d63638;
}

.autoresponder-modal .modal-body {
    padding: 30px;
}

/* Responsive Design */
@media (max-width: 768px) {
    .autoresponders-header {
        flex-direction: column;
        gap: 20px;
    }

    .form-grid {
        grid-template-columns: 1fr;
    }

    .autoresponder-modal .modal-content {
        width: 95%;
        margin: 20px;
    }

    .autoresponder-modal .modal-body {
        padding: 20px;
    }

    .autoresponders-table {
        font-size: 12px;
    }

    .column-campaign,
    .column-triggers,
    .column-created {
        display: none;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    var campaignsCache = {};
    var isLoading = false;

    // AJAX function to fetch campaigns
    function fetchCampaigns() {
        if (isLoading) {
            return Promise.resolve(campaignsCache);
        }

        isLoading = true;

        return $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'ipb_get_campaigns',
                nonce: '<?php echo esc_js(wp_create_nonce("ipb_ajax_nonce")); ?>'
            },
            dataType: 'json'
        }).done(function(response) {
            isLoading = false;
            if (response.success) {
                campaignsCache = response.data;
                console.log('Campaigns fetched successfully:', response.data);
                console.log('Campaigns array:', response.data.campaigns);


            } else {
                console.error('Error fetching campaigns:', response.data);
            }
        }).fail(function(xhr, status, error) {
            isLoading = false;
            console.error('AJAX error:', error);
            console.error('Response:', xhr.responseText);
        });
    }

    // Function to populate select dropdown with campaigns
    function populateSelect($select, selectedIds = []) {
        console.log('populateSelect called with:', campaignsCache);
        console.log('campaignsCache.campaigns:', campaignsCache.campaigns);

        $select.empty();

        if (campaignsCache.campaigns && campaignsCache.campaigns.length > 0) {
            console.log('Found', campaignsCache.campaigns.length, 'campaigns to populate');
            $.each(campaignsCache.campaigns, function(index, campaign) {
                var isSelected = selectedIds.includes(String(campaign.id));
                var option = new Option(
                    campaign.title + ' (ID: ' + campaign.id + ', Status: ' + campaign.status + ')',
                    campaign.id,
                    false,
                    isSelected
                );
                $select.append(option);
            });

            // Show success message
            $select.closest('.form-group').find('.campaigns-status').remove();
            $select.closest('.form-group').append(
                '<p class="description campaigns-status" style="color: #46b450;">' +
                campaignsCache.message + '</p>'
            );
        } else {
            console.log('No campaigns found. campaignsCache:', campaignsCache);
            console.log('campaignsCache.campaigns exists?', !!campaignsCache.campaigns);
            console.log('campaignsCache.campaigns length:', campaignsCache.campaigns ? campaignsCache.campaigns.length : 'undefined');

            $select.append(new Option('No popups found. Please create a popup first.', '', false, false));

            // Show error message
            $select.closest('.form-group').find('.campaigns-status').remove();
            $select.closest('.form-group').append(
                '<p class="description campaigns-status error-text">' +
                (campaignsCache.message || 'No published popups found.') +
                ' <a href="<?php echo esc_url(admin_url("admin.php?page=instant-popup-builder")); ?>" target="_blank">Create a popup</a></p>'
            );
        }

        $select.trigger('change');
    }

    // Initialize Select2 for campaign selection
    function initializeSelect2() {
        $('.ipb-campaign-select2').select2({
            placeholder: 'Select campaigns to associate with this autoresponder...',
            allowClear: true,
            width: '100%',
            closeOnSelect: false,
            multiple: true,
            templateResult: function(option) {
                if (!option.id) return option.text;

                // Create a custom template for dropdown options
                var $option = $(
                    '<div class="select2-campaign-option">' +
                        '<div class="campaign-title">' + option.text.split(' (ID:')[0] + '</div>' +
                        '<div class="campaign-meta">ID: ' + option.id + '</div>' +
                    '</div>'
                );
                return $option;
            },
            templateSelection: function(option) {
                if (!option.id) return option.text;

                // Show just the title in selected items
                var title = option.text.split(' (ID:')[0];
                return title;
            },
            language: {
                noResults: function() {
                    return 'No subscription popups found. <a href="<?php echo esc_url(admin_url("admin.php?page=instant-popup-builder")); ?>" target="_blank">Create one</a>';
                },
                searching: function() {
                    return 'Searching campaigns...';
                }
            },
            escapeMarkup: function(markup) {
                return markup;
            }
        });
    }

    // Initialize Select2 on page load
    initializeSelect2();

    // Show create autoresponder modal
    $('#create-new-autoresponder, #create-first-autoresponder').on('click', function(e) {
       // e.preventDefault();
       // $('#create-autoresponder-modal').show();
       window.open('https://instantpopupbuilder.com/extensions/subscription-popup/', '_blank');
    });

    // Close modal
    $('.close-modal, .cancel-modal').on('click', function(e) {
        e.preventDefault();
        $('#create-autoresponder-modal').hide();
        // Clear form
        $('#create-autoresponder-modal form')[0].reset();
        $('#new_campaign_ids').val(null).trigger('change');
    });

    // Close modal on outside click
    $(document).on('click', function(e) {
        if ($(e.target).is('#create-autoresponder-modal')) {
            $('#create-autoresponder-modal').hide();
            // Clear form
            $('#create-autoresponder-modal form')[0].reset();
            $('#new_campaign_ids').val(null).trigger('change');
        }
    });

    // Preview template functionality
    $('#preview-template, #preview-new-template').on('click', function(e) {
        e.preventDefault();
        var templateId = $(this).closest('.form-group').find('select').val();

        if (templateId && templateId > 0) {
            // Add template preview functionality here
            alert('Template preview functionality will be implemented with template system.');
        } else {
            alert('Please select a template first.');
        }
    });

    // Form validation
    $('.autoresponder-form').on('submit', function(e) {
        var title = $(this).find('input[name="autoresponder_title"]').val();
        var campaignIds = $(this).find('select[name="campaign_ids[]"]').val();
        var senderName = $(this).find('input[name="sender_name"]').val();
        var senderEmail = $(this).find('input[name="sender_email"]').val();
        var triggerRules = $(this).find('input[name="trigger_rules[]"]:checked').length;

        if (!title || !campaignIds || campaignIds.length === 0 || !senderName || !senderEmail || triggerRules === 0) {
            e.preventDefault();
            alert('Please fill in all required fields, select at least one campaign, and select at least one trigger rule.');
            return false;
        }

        // Email validation
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(senderEmail)) {
            e.preventDefault();
            alert('Please enter a valid sender email address.');
            return false;
        }

        var replyToEmail = $(this).find('input[name="reply_to_email"]').val();
        if (replyToEmail && !emailRegex.test(replyToEmail)) {
            e.preventDefault();
            alert('Please enter a valid reply-to email address.');
            return false;
        }
    });

    // No refresh needed since campaigns are loaded via PHP
});
</script>
