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

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

// Get all pages for dropdowns
$pages = get_pages();

// Get global subscription settings
$instant_popup_builder_subscription_settings = get_option('instant_popup_subscription_settings', array());

// Ensure media library is enqueued for Subscribe to Download
if (function_exists('wp_enqueue_media')) {
    wp_enqueue_media();
}

?>
<div class="ipb-section">

<div class="ipb-section-content" data-section="display">
<div class="subscription_settings_wrapper">
    <div class="subscription_settings_inner">
        <div class="settings_section">


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            <?php
            /**
             * Hook: Allow extensions to add settings after Email Settings (for new popups)
             * 
             * @param int $current_popup_id Current popup ID (0 for new popups)
             * @param array $instant_popup_builder_subscription_settings Current subscription settings
             */
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET edit_id identifies popup for settings form context only; saves use nonces elsewhere.
            $current_popup_id = isset($_GET['edit_id']) ? absint(wp_unslash($_GET['edit_id'])) : 0;
            do_action('ipb_subscription_settings_after_email', $current_popup_id, $instant_popup_builder_subscription_settings);

            // Check if hook-based integration is available
            // If hook-based integration exists, skip hardcoded version to avoid duplicates
            $hook_based_available = class_exists('Instant_Popup_Subscribe_To_Download_Hook_Integration');
            
            // Only show hardcoded STD section if hook-based version is not available
            if (!$hook_based_available) {
            ?>
            <!-- Subscribe to Download Section (Legacy - will be removed in Phase 2) -->
            <?php
            // Check if Subscribe to Download extension is installed and license is active
            if (!function_exists('is_plugin_active')) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }
            
            $std_plugin_active = false;
            // Method 1: Check if plugin is active via WordPress function
            if (function_exists('is_plugin_active')) {
                $std_plugin_active = is_plugin_active('instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php');
            }
            // Method 2: Check if class exists (fallback)
            if (!$std_plugin_active && class_exists('Instant_Popup_Subscribe_To_Download_Admin')) {
                $std_plugin_active = true;
            }
            // Method 3: Check if main plugin file exists and is loaded
            if (!$std_plugin_active) {
                $plugin_path = WP_PLUGIN_DIR . '/instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php';
                if (file_exists($plugin_path)) {
                    // Check if it's in active plugins list
                    $active_plugins = get_option('active_plugins', array());
                    $plugin_file = 'instant-popup-subscribe-to-download/instant-popup-subscribe-to-download.php';
                    $std_plugin_active = in_array($plugin_file, $active_plugins, true);
                }
            }
            
            // Check license status - check both options for reliability
            $std_license_active = get_option('subscribe_to_download_license_active') === 'yes';
            // Also check the enabled option as fallback
            if (!$std_license_active) {
                $std_license_active = get_option('ipb_subscribe_to_download_enabled') === 'yes';
            }
            $std_enabled = $std_plugin_active && $std_license_active;
            
            if ($std_enabled) {
                // Ensure media library is enqueued
                if (function_exists('wp_enqueue_media')) {
                    wp_enqueue_media();
                }
                
                // Get popup ID (0 for new popups)
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET edit_id identifies popup for STD section display only; saves use nonces elsewhere.
                $current_popup_id = isset($_GET['edit_id']) ? absint(wp_unslash($_GET['edit_id'])) : 0;
                
                // Initialize with defaults for new popups
                $std_file_id = 0;
                $std_file_attachment_id = 0;
                $std_delivery_method = 'button';
                $std_thank_you_message = 'Thank you for Subscribing !';
                $std_download_button_text = 'Click to download File';
                $std_file_encryption = 1;
                
                // Load from subscription_settings if available (for existing popups)
                if ($current_popup_id > 0) {
                    global $wpdb;
                    $table_name = $wpdb->prefix . 'instant_popup_subscription_settings';
                    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) == $table_name) {
                        $result = $wpdb->get_row($wpdb->prepare(
                            "SELECT settings FROM $table_name WHERE popup_id = %d",
                            $current_popup_id
                        ));
                        if ($result && !empty($result->settings)) {
                            $popup_subscription_settings = maybe_unserialize($result->settings);
                            if (!empty($popup_subscription_settings)) {
                                $std_file_id = isset($popup_subscription_settings['std_file_id']) ? intval($popup_subscription_settings['std_file_id']) : 0;
                                $std_file_attachment_id = isset($popup_subscription_settings['std_file_attachment_id']) ? intval($popup_subscription_settings['std_file_attachment_id']) : 0;
                                if (isset($popup_subscription_settings['std_delivery_method'])) {
                                    $std_delivery_method = sanitize_text_field($popup_subscription_settings['std_delivery_method']);
                                }
                                if (isset($popup_subscription_settings['std_thank_you_message'])) {
                                    $std_thank_you_message = $popup_subscription_settings['std_thank_you_message'];
                                }
                                if (isset($popup_subscription_settings['std_download_button_text'])) {
                                    $std_download_button_text = $popup_subscription_settings['std_download_button_text'];
                                }
                                if (isset($popup_subscription_settings['std_file_encryption'])) {
                                    $std_file_encryption = intval($popup_subscription_settings['std_file_encryption']);
                                }
                            }
                        }
                    }
                }
                
                // Use file_attachment_id if file_id is not set
                if (!$std_file_id && $std_file_attachment_id) {
                    $std_file_id = $std_file_attachment_id;
                }
                
                // Get file info if file_id exists
                $std_file_name = '';
                $std_file_url = '';
                if ($std_file_id) {
                    global $wpdb;
                    $file_table = $wpdb->prefix . 'instant_popup_download_files';
                    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $file_table)) == $file_table) {
                        $file = $wpdb->get_row($wpdb->prepare("SELECT file_name, file_path, storage_type, external_url FROM $file_table WHERE id = %d", $std_file_id));
                        if ($file) {
                            $std_file_name = $file->file_name;
                            if ($file->storage_type === 'external') {
                                $std_file_url = $file->external_url;
                            } else {
                                $std_file_url = wp_get_attachment_url($std_file_id);
                                if (!$std_file_url && file_exists($file->file_path)) {
                                    $upload_dir = wp_upload_dir();
                                    $std_file_url = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $file->file_path);
                                }
                            }
                        }
                    }
                }
            ?>
            <div class="setting_group" id="subscribe-to-download-section">
                <h3><i class="fa fa-download"></i> Subscribe to Download</h3>

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

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

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

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

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

        </div>
    </div>
</div>
</div>
</div>

<style>
#ipb_subscription .ipb-section{
    padding: 0px !important;
    border: unset !important;
}
#ipb_subscription .ipb-section-content{
    padding: 0px !important;
    border: unset !important;
}

.subscription_settings_wrapper {
    /* padding: 20px; */
    background: #fff;
    border-radius: 8px;
    /* box-shadow: 0 1px 3px rgba(0,0,0,0.1); */
}

/* Match edit subscription popup text sizes for consistency */
.subscription_settings_inner h2 {
    margin: 0 0 10px 0;
    color: #333;
    font-size: 18px;
}

.subscription_settings_inner .description {
    margin: 0 0 30px 0;
    color: #666;
    font-size: 14px;
    font-style: italic;
}

.setting_group {
    margin-bottom: 25px;
    padding: 15px;
    border: 1px solid #e5e5e5;
    border-radius: 6px;
    background: #fafafa;
}

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

.setting_field {
    margin-bottom: 15px;
}

.setting_field:last-child {
    margin-bottom: 0;
}

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

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

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

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

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

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

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

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

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

.save_action {
    text-align: center;
    padding: 20px 0;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    font-size: 13px;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.btn-primary {
    background: #007cba;
    color: white;
}

.btn-primary:hover {
    background: #005a87;
}

.save-status {
    margin-top: 10px;
    padding: 8px 12px;
    border-radius: 4px;
    display: none;
}

.save-status.success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.save-status.error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
</style>

<script>
jQuery(document).ready(function($) {
    // Toggle privacy options
    $('#subscription_show_privacy').on('change', function() {
        if ($(this).is(':checked')) {
            $('.privacy_options').slideDown();
        } else {
            $('.privacy_options').slideUp();
        }
    });

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

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

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

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

});
</script>
