<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @since      1.0.0
 * @package    Subscription_System
 */

class Subs_Sys_Public {

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

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

    /**
     * The subscription manager instance.
     *
     * @since    1.0.0
     * @access   private
     * @var      Subs_Sys_Manager    $subscription_manager    The subscription manager instance.
     */
    private $subscription_manager;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    string    $plugin_name       The name of the plugin.
     * @param    string    $version           The version of this plugin.
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->subscription_manager = new Subs_Sys_Manager();
        
        // Add content notification bar
        add_action('wp_footer', array($this, 'display_content_notification_bar'));
        add_action('wp_head', array($this, 'display_smart_subscription_bar'));
        add_action('template_redirect', array($this, 'handle_content_checkout_redirect'));
        add_action('template_redirect', array($this, 'handle_interest_checkout_redirect'));
        add_action('template_redirect', array($this, 'handle_interest_checkout_success'));
        add_action('template_redirect', array($this, 'handle_content_subscription_success'));
        add_action('wp_head', array($this, 'display_subscription_success_message'));

        // Floating button + auto-open modal
        add_action('wp_footer', array($this, 'render_interest_modal_triggers'));
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url(__FILE__) . 'css/subscription-system-public.css',
            array(),
            $this->version,
            'all'
        );
        
        // Enqueue dashicons for the account dashboard
        wp_enqueue_style('dashicons');
    }

    /**
     * Register the JavaScript for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {
        wp_enqueue_script(
            $this->plugin_name,
            SUBS_SYS_PLUGIN_URL . 'public/js/subscription-system-public.js',
            array('jquery'),
            $this->version,
            false
        );
        
        wp_localize_script(
            $this->plugin_name,
            'ss_vars',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('ss_public_nonce'),
                'i18n' => array(
                    'processing' => __('Processing...', 'subscription-system'),
                    'success' => __('Success!', 'subscription-system'),
                    'error' => __('Error:', 'subscription-system')
                )
            )
        );
        
        // Add parameters for AJAX
        wp_localize_script('subscription-system', 'subs_sys_params', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('subscription_system')
        ));

        // Enqueue content subscription scripts
        if (is_single() || is_page()) {
            wp_enqueue_script(
                'subs-sys-content-notification',
                SUBS_SYS_PLUGIN_URL . 'public/js/content-notification.js',
                array('jquery'),
                $this->version,
                true
            );

            wp_localize_script('subs-sys-content-notification', 'subsContentVars', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('subscribe_to_content_plan'),
                'post_id' => get_the_ID(),
                'user_logged_in' => is_user_logged_in(),
                'login_url' => wp_login_url(get_permalink()),
                'i18n' => array(
                    'subscribe_prompt' => __('Subscribe to get notified when new content like this is published!', 'subscription-system'),
                    'login_required' => __('Please log in to subscribe to content notifications.', 'subscription-system'),
                    'subscribe_button' => __('Subscribe Now', 'subscription-system'),
                    'login_button' => __('Login to Subscribe', 'subscription-system'),
                    'close_button' => __('×', 'subscription-system')
                )
            ));
        }
        
        // Enqueue jQuery UI datepicker if needed
        if (is_page('account') && isset($_GET['tab']) && $_GET['tab'] === 'worklog') {
            wp_enqueue_script('jquery-ui-datepicker');
            wp_enqueue_script('jquery-ui-timepicker', plugin_dir_url(__FILE__) . 'js/jquery-ui-timepicker-addon.min.js', array('jquery-ui-datepicker'), '1.6.3', true);
            wp_enqueue_style('jquery-ui-style', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
            wp_enqueue_style('jquery-ui-timepicker', plugin_dir_url(__FILE__) . 'css/jquery-ui-timepicker-addon.min.css');
        }
    }

    /**
     * Register shortcodes.
     *
     * @since    1.0.0
     */
    public function register_shortcodes() {
        // Create the shortcodes instance
        $plugin_shortcodes = new Subs_Sys_Shortcodes($this->plugin_name, $this->version);
        
        // Localize script for AJAX
        wp_localize_script($this->plugin_name . '-forms', 'subs_sys_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'register_nonce' => wp_create_nonce('subs_sys_register_nonce'),
            'login_nonce' => wp_create_nonce('subs_sys_login_nonce'),
            'forgot_password_nonce' => wp_create_nonce('subs_sys_forgot_password_nonce'),
            'reset_password_nonce' => wp_create_nonce('subs_sys_reset_password_nonce')
        ));
        
        // Localize script for account dashboard
        wp_register_script($this->plugin_name . '-account', plugin_dir_url(__FILE__) . 'js/subscription-system-account.js', array('jquery'), $this->version, false);
        wp_localize_script($this->plugin_name . '-account', 'subs_sys_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php')
        ));
    }

    /**
     * Shortcode for displaying subscription plans.
     *
     * @since    1.0.0
     * @param    array    $atts    Shortcode attributes.
     * @return   string            The shortcode output.
     */
    public function subscription_plans_shortcode($atts) {
        $atts = shortcode_atts(
            array(
                'columns' => 2,
                'show_button' => 'yes',
                'button_text' => __('Subscribe Now', 'subscription-system')
            ),
            $atts,
            'subscription_plans'
        );
        
        $plans = $this->subscription_manager->get_subscription_plans();
        
        if (empty($plans)) {
            return '<p>' . __('No subscription plans available.', 'subscription-system') . '</p>';
        }
        
        $settings = get_option('ss_settings', array(
            'currency' => 'USD',
            'currency_position' => 'before'
        ));
        
        $currency_symbols = array(
            'USD' => '$',
            'EUR' => '€',
            'GBP' => '£',
            'JPY' => '¥'
        );
        
        $currency_symbol = isset($currency_symbols[$settings['currency']]) ? $currency_symbols[$settings['currency']] : $settings['currency'];
        
        ob_start();
        include SUBS_SYS_PLUGIN_DIR . 'public/partials/subscription-system-plans.php';
        return ob_get_clean();
    }

    /**
     * Shortcode for displaying the subscription form.
     *
     * @since    1.0.0
     * @param    array    $atts    Shortcode attributes.
     * @return   string            The shortcode output.
     */
    public function subscription_form_shortcode($atts) {
        $atts = shortcode_atts(
            array(
                'plan_id' => '',
                'button_text' => __('Subscribe', 'subscription-system')
            ),
            $atts,
            'subscription_form'
        );
        
        // If no plan ID is specified, show all plans
        if (empty($atts['plan_id'])) {
            $plans = $this->subscription_manager->get_subscription_plans();
        } else {
            $plan = $this->subscription_manager->get_subscription_plan($atts['plan_id']);
            
            if (!$plan) {
                return '<p>' . __('Invalid subscription plan.', 'subscription-system') . '</p>';
            }
            
            $plans = array($atts['plan_id'] => $plan);
        }
        
        $settings = get_option('ss_settings', array(
            'currency' => 'USD',
            'currency_position' => 'before'
        ));
        
        $currency_symbols = array(
            'USD' => '$',
            'EUR' => '€',
            'GBP' => '£',
            'JPY' => '¥'
        );
        
        $currency_symbol = isset($currency_symbols[$settings['currency']]) ? $currency_symbols[$settings['currency']] : $settings['currency'];
        
        ob_start();
        include SUBS_SYS_PLUGIN_DIR . 'public/partials/subscription-system-form.php';
        return ob_get_clean();
    }

    /**
     * Shortcode for displaying the user's subscriptions.
     *
     * @since    1.0.0
     * @param    array    $atts    Shortcode attributes.
     * @return   string            The shortcode output.
     */
    public function my_subscriptions_shortcode($atts) {
        $atts = shortcode_atts(
            array(
                'show_status' => 'yes',
                'show_plan' => 'yes',
                'show_dates' => 'yes',
                'show_actions' => 'yes'
            ),
            $atts,
            'my_subscriptions'
        );
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            return '<p>' . __('Please log in to view your subscriptions.', 'subscription-system') . '</p>';
        }
        
        $user_id = get_current_user_id();
        $subscriptions = $this->subscription_manager->get_user_subscriptions($user_id);
        
        if (empty($subscriptions)) {
            return '<p>' . __('You have no active subscriptions.', 'subscription-system') . '</p>';
        }
        
        $plans = $this->subscription_manager->get_subscription_plans();
        
        ob_start();
        include SUBS_SYS_PLUGIN_DIR . 'public/partials/subscription-system-my-subscriptions.php';
        return ob_get_clean();
    }

    /**
     * Handle AJAX subscription requests.
     *
     * @since    1.0.0
     */
    public function ajax_subscribe() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ss_public_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed.', 'subscription-system')));
        }
        
        $plan_id = isset($_POST['plan_id']) ? sanitize_text_field($_POST['plan_id']) : '';
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        
        if (empty($plan_id)) {
            wp_send_json_error(array('message' => __('Please select a subscription plan.', 'subscription-system')));
        }
        
        if (empty($email) || !is_email($email)) {
            wp_send_json_error(array('message' => __('Please enter a valid email address.', 'subscription-system')));
        }
        
        // Get the plan
        $plan = $this->subscription_manager->get_subscription_plan($plan_id);
        
        if (!$plan) {
            wp_send_json_error(array('message' => __('Invalid subscription plan.', 'subscription-system')));
        }
        
        // Check if user is logged in
        $user_id = 0;
        
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
        } else {
            // Check if user exists with this email
            $user = get_user_by('email', $email);
            
            if ($user) {
                $user_id = $user->ID;
            } else {
                // Create a new user
                $username = sanitize_user(current(explode('@', $email)), true);
                $counter = 1;
                $new_username = $username;
                
                while (username_exists($new_username)) {
                    $new_username = $username . $counter;
                    $counter++;
                }
                
                $random_password = wp_generate_password(12, false);
                $user_id = wp_create_user($new_username, $random_password, $email);
                
                if (is_wp_error($user_id)) {
                    wp_send_json_error(array('message' => $user_id->get_error_message()));
                }
                
                // Send the user an email with their login details
                wp_new_user_notification($user_id, null, 'user');
            }
        }
        
        // Create the subscription
        $start_date = current_time('mysql');
        $end_date = null;
        
        if ($plan['duration'] > 0) {
            $end_date = date('Y-m-d H:i:s', strtotime($start_date . ' + ' . $plan['duration'] . ' days'));
        }
        
        $subscription_data = array(
            'user_id' => $user_id,
            'email' => $email,
            'plan_id' => $plan_id,
            'status' => 'active',
            'start_date' => $start_date,
            'end_date' => $end_date
        );
        
        $result = $this->subscription_manager->create_subscription($subscription_data);
        
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }
        
        // Get success page URL
        $settings = get_option('ss_settings', array('success_page' => 0));
        $redirect_url = $settings['success_page'] ? get_permalink($settings['success_page']) : home_url();
        
        wp_send_json_success(array(
            'message' => __('Subscription created successfully!', 'subscription-system'),
            'redirect' => $redirect_url
        ));
    }

    /**
     * Register AJAX handlers for the public side
     */
    public function register_ajax_handlers() {
        add_action('wp_ajax_get_work_items_by_channel', array($this, 'ajax_get_work_items_by_channel'));
        add_action('wp_ajax_add_user_work_log', array($this, 'ajax_add_user_work_log'));
    }

    /**
     * Get work items by channel ID (AJAX handler)
     */
    public function ajax_get_work_items_by_channel() {
        // Check nonce
        check_ajax_referer('subscription_system', 'security');
        
        $channel_id = isset($_POST['channel_id']) ? intval($_POST['channel_id']) : 0;
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_items';
        
        $work_items = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table_name WHERE channel_id = %d AND status = 'active' ORDER BY name ASC",
            $channel_id
        ));
        
        wp_send_json_success($work_items);
    }

    /**
     * Add a new work log for the current user (AJAX handler)
     */
    public function ajax_add_user_work_log() {
        // Check nonce
        check_ajax_referer('add_user_work_log', 'work_log_nonce');
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => 'You must be logged in to add a work log.'));
            return;
        }
        
        $user_id = get_current_user_id();
        $channel_id = isset($_POST['channel_id']) ? intval($_POST['channel_id']) : 0;
        $work_item_id = isset($_POST['work_item_id']) ? intval($_POST['work_item_id']) : 0;
        $importance = isset($_POST['importance']) ? sanitize_text_field(wp_unslash($_POST['importance'])) : '';
        $notes = isset($_POST['notes']) ? wp_kses_post($_POST['notes']) : '';
        $performed_at = isset($_POST['performed_at']) ? sanitize_text_field($_POST['performed_at']) : current_time('mysql');
        
        // Validate required fields
        if (empty($channel_id) || empty($work_item_id)) {
            wp_send_json_error(array('message' => 'Channel and Work Item are required fields.'));
            return;
        }
        
        // Validate performed_at date format
        if (!empty($performed_at)) {
            // Convert to MySQL format if needed
            if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $performed_at)) {
                $performed_at = $performed_at . ':00';
            } elseif (preg_match('/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}$/', $performed_at)) {
                $performed_at = date('Y-m-d H:i:s', strtotime($performed_at));
            }
        } else {
            $performed_at = current_time('mysql');
        }
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_logs';
        
        $result = $wpdb->insert(
            $table_name,
            array(
                'user_id' => $user_id,
                'channel_id' => $channel_id,
                'work_item_id' => $work_item_id,
                'importance' => $importance,
                'notes' => $notes,
                'performed_at' => $performed_at,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%d', '%d', '%s', '%s', '%s', '%s')
        );
        
        if ($result) {
            wp_send_json_success(array('message' => 'Work log added successfully.'));
        } else {
            wp_send_json_error(array('message' => 'Failed to add work log.'));
        }
    }

    /**
     * Display content notification bar on posts, pages, archives, categories, tags, etc.
     */
    public function display_content_notification_bar() {
        // Don't show on admin pages
        if (is_admin()) {
            return;
        }

        // Get applicable content plans based on current page type
        $content_manager = new Subs_Sys_Content_Manager();
        $applicable_plans = $this->get_applicable_plans_for_current_page($content_manager);

        if (empty($applicable_plans)) {
            return;
        }

        // Check if user is already subscribed to any of these plans
        $user_id = get_current_user_id();
        $user_is_subscribed = false;
        $subscribed_plans = [];
        $unsubscribed_plans = [];

        if ($user_id) {
            foreach ($applicable_plans as $plan) {
                $user_subscription = $content_manager->get_user_content_subscription($user_id, $plan->id);
                
                if ($user_subscription && $user_subscription->status === 'active') {
                    $subscribed_plans[] = $plan;
                } else {
                    $unsubscribed_plans[] = $plan;
                }
            }
            $user_is_subscribed = !empty($subscribed_plans);
        } else {
            $unsubscribed_plans = $applicable_plans;
        }

        // Determine which plan to show in the popup
        if ($user_is_subscribed) {
            $plan = $subscribed_plans[0]; // Show first subscribed plan
        } else {
            $plan = $unsubscribed_plans[0]; // Show first unsubscribed plan
        }


        ?>
        <div id="content-subscription-notification" class="content-subscription-notification" style="display: none;">
            <div class="notification-card">
                <div class="notification-header">
                    <div class="notification-icon-wrapper">
                <div class="notification-icon">
                            <?php if ($user_is_subscribed): ?>
                                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                            <?php else: ?>
                                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M18 8C18 6.4087 17.3679 4.88258 16.2426 3.75736C15.1174 2.63214 13.5913 2 12 2C10.4087 2 8.88258 2.63214 7.75736 3.75736C6.63214 4.88258 6 6.4087 6 8C6 15 3 17 3 17H21C21 17 18 15 18 8Z" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                                    <path d="M13.73 21C13.5542 21.3031 13.3019 21.5547 12.9982 21.7295C12.6946 21.9044 12.3504 21.9965 12 21.9965C11.6496 21.9965 11.3054 21.9044 11.0018 21.7295C10.6981 21.5547 10.4458 21.3031 10.27 21" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                            <?php endif; ?>
                </div>
                        <div class="notification-pulse"></div>
                </div>
                    <button class="close-notification" aria-label="<?php esc_attr_e('Close notification', 'subscription-system'); ?>">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </div>
                
                <div class="notification-content">
                    <div class="notification-title">
                        <h3><?php echo esc_html($plan->plan_name); ?></h3>
                        <?php if ($user_is_subscribed): ?>
                            <span class="status-badge subscribed">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M9 12L11 14L15 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                Active
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="notification-message">
                        <?php if ($user_is_subscribed): ?>
                            <p><?php esc_html_e('🎉 You\'re all set! You\'ll receive notifications when new content like this is published.', 'subscription-system'); ?></p>
                            <?php if (count($subscribed_plans) > 1): ?>
                                <p class="multiple-plans-note">
                                    <?php printf(esc_html__('You\'re subscribed to %d plans for this content.', 'subscription-system'), count($subscribed_plans)); ?>
                                </p>
                            <?php endif; ?>
                        <?php else: ?>
                            <p><?php esc_html_e('Stay in the loop! Get notified when we publish new content like this.', 'subscription-system'); ?></p>
                            <?php if (count($unsubscribed_plans) > 1): ?>
                                <p class="multiple-plans-note">
                                    <?php printf(esc_html__('%d subscription plans available for this content.', 'subscription-system'), count($unsubscribed_plans)); ?>
                                    <a href="#" class="view-all-plans" onclick="showAllPlans(event)">View all plans</a>
                                </p>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>

                    <?php if (!$user_is_subscribed): ?>
                <div class="notification-actions">
                    <?php if (is_user_logged_in()): ?>
                                <button id="subscribe-to-content-plan" class="primary-btn" data-plan-id="<?php echo esc_attr($plan->id); ?>">
                                    <div class="btn-content">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
                                        </svg>
                                        <span>
                            <?php if ($plan->price > 0): ?>
                                                <?php printf(esc_html__('Subscribe for $%s', 'subscription-system'), number_format($plan->price, 2)); ?>
                            <?php else: ?>
                                <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                            <?php endif; ?>
                                        </span>
                                    </div>
                                    <div class="btn-shine"></div>
                        </button>
                    <?php else: ?>
                                <a href="<?php echo esc_url(wp_login_url(get_permalink())); ?>" class="primary-btn">
                                    <div class="btn-content">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M15 3H19C19.5304 3 20.0391 3.21071 20.4142 3.58579C20.7893 3.96086 21 4.46957 21 5V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M10 17L15 12L10 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            <path d="M15 12H3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        <span><?php esc_html_e('Login to Subscribe', 'subscription-system'); ?></span>
                                    </div>
                                    <div class="btn-shine"></div>
                        </a>
                    <?php endif; ?>
                            
                            <div class="remind-later-container">
                                <button class="secondary-btn remind-later-notification" aria-label="<?php esc_attr_e('Remind me later', 'subscription-system'); ?>">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M12 8V12L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                    <span><?php esc_html_e('Remind me later', 'subscription-system'); ?></span>
                                    <svg class="dropdown-arrow" width="12" height="12" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </button>
                                
                                <div class="remind-later-dropdown" style="display: none;">
                                    <div class="dropdown-header">
                                        <span><?php esc_html_e('Remind me in:', 'subscription-system'); ?></span>
                                    </div>
                                    <div class="dropdown-options">
                                        <button class="remind-option" data-time="1" data-unit="hour">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M12 6V12L16 14" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
                                            </svg>
                                            <?php esc_html_e('1 Hour', 'subscription-system'); ?>
                                        </button>
                                        <button class="remind-option" data-time="1" data-unit="day">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M8 2V6M16 2V6M3 10H21M5 4H19C20.1046 4 21 4.89543 21 6V20C21 21.1046 20.1046 22 19 22H5C3.89543 22 3 21.1046 3 20V6C3 4.89543 3.89543 4 5 4Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            <?php esc_html_e('Tomorrow', 'subscription-system'); ?>
                                        </button>
                                        <button class="remind-option" data-time="3" data-unit="day">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M8 2V6M16 2V6M3 10H21M5 4H19C20.1046 4 21 4.89543 21 6V20C21 21.1046 20.1046 22 19 22H5C3.89543 22 3 21.1046 3 20V6C3 4.89543 3.89543 4 5 4Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            <?php esc_html_e('3 Days', 'subscription-system'); ?>
                                        </button>
                                        <button class="remind-option" data-time="1" data-unit="week">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M8 2V6M16 2V6M3 10H21M5 4H19C20.1046 4 21 4.89543 21 6V20C21 21.1046 20.1046 22 19 22H5C3.89543 22 3 21.1046 3 20V6C3 4.89543 3.89543 4 5 4Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            <?php esc_html_e('Next Week', 'subscription-system'); ?>
                                        </button>
                                        <button class="remind-option remind-never" data-time="never">
                                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                            </svg>
                                            <?php esc_html_e('Don\'t remind me', 'subscription-system'); ?>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if (count($unsubscribed_plans) > 1): ?>
        <!-- Multiple Plans Modal -->
        <div id="multiple-plans-modal" class="multiple-plans-modal" style="display: none;">
            <div class="modal-overlay" onclick="closeAllPlansModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3><?php esc_html_e('Available Subscription Plans', 'subscription-system'); ?></h3>
                    <button class="modal-close" onclick="closeAllPlansModal()">×</button>
                </div>
                <div class="modal-body">
                    <div class="plans-grid">
                        <?php foreach ($unsubscribed_plans as $available_plan): ?>
                            <div class="plan-card">
                                <div class="plan-header">
                                    <h4><?php echo esc_html($available_plan->plan_name); ?></h4>
                                    <div class="plan-price">
                                        <?php if ($available_plan->price > 0): ?>
                                            <span class="price"><?php printf('$%s', number_format($available_plan->price, 2)); ?></span>
                                            <span class="period">/<?php echo esc_html($available_plan->duration_unit); ?></span>
                                        <?php else: ?>
                                            <span class="price free"><?php esc_html_e('Free', 'subscription-system'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if (!empty($available_plan->description)): ?>
                                    <div class="plan-description">
                                        <p><?php echo esc_html($available_plan->description); ?></p>
                                    </div>
                                <?php endif; ?>
                                <div class="plan-actions">
                                    <?php if (is_user_logged_in()): ?>
                                        <button class="subscribe-plan-btn primary-btn" data-plan-id="<?php echo esc_attr($available_plan->id); ?>">
                                            <div class="btn-content">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
                                                </svg>
                                                <span>
                                                    <?php if ($available_plan->price > 0): ?>
                                                        <?php printf(esc_html__('Subscribe - $%s', 'subscription-system'), number_format($available_plan->price, 2)); ?>
                                                    <?php else: ?>
                                                        <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                            <div class="btn-shine"></div>
                                        </button>
                                    <?php else: ?>
                                        <a href="<?php echo esc_url(wp_login_url(get_permalink())); ?>" class="primary-btn">
                                            <div class="btn-content">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <path d="M15 3H19C19.5304 3 20.0391 3.21071 20.4142 3.58579C20.7893 3.96086 21 4.46957 21 5V19C19 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                    <path d="M10 17L15 12L10 7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                    <path d="M15 12H3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                                </svg>
                                                <span><?php esc_html_e('Login to Subscribe', 'subscription-system'); ?></span>
                                            </div>
                                            <div class="btn-shine"></div>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <style>
        .content-subscription-notification {
            position: fixed;
            bottom: 32px;
            right: 32px;
            z-index: 10000;
            animation: slideInUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        }

        .notification-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            max-width: 420px;
            min-width: 350px;
            overflow: hidden;
            position: relative;
            transition: all 0.3s ease;
        }

        .notification-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 5px;
            height: 100%;
            background: linear-gradient(180deg, #4a90e2, #5cb85c);
        }

        .notification-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 24px 24px 0;
        }

        .notification-icon-wrapper {
            position: relative;
        }

        .notification-icon {
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            position: relative;
            z-index: 2;
            box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
        }

        .notification-pulse {
            position: absolute;
            top: 0;
            left: 0;
            width: 56px;
            height: 56px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            opacity: 0.3;
            animation: pulse 2s infinite;
        }

        .close-notification {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(0, 0, 0, 0.05);
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
        }

        .close-notification:hover {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
            transform: scale(1.1);
        }

        .notification-content {
            padding: 16px 24px 24px;
        }

        .notification-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;
        }

        .notification-title h3 {
            font-size: 20px;
            font-weight: 700;
            color: #1a202c;
            margin: 0;
            letter-spacing: -0.025em;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 50px;
            font-size: 12px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .status-badge.subscribed {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
            border: 1px solid rgba(21, 87, 36, 0.1);
        }

        .notification-message {
            margin-bottom: 20px;
        }

        .notification-message p {
            font-size: 15px;
            line-height: 1.6;
            color: #4a5568;
            margin: 0;
        }

        .notification-actions {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }

        .primary-btn {
            background: linear-gradient(90deg, #4a90e2, #357ab8);
            color: white;
            border: none;
            padding: 0;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            text-decoration: none;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            box-shadow: 0 4px 10px rgba(74, 144, 226, 0.2);
        }

        .btn-content {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 16px 24px;
            position: relative;
            z-index: 2;
        }

        .btn-shine {
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
            transition: left 0.6s;
            z-index: 1;
        }

        .primary-btn:hover .btn-shine {
            left: 100%;
        }

        .primary-btn:hover {
            background: linear-gradient(90deg, #357ab8, #2a6496);
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(74, 144, 226, 0.3);
        }

        .primary-btn:active {
            transform: translateY(0);
        }

        .secondary-btn {
            background: rgba(248, 250, 252, 0.8);
            color: #64748b;
            border: 1px solid rgba(226, 232, 240, 0.6);
            padding: 12px 20px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            backdrop-filter: blur(10px);
        }

        .secondary-btn:hover {
            background: rgba(241, 245, 249, 0.9);
            color: #475569;
            border-color: rgba(203, 213, 225, 0.8);
            transform: translateY(-1px);
        }

        /* Remind Me Later Dropdown Styles */
        .remind-later-container {
            position: relative;
            display: inline-block;
        }

        .remind-later-notification {
            position: relative;
        }

        .remind-later-notification.active {
            background: rgba(241, 245, 249, 0.9);
            color: #475569;
            border-color: #4a90e2;
        }

        .dropdown-arrow {
            transition: transform 0.2s ease;
            margin-left: 4px;
        }

        .remind-later-notification.active .dropdown-arrow {
            transform: rotate(180deg);
        }

        .remind-later-dropdown {
            position: absolute;
            bottom: 100%;
            left: 0;
            right: 0;
            background: #fff;
            border: 1px solid #f0f0f0;
            border-radius: 8px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            margin-bottom: 8px;
            z-index: 1000;
            min-width: 200px;
            animation: dropdownSlideUp 0.2s ease-out;
        }

        .dropdown-header {
            padding: 12px 16px;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
            font-weight: 600;
            color: #64748b;
            background: #f9fbfd;
            border-radius: 8px 8px 0 0;
        }

        .dropdown-options {
            padding: 8px 0;
        }

        .remind-option {
            width: 100%;
            padding: 12px 16px;
            border: none;
            background: none;
            text-align: left;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all 0.2s ease;
        }

        .remind-option:hover {
            background: #f5f9ff;
            color: #4a90e2;
        }

        .remind-option.remind-never {
            border-top: 1px solid #f0f0f0;
            margin-top: 4px;
            color: #dc3545;
        }

        .remind-option.remind-never:hover {
            background: #feeeed;
            color: #dc3545;
        }

        @keyframes dropdownSlideUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Animations */
        @keyframes slideInUp {
            from {
                transform: translateY(100%) scale(0.9);
                opacity: 0;
            }
            to {
                transform: translateY(0) scale(1);
                opacity: 1;
            }
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
                opacity: 0.3;
            }
            50% {
                transform: scale(1.2);
                opacity: 0.1;
            }
            100% {
                transform: scale(1);
                opacity: 0.3;
            }
        }

        @keyframes gradientShift {
            0%, 100% {
                background: linear-gradient(90deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            }
            33% {
                background: linear-gradient(90deg, #764ba2 0%, #f093fb 50%, #667eea 100%);
            }
            66% {
                background: linear-gradient(90deg, #f093fb 0%, #667eea 50%, #764ba2 100%);
            }
        }

        /* Responsive Design */
        @media (max-width: 480px) {
            .content-subscription-notification {
                bottom: 20px;
                right: 20px;
                left: 20px;
            }
            
            .notification-card {
                max-width: none;
                min-width: auto;
            }
            
            .notification-header {
                padding: 20px 20px 0;
            }
            
            .notification-content {
                padding: 16px 20px 20px;
            }
            
            .notification-icon {
                width: 48px;
                height: 48px;
            }
            
            .notification-pulse {
                width: 48px;
                height: 48px;
            }
        }

        @media (max-width: 360px) {
            .notification-title {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }

        .multiple-plans-note {
            font-size: 13px;
            color: #64748b;
            margin-top: 8px;
        }

        .view-all-plans {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
            margin-left: 8px;
        }

        .view-all-plans:hover {
            color: #764ba2;
            text-decoration: underline;
        }

        /* Multiple Plans Modal */
        .multiple-plans-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 10001;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease-out;
        }

        .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background: white;
            border-radius: 12px;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            position: relative;
            z-index: 1;
            margin: 20px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            animation: slideInScale 0.3s cubic-bezier(0.16, 1, 0.3, 1);
        }

        .modal-content::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 5px;
            height: 100%;
            background: linear-gradient(180deg, #4a90e2, #5cb85c);
        }

        .modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 24px 32px;
            border-bottom: 1px solid #f0f0f0;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
            font-weight: 700;
            color: #1a202c;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            color: #64748b;
            cursor: pointer;
            padding: 4px;
            border-radius: 50%;
            transition: all 0.2s;
        }

        .modal-close:hover {
            background: #f1f5f9;
            color: #ef4444;
        }

        .modal-body {
            padding: 32px;
        }

        .plans-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
        }

        .plan-card {
            border: 1px solid #f0f0f0;
            border-radius: 10px;
            padding: 25px;
            transition: all 0.3s ease;
            background: #f9fbfd;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .plan-card:hover {
            border-color: #4a90e2;
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(74, 144, 226, 0.15);
        }

        .plan-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;
        }

        .plan-header h4 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #1a202c;
        }

        .plan-price {
            display: flex;
            align-items: baseline;
            gap: 4px;
        }

        .plan-price .price {
            font-size: 20px;
            font-weight: 700;
            color: #4a90e2;
        }

        .plan-price .price.free {
            color: #10b981;
        }

        .plan-price .period {
            font-size: 14px;
            color: #64748b;
        }

        .plan-description {
            margin-bottom: 20px;
        }

        .plan-description p {
            margin: 0;
            font-size: 14px;
            color: #4a5568;
            line-height: 1.5;
        }

        .plan-actions {
            margin-top: auto;
        }

        .subscribe-plan-btn {
            width: 100%;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideInScale {
            from {
                opacity: 0;
                transform: scale(0.9) translateY(20px);
            }
            to {
                opacity: 1;
                transform: scale(1) translateY(0);
            }
        }

        /* Responsive modal */
        @media (max-width: 768px) {
            .modal-content {
                max-width: 95vw;
                max-height: 90vh;
                margin: 10px;
            }

            .modal-header {
                padding: 20px 24px;
            }

            .modal-body {
                padding: 24px;
            }

            .plans-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .plan-card {
                padding: 20px;
            }
        }

        /* Success celebration animation */
        .success-celebration {
            animation: celebrate 0.6s ease-in-out;
        }

        @keyframes celebrate {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        /* Success toast animations */
        @keyframes slideInDown {
            from {
                transform: translateY(-100%) scale(0.9);
                opacity: 0;
            }
            to {
                transform: translateY(0) scale(1);
                opacity: 1;
            }
        }

        @keyframes slideInUp {
            from {
                transform: translateY(100%) scale(0.95);
                opacity: 0;
            }
            to {
                transform: translateY(0) scale(1);
                opacity: 1;
            }
        }

        @media (max-width: 768px) {
            .content-subscription-notification {
                bottom: 10px;
                right: 10px;
                left: 10px;
                max-width: none;
            }
            
            .notification-content {
                padding: 16px;
            }
            
            .notification-actions {
                flex-direction: column;
                align-items: stretch;
            }
            
            .subscribe-btn, .login-btn {
                text-align: center;
            }
        }
        </style>

        <script>
        // Show notification when page loads
        document.addEventListener('DOMContentLoaded', function() {
            const notification = document.getElementById('content-subscription-notification');
            if (notification) {
                notification.style.display = 'block';
                
                // Also add show class if it exists
                setTimeout(function() {
                    notification.classList.add('show');
                }, 100);
            }
        });

        // Functions for multiple plans modal
        function showAllPlans(event) {
            event.preventDefault();
            const modal = document.getElementById('multiple-plans-modal');
            if (modal) {
                modal.style.display = 'flex';
                document.body.style.overflow = 'hidden';
            }
        }

        function closeAllPlansModal() {
            const modal = document.getElementById('multiple-plans-modal');
            if (modal) {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        }

        // Handle subscription buttons in modal and remind me later functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Check if notification should be shown based on reminder settings
            if (shouldShowNotification()) {
                // Notification will be shown by existing logic
            } else {
                // Hide notification if reminder time hasn't passed
                const notification = document.getElementById('content-subscription-notification');
                if (notification) {
                    notification.style.display = 'none';
                }
                return;
            }

            // Handle remind me later button click
            document.addEventListener('click', function(e) {
                const remindButton = e.target.closest('.remind-later-notification');
                if (remindButton) {
                    e.preventDefault();
                    const dropdown = remindButton.closest('.remind-later-container').querySelector('.remind-later-dropdown');
                    const isActive = remindButton.classList.contains('active');
                    
                    if (isActive) {
                        // Close dropdown
                        remindButton.classList.remove('active');
                        dropdown.style.display = 'none';
                    } else {
                        // Open dropdown
                        remindButton.classList.add('active');
                        dropdown.style.display = 'block';
                    }
                    return;
                }

                // Handle remind option selection
                const remindOption = e.target.closest('.remind-option');
                if (remindOption) {
                    e.preventDefault();
                    const time = remindOption.getAttribute('data-time');
                    const unit = remindOption.getAttribute('data-unit');
                    
                    handleRemindMeLater(time, unit);
                    return;
                }

                // Handle multiple plan subscription buttons
                if (e.target.classList.contains('subscribe-plan-btn') || e.target.closest('.subscribe-plan-btn')) {
                    const button = e.target.classList.contains('subscribe-plan-btn') ? e.target : e.target.closest('.subscribe-plan-btn');
                    const planId = button.getAttribute('data-plan-id');
                    
                    if (planId) {
                        // Close modal
                        closeAllPlansModal();
                        
                        // Trigger subscription (use existing AJAX logic)
                        if (typeof jQuery !== 'undefined') {
                            jQuery('#subscribe-to-content-plan').attr('data-plan-id', planId).click();
                        }
                    }
                }
            });

            // Close dropdown when clicking outside
            document.addEventListener('click', function(e) {
                const remindContainer = e.target.closest('.remind-later-container');
                if (!remindContainer) {
                    // Close all dropdowns
                    document.querySelectorAll('.remind-later-notification.active').forEach(button => {
                        button.classList.remove('active');
                        button.closest('.remind-later-container').querySelector('.remind-later-dropdown').style.display = 'none';
                    });
                }
            });

            // Close modal on escape key
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    closeAllPlansModal();
                    
                    // Also close remind me later dropdown
                    document.querySelectorAll('.remind-later-notification.active').forEach(button => {
                        button.classList.remove('active');
                        button.closest('.remind-later-container').querySelector('.remind-later-dropdown').style.display = 'none';
                    });
                }
            });
        });

        // Check if notification should be shown based on reminder settings
        function shouldShowNotification() {
            const remindData = localStorage.getItem('content_subscription_remind');
            if (!remindData) {
                return true; // Show if no reminder is set
            }

            try {
                const data = JSON.parse(remindData);
                const now = new Date().getTime();
                
                if (data.type === 'never') {
                    return false; // Never show again
                }
                
                if (data.remindAt && now < data.remindAt) {
                    return false; // Still in reminder period
                }
                
                // Reminder time has passed, show notification
                localStorage.removeItem('content_subscription_remind');
                return true;
            } catch (e) {
                // Invalid data, show notification
                localStorage.removeItem('content_subscription_remind');
                return true;
            }
        }

        // Handle remind me later option selection
        function handleRemindMeLater(time, unit) {
            const notification = document.getElementById('content-subscription-notification');
            
            if (time === 'never') {
                // Don't remind again
                localStorage.setItem('content_subscription_remind', JSON.stringify({
                    type: 'never',
                    setAt: new Date().getTime()
                }));
                
                // Show confirmation message
                showRemindConfirmation("We won't remind you about this subscription again.");
            } else {
                // Calculate reminder time
                let remindAt = new Date().getTime();
                const timeNum = parseInt(time);
                
                switch (unit) {
                    case 'hour':
                        remindAt += timeNum * 60 * 60 * 1000;
                        break;
                    case 'day':
                        remindAt += timeNum * 24 * 60 * 60 * 1000;
                        break;
                    case 'week':
                        remindAt += timeNum * 7 * 24 * 60 * 60 * 1000;
                        break;
                }
                
                // Store reminder
                localStorage.setItem('content_subscription_remind', JSON.stringify({
                    type: 'timed',
                    remindAt: remindAt,
                    setAt: new Date().getTime(),
                    time: timeNum,
                    unit: unit
                }));
                
                // Show confirmation message
                const unitText = unit === 'hour' ? 'hour' : (unit === 'day' ? (timeNum === 1 ? 'day' : 'days') : 'week');
                const timeText = timeNum === 1 && unit === 'day' ? 'tomorrow' : `in ${timeNum} ${unitText}`;
                showRemindConfirmation(`We'll remind you ${timeText}.`);
            }
            
            // Hide notification with animation
            if (notification) {
                notification.style.transform = 'translateY(20px)';
                notification.style.opacity = '0';
                setTimeout(function() {
                    notification.style.display = 'none';
                }, 300);
            }
        }

        // Show reminder confirmation message
        function showRemindConfirmation(message) {
            // Remove any existing confirmation
            const existing = document.querySelector('.remind-confirmation');
            if (existing) {
                existing.remove();
            }

            // Create confirmation toast
            const confirmation = document.createElement('div');
            confirmation.className = 'remind-confirmation';
            confirmation.innerHTML = `
                <div class="remind-confirmation-content">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    <span>${message}</span>
                </div>
            `;
            
            // Style the confirmation
            Object.assign(confirmation.style, {
                position: 'fixed',
                bottom: '32px',
                right: '32px',
                background: 'linear-gradient(90deg, #4a90e2, #357ab8)',
                color: 'white',
                borderRadius: '8px',
                padding: '16px 20px',
                zIndex: '10001',
                boxShadow: '0 4px 10px rgba(74, 144, 226, 0.2)',
                fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',
                fontSize: '14px',
                maxWidth: '300px',
                animation: 'slideInUp 0.3s ease-out'
            });
            
            confirmation.querySelector('.remind-confirmation-content').style.cssText = `
                display: flex;
                align-items: center;
                gap: 10px;
            `;
            
            document.body.appendChild(confirmation);
            
            // Auto-remove after 3 seconds
            setTimeout(function() {
                confirmation.style.transform = 'translateY(20px)';
                confirmation.style.opacity = '0';
                setTimeout(function() {
                    if (confirmation.parentNode) {
                        confirmation.remove();
                    }
                }, 300);
            }, 3000);
        }
        </script>
        
        <?php
    }

    /**
     * Display smart subscription bar on pages/posts with active content plans
     */
    public function display_smart_subscription_bar() {
        // Only show on single posts/pages
        if (!is_single() && !is_page()) {
            return;
        }

        // Don't show for admin users
        if (current_user_can('manage_options')) {
            return;
        }

        global $post;
        if (!$post) {
            return;
        }

        $content_manager = new Subs_Sys_Content_Manager();
        
        // Get applicable content plans for this post
        $applicable_plans = array();
        
        // Check for category-based plans
        $categories = wp_get_post_categories($post->ID);
        foreach ($categories as $category_id) {
            $category_plans = $content_manager->get_content_plans(array(
                'content_type' => 'category',
                'content_ids' => $category_id,
                'status' => 'active'
            ));
            $applicable_plans = array_merge($applicable_plans, $category_plans);
        }
        
        // Check for tag-based plans
        $tags = wp_get_post_tags($post->ID);
        foreach ($tags as $tag) {
            $tag_plans = $content_manager->get_content_plans(array(
                'content_type' => 'tag',
                'content_ids' => $tag->term_id,
                'status' => 'active'
            ));
            $applicable_plans = array_merge($applicable_plans, $tag_plans);
        }
        
        // Check for post-type-based plans
        $post_type_plans = $content_manager->get_content_plans(array(
            'content_type' => 'post_type',
            'content_ids' => $post->post_type,
            'status' => 'active'
        ));
        $applicable_plans = array_merge($applicable_plans, $post_type_plans);
        
        // Check for specific post plans
        $post_plans = $content_manager->get_content_plans(array(
            'content_type' => 'post',
            'content_ids' => $post->ID,
            'status' => 'active'
        ));
        $applicable_plans = array_merge($applicable_plans, $post_plans);

        // Remove duplicates
        $applicable_plans = array_unique($applicable_plans, SORT_REGULAR);

        if (empty($applicable_plans)) {
            return;
        }

        // Check if user is logged in
        $user_id = get_current_user_id();
        $is_logged_in = is_user_logged_in();
        
        // Check if user is already subscribed to any of these plans
        $already_subscribed = false;
        $subscribed_plan = null;
        if ($is_logged_in) {
            foreach ($applicable_plans as $plan) {
                $user_subscription = $content_manager->get_user_content_subscription($user_id, $plan->id);
                if ($user_subscription && $user_subscription->status === 'active') {
                    $already_subscribed = true;
                    $subscribed_plan = $plan;
                    break;
                }
            }
        }

        // Get the first applicable plan for display
        $primary_plan = $applicable_plans[0];
        $plan_count = count($applicable_plans);

        ?>
        <div id="smart-subscription-bar" class="smart-subscription-bar">
            <div class="subscription-bar-content">
                <div class="subscription-bar-left">
                    <div class="subscription-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
                        </svg>
                    </div>
                    <div class="subscription-text">
                        <h4><?php esc_html_e('Stay Updated!', 'subscription-system'); ?></h4>
                        <p>
                            <?php if ($plan_count > 1): ?>
                                <?php printf(esc_html__('Get notified about new content in this %s and %d other topics.', 'subscription-system'), 
                                    ucfirst($primary_plan->content_type), $plan_count - 1); ?>
                            <?php else: ?>
                                <?php printf(esc_html__('Get notified about new content in this %s.', 'subscription-system'), 
                                    ucfirst($primary_plan->content_type)); ?>
                            <?php endif; ?>
                        </p>
                    </div>
                </div>
                <div class="subscription-bar-right">
                    <?php if ($is_logged_in): ?>
                        <?php if ($already_subscribed && $subscribed_plan): ?>
                            <button class="subscription-bar-btn success" onclick="unsubscribeFromPlan(<?php echo esc_js($subscribed_plan->id); ?>, '<?php echo esc_js($subscribed_plan->plan_name); ?>')">
                                <?php esc_html_e('Unsubscribe', 'subscription-system'); ?>
                            </button>
                        <?php else: ?>
                            <button class="subscription-bar-btn primary" onclick="showSubscriptionModal()">
                                <?php if ($primary_plan->price > 0): ?>
                                    <?php printf(esc_html__('Subscribe - $%s', 'subscription-system'), number_format($primary_plan->price, 2)); ?>
                                <?php else: ?>
                                    <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                                <?php endif; ?>
                            </button>
                        <?php endif; ?>
                    <?php else: ?>
                        <button class="subscription-bar-btn primary" onclick="showLoginModal()">
                            <?php esc_html_e('Login to Subscribe', 'subscription-system'); ?>
                        </button>
                    <?php endif; ?>
                    <button class="subscription-bar-btn secondary" onclick="dismissSubscriptionBar()">
                        <?php esc_html_e('Dismiss', 'subscription-system'); ?>
                    </button>
                </div>
            </div>
            <button class="subscription-bar-close" onclick="dismissSubscriptionBar()">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                </svg>
            </button>
        </div>

        <!-- Subscription Modal -->
        <div id="subscription-modal" class="subscription-modal" style="display: none;">
            <div class="modal-overlay" onclick="hideSubscriptionModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3><?php esc_html_e('Choose Your Subscription Plan', 'subscription-system'); ?></h3>
                    <button class="modal-close" onclick="hideSubscriptionModal()">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="plans-grid">
                        <?php foreach ($applicable_plans as $plan): ?>
                            <div class="plan-card">
                                <div class="plan-header">
                                    <h4><?php echo esc_html($plan->plan_name); ?></h4>
                                    <div class="plan-price">
                                        <?php if ($plan->price > 0): ?>
                                            <span class="price">$<?php echo esc_html(number_format($plan->price, 2)); ?></span>
                                            <span class="period">/ <?php echo esc_html($plan->duration . ' ' . $plan->duration_unit); ?></span>
                                        <?php else: ?>
                                            <span class="price-free"><?php esc_html_e('Free', 'subscription-system'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if ($plan->description): ?>
                                    <p class="plan-description"><?php echo esc_html($plan->description); ?></p>
                                <?php endif; ?>
                                <div class="plan-features">
                                    <div class="feature">
                                        <strong><?php esc_html_e('Content Type:', 'subscription-system'); ?></strong>
                                        <?php echo esc_html(ucfirst($plan->content_type)); ?>
                                    </div>
                                    <div class="feature">
                                        <strong><?php esc_html_e('Notifications:', 'subscription-system'); ?></strong>
                                        <?php echo esc_html(ucfirst($plan->notification_frequency)); ?>
                                    </div>
                                </div>
                                <button class="plan-subscribe-btn" onclick="subscribeToPlan(<?php echo esc_js($plan->id); ?>, <?php echo esc_js($plan->price); ?>)">
                                    <?php if ($plan->price > 0): ?>
                                        <?php printf(esc_html__('Subscribe - $%s', 'subscription-system'), number_format($plan->price, 2)); ?>
                                    <?php else: ?>
                                        <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                                    <?php endif; ?>
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Login Modal -->
        <div id="login-modal" class="subscription-modal" style="display: none;">
            <div class="modal-overlay" onclick="hideLoginModal()"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3><?php esc_html_e('Login Required', 'subscription-system'); ?></h3>
                    <button class="modal-close" onclick="hideLoginModal()">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                        </svg>
                    </button>
                </div>
                <div class="modal-body">
                    <p><?php esc_html_e('Please log in to subscribe to content plans and receive notifications.', 'subscription-system'); ?></p>
                    <div class="login-actions">
                        <a href="<?php echo esc_url(wp_login_url(get_permalink())); ?>" class="login-btn">
                            <?php esc_html_e('Login', 'subscription-system'); ?>
                        </a>
                        <a href="<?php echo esc_url(wp_registration_url()); ?>" class="register-btn">
                            <?php esc_html_e('Register', 'subscription-system'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <style>
        .smart-subscription-bar {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            z-index: 9999;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transform: translateY(-100%);
            transition: transform 0.3s ease;
        }

        .smart-subscription-bar.show {
            transform: translateY(0);
        }

        .subscription-bar-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .subscription-bar-left {
            display: flex;
            align-items: center;
            flex: 1;
        }

        .subscription-icon {
            margin-right: 12px;
            opacity: 0.9;
        }

        .subscription-text h4 {
            margin: 0 0 4px 0;
            font-size: 16px;
            font-weight: 600;
        }

        .subscription-text p {
            margin: 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .subscription-bar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .subscription-bar-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .subscription-bar-btn.primary {
            background: rgba(255,255,255,0.2);
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .subscription-bar-btn.primary:hover {
            background: rgba(255,255,255,0.3);
        }

        .subscription-bar-btn.secondary {
            background: transparent;
            color: white;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .subscription-bar-btn.secondary:hover {
            background: rgba(255,255,255,0.1);
        }

        .subscription-bar-btn.success {
            background: rgba(220,53,69,0.2);
            color: white;
            border: 1px solid rgba(220,53,69,0.3);
        }

        .subscription-bar-btn.success:hover {
            background: rgba(220,53,69,0.3);
        }

        .subscription-bar-close {
            position: absolute;
            top: 12px;
            right: 12px;
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            opacity: 0.7;
            transition: opacity 0.2s ease;
        }

        .subscription-bar-close:hover {
            opacity: 1;
        }

        .subscription-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
        }

        .modal-content {
            position: relative;
            background: white;
            border-radius: 12px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }

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

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

        .modal-close {
            background: none;
            border: none;
            cursor: pointer;
            color: #666;
            padding: 4px;
        }

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

        .modal-body {
            padding: 24px;
        }

        .plans-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .plan-card {
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            transition: box-shadow 0.2s ease;
        }

        .plan-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .plan-header h4 {
            margin: 0 0 8px 0;
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .plan-price .price {
            font-size: 24px;
            font-weight: 700;
            color: #667eea;
        }

        .plan-price .period {
            font-size: 14px;
            color: #666;
        }

        .plan-price .price-free {
            font-size: 20px;
            font-weight: 600;
            color: #28a745;
        }

        .plan-description {
            margin: 12px 0;
            color: #666;
            font-size: 14px;
        }

        .plan-features {
            margin: 16px 0;
            text-align: left;
        }

        .feature {
            margin-bottom: 8px;
            font-size: 14px;
        }

        .feature strong {
            color: #333;
        }

        .plan-subscribe-btn {
            width: 100%;
            background: #667eea;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .plan-subscribe-btn:hover {
            background: #5a6fd8;
        }

        .login-actions {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-top: 20px;
        }

        .login-btn, .register-btn {
            padding: 12px 24px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.2s ease;
        }

        .login-btn {
            background: #667eea;
            color: white;
        }

        .login-btn:hover {
            background: #5a6fd8;
            color: white;
        }

        .register-btn {
            background: transparent;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .register-btn:hover {
            background: #667eea;
            color: white;
        }

        /* Adjust body padding when bar is shown */
        body.subscription-bar-active {
            padding-top: 80px;
        }

        @media (max-width: 768px) {
            .subscription-bar-content {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
                padding: 16px;
            }

            .subscription-bar-right {
                width: 100%;
                justify-content: space-between;
            }

            .subscription-bar-btn {
                flex: 1;
            }

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

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

            body.subscription-bar-active {
                padding-top: 120px;
            }
        }
        </style>

        <script>
        // Show subscription bar after page load
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(function() {
                const bar = document.getElementById('smart-subscription-bar');
                if (bar) {
                    bar.classList.add('show');
                    document.body.classList.add('subscription-bar-active');
                }
            }, 1000); // Show after 1 second
        });

        function showSubscriptionModal() {
            document.getElementById('subscription-modal').style.display = 'flex';
        }

        function hideSubscriptionModal() {
            document.getElementById('subscription-modal').style.display = 'none';
        }

        function showLoginModal() {
            document.getElementById('login-modal').style.display = 'flex';
        }

        function hideLoginModal() {
            document.getElementById('login-modal').style.display = 'none';
        }

        function dismissSubscriptionBar() {
            const bar = document.getElementById('smart-subscription-bar');
            if (bar) {
                bar.classList.remove('show');
                document.body.classList.remove('subscription-bar-active');
                // Store dismissal in localStorage
                localStorage.setItem('subscription_bar_dismissed', 'true');
            }
        }

        function subscribeToPlan(planId, price) {
            if (price > 0) {
                // Redirect to checkout for paid plans
                window.location.href = '<?php echo home_url(); ?>?action=content_checkout&content_plan_id=' + planId;
            } else {
                // Handle free subscription via AJAX
                const formData = new FormData();
                formData.append('action', 'subscribe_to_content_plan');
                formData.append('plan_id', planId);
                formData.append('subscription_nonce', '<?php echo wp_create_nonce('subscribe_to_content_plan'); ?>');

                fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('<?php esc_html_e('Successfully subscribed! You will now receive notifications.', 'subscription-system'); ?>');
                        hideSubscriptionModal();
                        dismissSubscriptionBar();
                        // Reload page to update subscription status
                        window.location.reload();
                    } else {
                        alert(data.data.message || '<?php esc_html_e('Subscription failed. Please try again.', 'subscription-system'); ?>');
                    }
                })
                .catch(error => {
                    alert('<?php esc_html_e('An error occurred. Please try again.', 'subscription-system'); ?>');
                });
            }
        }

        function unsubscribeFromPlan(planId, planName) {
            if (!confirm('<?php esc_html_e('Are you sure you want to unsubscribe from', 'subscription-system'); ?> "' + planName + '"? <?php esc_html_e('You will no longer receive notifications for this content.', 'subscription-system'); ?>')) {
                return;
            }

            const formData = new FormData();
            formData.append('action', 'unsubscribe_from_content_plan');
            formData.append('plan_id', planId);
            formData.append('unsubscribe_nonce', '<?php echo wp_create_nonce('unsubscribe_from_content_plan'); ?>');

            fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('<?php esc_html_e('Successfully unsubscribed!', 'subscription-system'); ?>');
                    dismissSubscriptionBar();
                    // Reload page to update subscription status
                    window.location.reload();
                } else {
                    alert(data.data.message || '<?php esc_html_e('Failed to unsubscribe. Please try again.', 'subscription-system'); ?>');
                }
            })
            .catch(error => {
                alert('<?php esc_html_e('An error occurred. Please try again.', 'subscription-system'); ?>');
            });
        }

        // Check if user previously dismissed the bar
        if (localStorage.getItem('subscription_bar_dismissed') === 'true') {
            // Don't show the bar if previously dismissed
            document.addEventListener('DOMContentLoaded', function() {
                const bar = document.getElementById('smart-subscription-bar');
                if (bar) {
                    bar.style.display = 'none';
                }
            });
        }
        </script>
        <?php
    }

    /**
     * Handle content subscription checkout redirect
     */
    public function handle_content_checkout_redirect() {
        // Check if this is a content checkout request
        if (isset($_GET['action']) && $_GET['action'] === 'content_checkout' && isset($_GET['content_plan_id'])) {
            $plan_id = intval($_GET['content_plan_id']);
            
            if ($plan_id > 0) {
                // Create a temporary page with the checkout shortcode
                $this->display_content_checkout_page($plan_id);
                exit;
            }
        }
    }

    /**
     * Display content checkout page
     */
    private function display_content_checkout_page($plan_id) {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_redirect(wp_login_url(add_query_arg(array('action' => 'content_checkout', 'content_plan_id' => $plan_id), home_url())));
            exit;
        }

        $content_manager = new Subs_Sys_Content_Manager();
        $plan = $content_manager->get_content_plan($plan_id);

        if (!$plan || $plan->status !== 'active') {
            wp_die(__('Content subscription plan not found or inactive.', 'subscription-system'));
        }

        $user_id = get_current_user_id();
        $user_subscription = $content_manager->get_user_content_subscription($user_id, $plan->id);

        // Check if already subscribed
        if ($user_subscription && $user_subscription->status === 'active') {
            wp_redirect(add_query_arg(array('tab' => 'content-subscriptions'), get_permalink()));
            exit;
        }

        // Get the shortcode output
        $shortcodes = new Subs_Sys_Shortcodes('subscription-system', '1.0.0');
        $checkout_content = $shortcodes->render_content_subscription_checkout(array('plan_id' => $plan_id));

        // Display the checkout page
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo('charset'); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title><?php printf(__('Subscribe to %s - %s', 'subscription-system'), $plan->plan_name, get_bloginfo('name')); ?></title>
            <?php wp_head(); ?>
            <style>
                body { 
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
                    margin: 0;
                    padding: 20px;
                    background: #f8f9fa;
                }
                .checkout-container {
                    max-width: 800px;
                    margin: 0 auto;
                    background: white;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    overflow: hidden;
                }
                .checkout-header {
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                    color: white;
                    padding: 30px;
                    text-align: center;
                }
                .checkout-header h1 {
                    margin: 0;
                    font-size: 28px;
                    font-weight: 600;
                }
                .checkout-content {
                    padding: 40px;
                }
                .back-link {
                    display: inline-block;
                    margin-bottom: 20px;
                    color: #667eea;
                    text-decoration: none;
                    font-weight: 500;
                }
                .back-link:hover {
                    text-decoration: underline;
                }
            </style>
        </head>
        <body>
            <div class="checkout-container">
                <div class="checkout-header">
                    <h1><?php printf(__('Subscribe to %s', 'subscription-system'), esc_html($plan->plan_name)); ?></h1>
                    <p><?php esc_html_e('Complete your subscription to start receiving notifications', 'subscription-system'); ?></p>
                </div>
                <div class="checkout-content">
                    <a href="<?php echo esc_url(home_url()); ?>" class="back-link">← <?php esc_html_e('Back to Home', 'subscription-system'); ?></a>
                    <?php echo $checkout_content; ?>
                </div>
            </div>
            <?php wp_footer(); ?>
        </body>
        </html>
        <?php
    }

    /**
     * Handle interest subscription paid checkout redirect (phase 1 placeholder).
     */
    public function handle_interest_checkout_redirect() {
        if ( ! isset( $_GET['action'] ) || 'interest_checkout' !== $_GET['action'] ) {
            return;
        }

        $subscription_id = isset( $_GET['interest_subscription_id'] ) ? absint( $_GET['interest_subscription_id'] ) : 0;
        if ( ! $subscription_id ) {
            wp_die( esc_html__( 'Invalid subscription.', 'subscription-system' ) );
        }

        $interest     = new Subs_Sys_Interest_Subscription();
        $subscription = $interest->get_subscription( $subscription_id );

        if ( ! $subscription || 'paid' !== $subscription->plan_type ) {
            wp_die( esc_html__( 'Subscription not found.', 'subscription-system' ) );
        }

        // Resolve plan — try content plans first, fall back to regular plans.
        $plan      = null;
        $plan_name = __( 'Paid Subscription', 'subscription-system' );
        $price     = 0.0;
        $duration  = 30;
        $stripe_price_id = '';

        if ( ! empty( $subscription->plan_id ) ) {
            $cp = Subs_Sys_Interest_Subscription::get_content_plan_by_id( $subscription->plan_id );
            if ( $cp ) {
                $plan            = $cp;
                $plan_name       = $cp->plan_name;
                $price           = (float) $cp->price;
                $duration        = (int) ( $cp->duration ?? 30 );
                $stripe_price_id = $cp->stripe_price_id ?? '';
            } else {
                $rp = Subs_Sys_Interest_Subscription::get_plan_by_id( $subscription->plan_id );
                if ( $rp ) {
                    $plan            = $rp;
                    $plan_name       = $rp->plan_name;
                    $price           = (float) $rp->price;
                    $duration        = (int) ( $rp->duration ?? 30 );
                    $stripe_price_id = $rp->stripe_price_id ?? '';
                }
            }
        }

        $price = $price > 0 ? $price : Subs_Sys_Interest_Subscription::get_paid_price();

        // Resolve billing interval from duration.
        $interval       = 'month';
        $interval_count = 1;
        if ( $duration <= 1 )        { $interval = 'day';   $interval_count = 1; }
        elseif ( $duration <= 7 )    { $interval = 'week';  $interval_count = 1; }
        elseif ( $duration <= 31 )   { $interval = 'month'; $interval_count = 1; }
        elseif ( $duration <= 93 )   { $interval = 'month'; $interval_count = 3; }
        elseif ( $duration <= 186 )  { $interval = 'month'; $interval_count = 6; }
        else                         { $interval = 'year';  $interval_count = 1; }

        // Build success / cancel URLs.
        $success_url = add_query_arg( array(
            'action'                   => 'interest_checkout_success',
            'interest_subscription_id' => $subscription_id,
            'session_id'               => '{CHECKOUT_SESSION_ID}',
        ), home_url( '/' ) );

        $cancel_url = add_query_arg( array(
            'action'                   => 'interest_checkout',
            'interest_subscription_id' => $subscription_id,
            'cancelled'                => '1',
        ), home_url( '/' ) );

        // ── Try Stripe Checkout ────────────────────────────────────────────
        $stripe_enabled = get_option( 'subscription_stripe_enabled', 0 );
        $test_mode      = get_option( 'subscription_stripe_test_mode', 1 );
        $api_key        = $test_mode
            ? get_option( 'subscription_stripe_test_secret_key', '' )
            : get_option( 'subscription_stripe_live_secret_key', '' );
        if ( empty( $api_key ) ) {
            $api_key = get_option( 'subscription_stripe_secret_key', '' );
        }

        if ( $stripe_enabled && ! empty( $api_key ) ) {
            if ( ! class_exists( '\Stripe\Stripe' ) ) {
                $admin = new Subs_Sys_Admin( $this->plugin_name, $this->version );
                if ( method_exists( $admin, 'ensure_stripe_sdk_loaded' ) ) {
                    $admin->ensure_stripe_sdk_loaded();
                }
            }

            if ( class_exists( '\Stripe\Stripe' ) ) {
                try {
                    \Stripe\Stripe::setApiKey( $api_key );

                    // Use the synced price ID if it exists and is not a mock/free placeholder.
                    $use_existing_price = ! empty( $stripe_price_id )
                        && strpos( $stripe_price_id, 'mock_' ) === false
                        && 'free' !== $stripe_price_id;

                    $line_item = $use_existing_price
                        ? array( 'price' => $stripe_price_id, 'quantity' => 1 )
                        : array(
                            'quantity'   => 1,
                            'price_data' => array(
                                'currency'     => strtolower( get_option( 'subscription_currency', 'usd' ) ),
                                'product_data' => array( 'name' => $plan_name ),
                                'unit_amount'  => (int) ( $price * 100 ),
                                'recurring'    => array(
                                    'interval'       => $interval,
                                    'interval_count' => $interval_count,
                                ),
                            ),
                        );

                    $session = \Stripe\Checkout\Session::create( array(
                        'payment_method_types' => array( 'card' ),
                        'mode'                 => 'subscription',
                        'line_items'           => array( $line_item ),
                        'customer_email'       => $subscription->subscriber_email,
                        'success_url'          => $success_url,
                        'cancel_url'           => $cancel_url,
                        'metadata'             => array(
                            'interest_subscription_id' => $subscription_id,
                            'subscriber_name'          => $subscription->subscriber_name,
                        ),
                    ) );

                    // Redirect to Stripe-hosted checkout page.
                    wp_redirect( $session->url );
                    exit;

                } catch ( \Exception $e ) {
                    // Fall through to the info page with error notice.
                    $stripe_error = $e->getMessage();
                }
            }
        }

        // ── Fallback: show info page (Stripe not configured) ──────────────
        $category_names = array();
        $tag_names      = array();
        foreach ( (array) $subscription->category_ids as $cat_id ) {
            $term = get_term( $cat_id, 'category' );
            if ( $term && ! is_wp_error( $term ) ) {
                $category_names[] = $term->name;
            }
        }
        foreach ( (array) $subscription->tag_ids as $tag_id ) {
            $term = get_term( $tag_id, 'post_tag' );
            if ( $term && ! is_wp_error( $term ) ) {
                $tag_names[] = $term->name;
            }
        }

        $cancelled     = isset( $_GET['cancelled'] );
        $stripe_setup  = admin_url( 'admin.php?page=subscription-settings&tab=payment' );
        $price_display = '$' . number_format( $price, 2 ) . ' / ' . $interval_count . ' ' . $interval . ( $interval_count > 1 ? 's' : '' );

        status_header( 200 );
        nocache_headers();
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo( 'charset' ); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title><?php esc_html_e( 'Complete Your Subscription', 'subscription-system' ); ?></title>
            <?php wp_head(); ?>
            <style>
                *{box-sizing:border-box}
                body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;margin:0;padding:20px;background:#f3f4f6;color:#111827}
                .cc{max-width:580px;margin:40px auto;background:#fff;border-radius:14px;box-shadow:0 4px 24px rgba(0,0,0,.09);overflow:hidden}
                .ch{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;padding:32px;text-align:center}
                .ch h1{margin:0 0 6px;font-size:22px}
                .ch p{margin:0;opacity:.9;font-size:15px}
                .cb{padding:28px 32px}
                .row{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px}
                .pill{background:#eef2ff;color:#4f46e5;border-radius:20px;padding:5px 14px;font-size:13px;font-weight:500}
                .notice{padding:16px;border-radius:8px;font-size:14px;margin-bottom:18px;line-height:1.5}
                .notice.info{background:#eef2ff;color:#3730a3;border-left:4px solid #667eea}
                .notice.warn{background:#fff7ed;color:#9a3412;border-left:4px solid #f97316}
                .notice.error{background:#fef2f2;color:#991b1b;border-left:4px solid #ef4444}
                .btn{display:inline-block;padding:12px 28px;border-radius:8px;font-size:15px;font-weight:600;text-decoration:none;margin-top:6px}
                .btn-primary{background:#667eea;color:#fff}
                .btn-ghost{color:#667eea;border:1px solid #c7d2fe}
                .label{font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px}
            </style>
        </head>
        <body>
        <div class="cc">
            <div class="ch">
                <h1><?php echo esc_html( $plan_name ); ?></h1>
                <p><?php echo esc_html( $price_display ); ?></p>
            </div>
            <div class="cb">
                <p><strong><?php esc_html_e( 'Subscriber:', 'subscription-system' ); ?></strong>
                   <?php echo esc_html( $subscription->subscriber_name ); ?>
                   &lt;<?php echo esc_html( $subscription->subscriber_email ); ?>&gt;</p>

                <?php if ( ! empty( $category_names ) || ! empty( $tag_names ) ) : ?>
                <p class="label"><?php esc_html_e( 'Subscribing to', 'subscription-system' ); ?></p>
                <div class="row">
                    <?php foreach ( $category_names as $n ) : ?>
                        <span class="pill">📁 <?php echo esc_html( $n ); ?></span>
                    <?php endforeach; ?>
                    <?php foreach ( $tag_names as $n ) : ?>
                        <span class="pill">🏷️ <?php echo esc_html( $n ); ?></span>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>

                <?php if ( $cancelled ) : ?>
                <div class="notice warn">
                    <?php esc_html_e( 'Payment was cancelled. Your subscription has not been activated. You can try again below.', 'subscription-system' ); ?>
                </div>
                <?php endif; ?>

                <?php if ( ! empty( $stripe_error ) ) : ?>
                <div class="notice error">
                    <strong><?php esc_html_e( 'Stripe error:', 'subscription-system' ); ?></strong>
                    <?php echo esc_html( $stripe_error ); ?>
                </div>
                <?php endif; ?>

                <?php if ( ! $stripe_enabled || empty( $api_key ) ) : ?>
                <div class="notice info">
                    <strong><?php esc_html_e( 'Action required:', 'subscription-system' ); ?></strong>
                    <?php esc_html_e( 'Stripe is not configured yet. To accept payments, go to your admin panel and add your Stripe API keys.', 'subscription-system' ); ?>
                    <?php if ( current_user_can( 'manage_options' ) ) : ?>
                        <br><br>
                        <a class="btn btn-primary" href="<?php echo esc_url( $stripe_setup ); ?>">
                            <?php esc_html_e( '⚙ Configure Stripe →', 'subscription-system' ); ?>
                        </a>
                    <?php endif; ?>
                </div>
                <?php else : ?>
                <div class="notice info">
                    <?php esc_html_e( 'Your subscription preferences are saved. There was a problem launching Stripe. Please contact the site administrator.', 'subscription-system' ); ?>
                </div>
                <?php endif; ?>

                <p style="margin-top:24px">
                    <a class="btn btn-ghost" href="<?php echo esc_url( home_url( '/' ) ); ?>">
                        &larr; <?php esc_html_e( 'Back to Home', 'subscription-system' ); ?>
                    </a>
                </p>
            </div>
        </div>
        <?php wp_footer(); ?>
        </body>
        </html>
        <?php
        exit;
    }

    /**
     * Handle Stripe success redirect after interest subscription payment.
     */
    public function handle_interest_checkout_success() {
        if ( ! isset( $_GET['action'] ) || 'interest_checkout_success' !== $_GET['action'] ) {
            return;
        }

        $subscription_id = isset( $_GET['interest_subscription_id'] ) ? absint( $_GET['interest_subscription_id'] ) : 0;
        $session_id      = isset( $_GET['session_id'] ) ? sanitize_text_field( wp_unslash( $_GET['session_id'] ) ) : '';

        if ( ! $subscription_id ) {
            wp_die( esc_html__( 'Invalid subscription.', 'subscription-system' ) );
        }

        $interest     = new Subs_Sys_Interest_Subscription();
        $subscription = $interest->get_subscription( $subscription_id );

        if ( ! $subscription ) {
            wp_die( esc_html__( 'Subscription not found.', 'subscription-system' ) );
        }

        // Verify with Stripe if session ID is provided.
        $verified = false;
        if ( ! empty( $session_id ) ) {
            $test_mode = get_option( 'subscription_stripe_test_mode', 1 );
            $api_key   = $test_mode
                ? get_option( 'subscription_stripe_test_secret_key', '' )
                : get_option( 'subscription_stripe_live_secret_key', '' );
            if ( empty( $api_key ) ) {
                $api_key = get_option( 'subscription_stripe_secret_key', '' );
            }

            if ( ! empty( $api_key ) && class_exists( '\Stripe\Stripe' ) ) {
                try {
                    \Stripe\Stripe::setApiKey( $api_key );
                    $session  = \Stripe\Checkout\Session::retrieve( $session_id );
                    $verified = in_array( $session->payment_status, array( 'paid', 'no_payment_required' ), true );
                } catch ( \Exception $e ) {
                    // Verification failed — still activate (webhook will handle edge cases).
                    $verified = false;
                }
            }
        }

        // Activate the subscription (Stripe verified, or session_id was absent — trust the redirect).
        if ( $verified || empty( $session_id ) ) {
            $interest->activate_paid_subscription( $subscription_id, $session_id );
        }

        // Build a clean success page.
        $category_names = array();
        $tag_names      = array();
        foreach ( (array) $subscription->category_ids as $cat_id ) {
            $term = get_term( $cat_id, 'category' );
            if ( $term && ! is_wp_error( $term ) ) { $category_names[] = $term->name; }
        }
        foreach ( (array) $subscription->tag_ids as $tag_id ) {
            $term = get_term( $tag_id, 'post_tag' );
            if ( $term && ! is_wp_error( $term ) ) { $tag_names[] = $term->name; }
        }

        status_header( 200 );
        nocache_headers();
        ?>
        <!DOCTYPE html>
        <html <?php language_attributes(); ?>>
        <head>
            <meta charset="<?php bloginfo( 'charset' ); ?>">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title><?php esc_html_e( 'Subscription Activated', 'subscription-system' ); ?></title>
            <?php wp_head(); ?>
            <style>
                *{box-sizing:border-box}
                body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;margin:0;padding:20px;background:#f3f4f6;color:#111827}
                .cc{max-width:520px;margin:60px auto;background:#fff;border-radius:14px;box-shadow:0 4px 24px rgba(0,0,0,.09);padding:40px;text-align:center}
                .icon{font-size:56px;margin-bottom:12px}
                h1{margin:0 0 10px;font-size:24px;color:#111827}
                p{color:#6b7280;font-size:15px;margin:0 0 20px;line-height:1.6}
                .row{display:flex;gap:8px;flex-wrap:wrap;justify-content:center;margin:16px 0 28px}
                .pill{background:#d1fae5;color:#065f46;border-radius:20px;padding:6px 16px;font-size:13px;font-weight:500}
                .btn{display:inline-block;padding:13px 30px;border-radius:8px;font-size:15px;font-weight:600;text-decoration:none;background:#667eea;color:#fff}
            </style>
        </head>
        <body>
        <div class="cc">
            <div class="icon">🎉</div>
            <h1><?php esc_html_e( 'You\'re subscribed!', 'subscription-system' ); ?></h1>
            <p><?php esc_html_e( 'Your subscription is now active. You\'ll receive email notifications when new content is published in:', 'subscription-system' ); ?></p>
            <div class="row">
                <?php foreach ( $category_names as $n ) : ?>
                    <span class="pill">📁 <?php echo esc_html( $n ); ?></span>
                <?php endforeach; ?>
                <?php foreach ( $tag_names as $n ) : ?>
                    <span class="pill">🏷️ <?php echo esc_html( $n ); ?></span>
                <?php endforeach; ?>
            </div>
            <a class="btn" href="<?php echo esc_url( home_url( '/' ) ); ?>">
                <?php esc_html_e( 'Back to Home', 'subscription-system' ); ?>
            </a>
        </div>
        <?php wp_footer(); ?>
        </body>
        </html>
        <?php
        exit;
    }

    /**
     * Handle content subscription success redirect
     */
    public function handle_content_subscription_success() {
        // Check if this is a content subscription success redirect
        if (isset($_GET['content_subscription_success']) && $_GET['content_subscription_success'] === '1' && isset($_GET['plan_id'])) {
            $plan_id = intval($_GET['plan_id']);
            $user_id = get_current_user_id();
            
            if ($plan_id > 0 && $user_id > 0) {
                // Log the redirect processing
                error_log("Processing content subscription success redirect. User: $user_id, Plan: $plan_id");
                
                // Initialize content manager
                $content_manager = new Subs_Sys_Content_Manager();
                
                // Ensure content tables exist
                if (!Subs_Sys_DB_Updater::content_tables_exist()) {
                    $db_updater = new Subs_Sys_DB_Updater();
                    $db_updater->add_content_subscription_tables();
                    error_log('Content tables created from success redirect');
                }
                
                // Check if user is already subscribed
                $existing_subscription = $content_manager->get_user_content_subscription($user_id, $plan_id);
                if (!$existing_subscription || $existing_subscription->status !== 'active') {
                    // Create the content subscription since payment was successful
                    $result = $content_manager->subscribe_user_to_content($user_id, $plan_id);
                    
                    if (is_wp_error($result)) {
                        error_log('Failed to create content subscription from success redirect: ' . $result->get_error_message());
                    } else {
                        error_log("Content subscription created successfully from success redirect. Subscription ID: $result");
                    }
                }
                
                // Check if a dedicated success page is configured
                $success_page_id = get_option('content_subscription_success_page');
                if ($success_page_id && $success_page_id > 0) {
                    // Redirect to the dedicated success page
                    $redirect_url = get_permalink($success_page_id);
                    $redirect_url = add_query_arg([
                        'subscription_success' => '1',
                        'plan_id' => $plan_id,
                        'message' => urlencode('Payment successful! Your subscription is now active.')
                    ], $redirect_url);
                } else {
                    // Fallback to current page with success parameters
                    $redirect_url = remove_query_arg(['content_subscription_success', 'plan_id']);
                    $redirect_url = add_query_arg([
                        'subscription_success' => '1',
                        'message' => urlencode('Payment successful! Your subscription is now active.')
                    ], $redirect_url);
                }
                
                wp_redirect($redirect_url);
                exit;
            }
        }
    }

    /**
     * Display subscription success message
     */
    public function display_subscription_success_message() {
        // Check if this is a subscription success page
        if (isset($_GET['subscription_success']) && $_GET['subscription_success'] === '1') {
            $message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : 'Successfully subscribed! Your subscription is now active.';
            ?>
            <style>
                            .subscription-success-banner {
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    background: linear-gradient(90deg, #4a90e2, #357ab8);
                    color: white;
                    padding: 16px 20px;
                    z-index: 10001;
                    text-align: center;
                    box-shadow: 0 4px 10px rgba(74, 144, 226, 0.2);
                    animation: slideDownSuccess 0.5s cubic-bezier(0.16, 1, 0.3, 1);
                    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                }
            
            .subscription-success-banner .success-content {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: 12px;
                max-width: 1200px;
                margin: 0 auto;
            }
            
            .subscription-success-banner .success-icon {
                width: 24px;
                height: 24px;
                flex-shrink: 0;
            }
            
            .subscription-success-banner .success-text {
                font-size: 16px;
                font-weight: 600;
            }
            
            .subscription-success-banner .close-success {
                position: absolute;
                right: 20px;
                top: 50%;
                transform: translateY(-50%);
                background: none;
                border: none;
                color: white;
                font-size: 20px;
                cursor: pointer;
                padding: 4px;
                line-height: 1;
                opacity: 0.8;
                transition: opacity 0.2s;
            }
            
            .subscription-success-banner .close-success:hover {
                opacity: 1;
            }
            
            @keyframes slideDownSuccess {
                from {
                    transform: translateY(-100%);
                    opacity: 0;
                }
                to {
                    transform: translateY(0);
                    opacity: 1;
                }
            }
            
            /* Add top margin to body to prevent content overlap */
            body.has-success-banner {
                margin-top: 60px !important;
            }
            
            @media (max-width: 768px) {
                .subscription-success-banner {
                    padding: 12px 16px;
                }
                .subscription-success-banner .success-text {
                    font-size: 14px;
                }
                body.has-success-banner {
                    margin-top: 50px !important;
                }
            }
            </style>
            
            <div id="subscription-success-banner" class="subscription-success-banner">
                <div class="success-content">
                    <div class="success-icon">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </div>
                    <div class="success-text">
                        🎉 <?php echo esc_html($message); ?>
                    </div>
                </div>
                <button class="close-success" onclick="closeSuccessBanner()" aria-label="Close success message">×</button>
            </div>
            
            <script>
            // Add body class for margin
            document.body.classList.add('has-success-banner');
            
            // Auto-hide after 8 seconds
            setTimeout(function() {
                closeSuccessBanner();
            }, 8000);
            
            // Close success banner function
            function closeSuccessBanner() {
                const banner = document.getElementById('subscription-success-banner');
                if (banner) {
                    banner.style.transform = 'translateY(-100%)';
                    banner.style.opacity = '0';
                    document.body.classList.remove('has-success-banner');
                    setTimeout(function() {
                        banner.remove();
                    }, 300);
                }
            }
            </script>
            <?php
        }
    }

    /**
     * Get applicable content plans for the current page
     */
    private function get_applicable_plans_for_current_page($content_manager) {
        $applicable_plans = [];


        // Handle different page types
        if (is_single() || is_page()) {
            // Single post or page
            $post_id = get_the_ID();
            if ($post_id) {
                $applicable_plans = $content_manager->get_applicable_content_plans($post_id);
            }
        } elseif (is_category()) {
            // Category archive page
            $category = get_queried_object();
            if ($category && isset($category->term_id)) {
                $category_plans = $content_manager->get_content_plans([
                    'content_type' => 'category',
                    'status' => 'active'
                ]);
                
                // Filter plans that include this category
                foreach ($category_plans as $plan) {
                    if (is_array($plan->content_ids) && in_array($category->term_id, $plan->content_ids)) {
                        $applicable_plans[] = $plan;
                    }
                }
            }
        } elseif (is_tag()) {
            // Tag archive page
            $tag = get_queried_object();
            if ($tag && isset($tag->term_id)) {
                $tag_plans = $content_manager->get_content_plans([
                    'content_type' => 'tag',
                    'status' => 'active'
                ]);
                
                // Filter plans that include this tag
                foreach ($tag_plans as $plan) {
                    if (is_array($plan->content_ids) && in_array($tag->term_id, $plan->content_ids)) {
                        $applicable_plans[] = $plan;
                    }
                }
            }
        } elseif (is_post_type_archive()) {
            // Post type archive page
            $post_type = get_query_var('post_type');
            if ($post_type) {
                $post_type_plans = $content_manager->get_content_plans([
                    'content_type' => 'post_type',
                    'status' => 'active'
                ]);
                // Filter plans that include this post type
                foreach ($post_type_plans as $plan) {
                    if (is_array($plan->content_ids) && in_array($post_type, $plan->content_ids)) {
                        $applicable_plans[] = $plan;
                    }
                }
            }
        } elseif (is_tax()) {
            // Custom taxonomy archive page
            $term = get_queried_object();
            if ($term && isset($term->term_id)) {
                // Check if we have plans for this taxonomy (treating as category for now)
                $tax_plans = $content_manager->get_content_plans([
                    'content_type' => 'category',
                    'status' => 'active'
                ]);
                // Filter plans that include this term
                foreach ($tax_plans as $plan) {
                    if (is_array($plan->content_ids) && in_array($term->term_id, $plan->content_ids)) {
                        $applicable_plans[] = $plan;
                    }
                }
            }
        }

        // Remove duplicates
        $applicable_plans = array_unique($applicable_plans, SORT_REGULAR);


        return $applicable_plans;
    }

    // ──────────────────────────────────────────────────────────────────────────
    // Subscribe Button & Modal Trigger helpers
    // ──────────────────────────────────────────────────────────────────────────

    /**
     * Determine whether the modal triggers should render on the current page,
     * based on the admin Display Settings.
     *
     * @return bool
     */
    private function should_render_modal_triggers() {
        // All posts (any singular post type except page).
        if ( get_option( 'subs_modal_display_all_posts', 0 ) && is_singular() && ! is_page() ) {
            return true;
        }

        // All pages.
        if ( get_option( 'subs_modal_display_all_pages', 0 ) && is_page() ) {
            return true;
        }

        // Single posts only.
        if ( get_option( 'subs_modal_display_single_posts', 0 ) && is_single() ) {
            return true;
        }

        // Single pages only.
        if ( get_option( 'subs_modal_display_single_pages', 0 ) && is_page() && is_singular() ) {
            return true;
        }

        // Custom post types.
        $selected_cpts = (array) get_option( 'subs_modal_display_post_types', array() );
        if ( ! empty( $selected_cpts ) && is_singular( $selected_cpts ) ) {
            return true;
        }

        // Specific pages.
        $specific_pages = array_map( 'absint', (array) get_option( 'subs_modal_display_specific_pages', array() ) );
        if ( ! empty( $specific_pages ) && is_page( $specific_pages ) ) {
            return true;
        }

        return false;
    }

    /**
     * Collect context data (category/tag IDs) for the current post.
     *
     * @return array{category_ids: int[], tag_ids: int[]}
     */
    private function get_current_post_context() {
        $context = array( 'category_ids' => array(), 'tag_ids' => array() );

        if ( ! is_singular() ) {
            return $context;
        }

        $post_id = get_the_ID();
        if ( ! $post_id ) {
            return $context;
        }

        if ( get_option( 'subs_modal_context_categories', 1 ) ) {
            $cats = wp_get_post_categories( $post_id, array( 'fields' => 'ids' ) );
            $context['category_ids'] = array_map( 'intval', is_array( $cats ) ? $cats : array() );
        }

        if ( get_option( 'subs_modal_context_tags', 1 ) ) {
            $tags = wp_get_post_tags( $post_id, array( 'fields' => 'ids' ) );
            $context['tag_ids'] = array_map( 'intval', is_array( $tags ) ? $tags : array() );
        }

        return $context;
    }

    /**
     * Output the floating button and/or auto-open modal in wp_footer,
     * respecting the configured display settings.
     */
    public function render_interest_modal_triggers() {
        $show_floating = (bool) get_option( 'subs_modal_floating_btn', 0 );
        $auto_open     = (bool) get_option( 'subs_modal_auto_open', 0 );

        if ( ! $show_floating && ! $auto_open ) {
            return;
        }

        if ( ! $this->should_render_modal_triggers() ) {
            return;
        }

        // Enqueue the modal assets (shared helper, safe to call multiple times).
        subs_sys_enqueue_interest_modal_assets( $this->plugin_name, $this->version );

        $modal_id = 'ss-interest-modal-footer';
        $btn_text = get_option( 'subs_modal_floating_btn_text', __( 'Subscribe', 'subscription-system' ) );
        $btn_pos  = sanitize_key( get_option( 'subs_modal_floating_btn_position', 'bottom-right' ) );
        $context  = $this->get_current_post_context();

        // Only show the categories/tags actually assigned to the current post.
        // Falls back to all available on non-singular pages (archives, home, etc.).
        if ( ! empty( $context['category_ids'] ) ) {
            $categories = Subs_Sys_Interest_Subscription::get_categories_by_ids( $context['category_ids'] );
        } else {
            $categories = Subs_Sys_Interest_Subscription::get_available_categories();
        }

        if ( ! empty( $context['tag_ids'] ) ) {
            $tags = Subs_Sys_Interest_Subscription::get_tags_by_ids( $context['tag_ids'] );
        } else {
            $tags = Subs_Sys_Interest_Subscription::get_available_tags();
        }

        $plans = Subs_Sys_Interest_Subscription::get_content_modal_plans( $context['category_ids'], $context['tag_ids'] );

        // Output floating button.
        if ( $show_floating ) {
            printf(
                '<button type="button" class="ss-interest-subscribe-btn ss-interest-floating-btn ss-floating--%s" data-ss-open-interest-modal="#%s" aria-label="%s">%s</button>',
                esc_attr( $btn_pos ),
                esc_attr( $modal_id ),
                esc_attr( $btn_text ),
                esc_html( $btn_text )
            );
        }

        // Output the modal (with context data as data attributes for JS to pick up).
        $args = array(
            'modal_id'           => $modal_id,
            'categories'         => $categories,
            'tags'               => $tags,
            'plans'              => $plans,
            'plan_source'        => 'content',
            'context_categories' => $context['category_ids'],
            'context_tags'       => $context['tag_ids'],
        );

        // Pass auto-open data attribute so JS knows to open this specific modal.
        $data_auto_open = $auto_open ? ' data-ss-auto-open="1"' : '';
        echo '<div' . $data_auto_open . '>';
        include SUBS_SYS_PLUGIN_DIR . 'public/partials/interest-subscribe-modal.php';
        echo '</div>';
    }
} 