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

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

/**
 * Class for handling shortcodes
 */
class Subs_Sys_Shortcodes {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

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

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    string    $plugin_name       The name of the plugin.
     * @param    string    $version           The version of this plugin.
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        
        // Register shortcodes directly in the constructor
        add_shortcode('subscriptionsystem_register', array($this, 'render_registration_form'));
        add_shortcode('subscriptionsystem_login', array($this, 'render_login_form'));
        add_shortcode('subscriptionsystem_forgot_password', array($this, 'render_forgot_password_form'));
        add_shortcode('subscriptionsystem_account', array($this, 'render_account_dashboard'));
        add_shortcode('pricing_plans', array($this, 'pricing_plans_shortcode'));
        add_shortcode('subscription_checkout', array($this, 'subscription_checkout_shortcode'));
        add_shortcode('subscription_success', array($this, 'subscription_success_shortcode'));
        add_shortcode('content_subscription_plans', array($this, 'render_content_subscription_plans'));
        add_shortcode('content_subscription_checkout', array($this, 'render_content_subscription_checkout'));
        add_shortcode('content_subscription_success', array($this, 'render_content_subscription_success'));
        add_shortcode('subscriptionsystem_subscribe', array($this, 'render_interest_subscribe_button'));
        
        // Add AJAX handlers for password reset
        add_action('wp_ajax_nopriv_subs_sys_forgot_password', array($this, 'process_forgot_password'));
        add_action('wp_ajax_nopriv_subs_sys_reset_password', array($this, 'process_reset_password'));
        
        // Add AJAX handlers for account dashboard
        add_action('wp_ajax_subs_sys_update_profile', array($this, 'process_profile_update'));
        add_action('wp_ajax_update_billing_info', array($this, 'process_billing_update'));
        add_action('wp_ajax_subs_sys_update_avatar', array($this, 'process_avatar_update'));
    }

    /**
     * Render the registration form
     *
     * @since    1.0.0
     * @return   string    The HTML output for the registration form.
     */
    public function render_registration_form() {
        // Check if user is already logged in
        if (is_user_logged_in()) {
            return '<p class="subscription-system-message">You are already logged in. <a href="' . wp_logout_url(get_permalink()) . '">Logout</a></p>';
        }
        
        // Enqueue necessary scripts and styles
        wp_enqueue_style($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/css/subscription-system-forms.css', array(), time(), 'all');
        wp_enqueue_script($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/js/subscription-system-forms.js', array('jquery'), time(), false);
        
        // Add AJAX object
        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'),
        ));
        
        ob_start();
        include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-system-register-form.php';
        return ob_get_clean();
    }
    
    /**
     * Render the login form
     *
     * @since    1.0.0
     * @return   string    The HTML output for the login form.
     */
    public function render_login_form() {
        // Check if user is already logged in
        if (is_user_logged_in()) {
            return '<p class="subscription-system-message">You are already logged in. <a href="' . wp_logout_url(get_permalink()) . '">Logout</a></p>';
        }
        
        // Enqueue necessary scripts and styles
        wp_enqueue_style($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/css/subscription-system-forms.css', array(), time(), 'all');
        wp_enqueue_script($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/js/subscription-system-forms.js', array('jquery'), time(), false);
        
        // Add AJAX object
        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'),
        ));
        
        ob_start();
        include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-system-login-form.php';
        return ob_get_clean();
    }

    /**
     * Render the pricing plans shortcode.
     *
     * @param array $atts Shortcode attributes.
     * @return string The shortcode output.
     */
    public function pricing_plans_shortcode($atts) {
        // Parse shortcode attributes
        $atts = shortcode_atts(
            array(
                'layout' => get_option('subscription_default_layout', 'layout1'),
                'category' => '',
                'code' => '',  // New attribute for category ID
                'columns' => '3',
                'orientation' => 'vertical', // New attribute for orientation
            ),
            $atts,
            'pricing_plans'
        );

        // Get plans from database
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_plans';
        $categories_table = $wpdb->prefix . 'subscription_categories';
        
        $sql = "SELECT p.* FROM $table_name p WHERE p.status = 'active'";
        
        // Add category filter if specified by name
        if (!empty($atts['category'])) {
            // Join with categories table to filter by category name
            $sql = "SELECT p.* FROM $table_name p 
                    JOIN $categories_table c ON p.category_id = c.id 
                    WHERE p.status = 'active' AND c.category_name = %s";
            $sql = $wpdb->prepare($sql, $atts['category']);
        }
        // Add category filter if specified by ID (code)
        elseif (!empty($atts['code'])) {
            // Filter by category ID directly
            $sql = "SELECT p.* FROM $table_name p 
                    WHERE p.status = 'active' AND p.category_id = %d";
            $sql = $wpdb->prepare($sql, intval($atts['code']));
        }
        
        $sql .= " ORDER BY p.price ASC";
        
        $plans = $wpdb->get_results($sql);
        
        // Start output buffering
        ob_start();
        
        // Add horizontal class if orientation is horizontal
        $orientation_class = ($atts['orientation'] === 'horizontal') ? 'horizontal' : '';
        
        // Include the appropriate template based on layout
        switch ($atts['layout']) {
            case 'layout2':
                include plugin_dir_path(dirname(__FILE__)) . 'public/partials/pricing-plans-layout2.php';
                break;
            case 'layout3':
                include plugin_dir_path(dirname(__FILE__)) . 'public/partials/pricing-plans-layout3.php';
                break;
            case 'layout1':
            default:
                include plugin_dir_path(dirname(__FILE__)) . 'public/partials/pricing-plans-layout1.php';
                break;
        }
        
        // Return the buffered content
        return ob_get_clean();
    }
    
    /**
     * Render the forgot password form
     *
     * @since    1.0.0
     * @return   string    The HTML output for the forgot password form.
     */
    public function render_forgot_password_form() {
        // If user is logged in, no need for password reset
        if (is_user_logged_in()) {
            return '<p class="subscription-system-message">You are already logged in. <a href="' . wp_logout_url(get_permalink()) . '">Logout</a></p>';
        }
        
        // Check if this is a password reset link
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
        $key = isset($_GET['key']) ? sanitize_text_field($_GET['key']) : '';
        $login = isset($_GET['login']) ? sanitize_text_field($_GET['login']) : '';
        
        // Enqueue necessary scripts and styles
        wp_enqueue_style($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/css/subscription-system-forms.css', array(), time(), 'all');
        wp_enqueue_script($this->plugin_name . '-forms', plugin_dir_url(dirname(__FILE__)) . 'public/js/subscription-system-forms.js', array('jquery'), time(), false);
        
        // Add AJAX object
        wp_localize_script($this->plugin_name . '-forms', 'subs_sys_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'forgot_password_nonce' => wp_create_nonce('subs_sys_forgot_password_nonce'),
            'reset_password_nonce' => wp_create_nonce('subs_sys_reset_password_nonce'),
        ));
        
        ob_start();
        
        if ($action === 'rp' && !empty($key) && !empty($login)) {
            // This is a password reset link, show the reset password form
            include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-system-reset-password-form.php';
        } else {
            // Show the forgot password form
            include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-system-forgot-password-form.php';
        }
        
        return ob_get_clean();
    }
    
    /**
     * Render the account dashboard
     *
     * @since    1.0.0
     * @return   string    The HTML output for the account dashboard.
     */
    public function render_account_dashboard() {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            // Get login page
            $login_page_id = get_option('login_page', 0);
            $login_url = $login_page_id ? get_permalink($login_page_id) : wp_login_url();
            
            return '<div class="subscription-system-message error">You must be logged in to view your account. <a href="' . esc_url($login_url) . '">Login here</a></div>';
        }
        
        // Enqueue necessary scripts and styles
        wp_enqueue_style($this->plugin_name . '-account', plugin_dir_url(dirname(__FILE__)) . 'public/css/subscription-system-account.css', array(), $this->version, 'all');
        wp_enqueue_script($this->plugin_name . '-account', plugin_dir_url(dirname(__FILE__)) . 'public/js/subscription-system-account.js', array('jquery'), $this->version, false);
        
        // Add AJAX object
        wp_localize_script($this->plugin_name . '-account', 'subs_sys_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'avatar_nonce' => wp_create_nonce('update_avatar_nonce')
        ));
        
        // Get current user
        $current_user = wp_get_current_user();
        
        // Get user data
        $user_id = $current_user->ID;
        $first_name = get_user_meta($user_id, 'first_name', true);
        $last_name = get_user_meta($user_id, 'last_name', true);
        $email = $current_user->user_email;
        $username = $current_user->user_login;
        $role = implode(', ', $current_user->roles);
        
        // Get custom avatar if available
        $profile_image_id = get_user_meta($user_id, 'profile_image', true);
        if ($profile_image_id) {
            $avatar_url = wp_get_attachment_image_url($profile_image_id, 'thumbnail');
            $avatar = '<img src="' . esc_url($avatar_url) . '" alt="' . esc_attr($first_name . ' ' . $last_name) . '">';
        } else {
            // Use default avatar
            $avatar = get_avatar($user_id, 96, '', $first_name . ' ' . $last_name);
        }
        
        // Get active tab
        $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'overview';
        
        ob_start();
        include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-system-account.php';
        return ob_get_clean();
    }
    
    /**
     * Process the registration form submission
     *
     * @since    1.0.0
     */
    public function process_registration() {
        // Check nonce for security
        check_ajax_referer('subs_sys_register_nonce', 'security');
        
        $response = array(
            'success' => false,
            'message' => ''
        );
        
        // Validate required fields
        $first_name = isset($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
        $last_name = isset($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
        $username = isset($_POST['username']) ? sanitize_user($_POST['username']) : '';
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        
        // Validate required fields
        if (empty($username) || empty($email) || empty($password)) {
            $response['message'] = 'Required fields cannot be empty.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if username already exists
        if (username_exists($username)) {
            $response['message'] = 'Username already exists. Please choose another one.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if email already exists
        if (email_exists($email)) {
            $response['message'] = 'Email already exists. Please use another email or login.';
            wp_send_json($response);
            wp_die();
        }
        
        // Create the user
        $user_id = wp_create_user($username, $password, $email);
        
        if (is_wp_error($user_id)) {
            $response['message'] = $user_id->get_error_message();
            wp_send_json($response);
            wp_die();
        }
        
        // Update user meta
        update_user_meta($user_id, 'first_name', $first_name);
        update_user_meta($user_id, 'last_name', $last_name);
        
        // Set the user role
        $user = new WP_User($user_id);
        $user->set_role('subscriber');
        
        // Auto login user
        wp_set_current_user($user_id);
        wp_set_auth_cookie($user_id);
        
        $response['success'] = true;
        $response['message'] = 'Registration successful! Redirecting...';
        
        // Get the account page ID from options
        $account_page_id = get_option('account_page', 0);
        
        // If account page is set, redirect to it, otherwise redirect to home
        $response['redirect'] = $account_page_id ? get_permalink($account_page_id) : home_url();
        
        wp_send_json($response);
        wp_die();
    }
    
    /**
     * Process the login form submission
     *
     * @since    1.0.0
     */
    public function process_login() {
        // Check nonce for security
        check_ajax_referer('subs_sys_login_nonce', 'security');
        
        $response = array(
            'success' => false,
            'message' => ''
        );
        
        $username_email = isset($_POST['username_email']) ? sanitize_text_field($_POST['username_email']) : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
        $remember = isset($_POST['remember']) ? (bool) $_POST['remember'] : false;
        
        // Validate required fields
        if (empty($username_email) || empty($password)) {
            $response['message'] = 'Username/Email and password are required.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if username_email is an email
        if (is_email($username_email)) {
            $user = get_user_by('email', $username_email);
            if ($user) {
                $username_email = $user->user_login;
            }
        }
        
        // Attempt to log the user in
        $user = wp_signon(array(
            'user_login' => $username_email,
            'user_password' => $password,
            'remember' => $remember
        ), false);
        
        if (is_wp_error($user)) {
            $response['message'] = 'Invalid username/email or password.';
            wp_send_json($response);
            wp_die();
        }
        
        $response['success'] = true;
        $response['message'] = 'Login successful! Redirecting...';
        
        // Get the account page ID from options
        $account_page_id = get_option('account_page', 0);
        
        // If account page is set, redirect to it, otherwise redirect to home
        $response['redirect'] = $account_page_id ? get_permalink($account_page_id) : home_url();
        
        wp_send_json($response);
        wp_die();
    }

    /**
     * Process the forgot password form submission
     *
     * @since    1.0.0
     */
    public function process_forgot_password() {
        // Check nonce for security
        check_ajax_referer('subs_sys_forgot_password_nonce', 'security');
        
        $response = array(
            'success' => false,
            'message' => ''
        );
        
        $user_login = isset($_POST['user_login']) ? sanitize_text_field($_POST['user_login']) : '';
        
        if (empty($user_login)) {
            $response['message'] = 'Please enter a username or email address.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if it's an email or username
        if (is_email($user_login)) {
            $user_data = get_user_by('email', $user_login);
        } else {
            $user_data = get_user_by('login', $user_login);
        }
        
        if (!$user_data) {
            $response['message'] = 'No account found with that username or email address.';
            wp_send_json($response);
            wp_die();
        }
        
        // Generate a password reset key
        $key = get_password_reset_key($user_data);
        
        if (is_wp_error($key)) {
            $response['message'] = 'Error generating password reset link. Please try again later.';
            wp_send_json($response);
            wp_die();
        }
        
        // Get the reset password page URL
        $reset_page_id = get_option('forgot_password_page', 0);
        $reset_page_url = $reset_page_id ? get_permalink($reset_page_id) : home_url('/forgot-password/');
        
        // Build the reset link
        $reset_link = add_query_arg(
            array(
                'action' => 'rp',
                'key' => $key,
                'login' => rawurlencode($user_data->user_login)
            ),
            $reset_page_url
        );
        
        // Set up email subject
        /* translators: %s: website name */
        $subject = sprintf(__('[%s] Password Reset', 'subscription-system'), get_bloginfo('name'));
        
        // Build email message
        /* translators: %s: website name */
        $message = __('Someone has requested a password reset for the following account:', 'subscription-system') . "\r\n\r\n";
        /* translators: %s: website name */
        $message .= sprintf(__('Site Name: %s', 'subscription-system'), get_bloginfo('name')) . "\r\n\r\n";
        /* translators: %s: username */
        $message .= sprintf(__('Username: %s', 'subscription-system'), $user_data->user_login) . "\r\n\r\n";
        $message .= __('If this was a mistake, just ignore this email and nothing will happen.', 'subscription-system') . "\r\n\r\n";
        $message .= __('To reset your password, visit the following address:', 'subscription-system') . "\r\n\r\n";
        $message .= $reset_link . "\r\n\r\n";
        
        // Send email
        $mail_sent = wp_mail($user_data->user_email, $subject, $message);
        
        if ($mail_sent) {
            $response['success'] = true;
            $response['message'] = 'Password reset link has been sent to your email address.';
        } else {
            $response['message'] = 'Error sending email. Please try again later.';
        }
        
        wp_send_json($response);
        wp_die();
    }

    /**
     * Process the reset password form submission
     *
     * @since    1.0.0
     */
    public function process_reset_password() {
        // Check nonce for security
        check_ajax_referer('subs_sys_reset_password_nonce', 'security');
        
        $response = array(
            'success' => false,
            'message' => ''
        );
        
        $rp_key = isset($_POST['rp_key']) ? sanitize_text_field($_POST['rp_key']) : '';
        $rp_login = isset($_POST['rp_login']) ? sanitize_text_field($_POST['rp_login']) : '';
        $pass1 = isset($_POST['pass1']) ? $_POST['pass1'] : '';
        $pass2 = isset($_POST['pass2']) ? $_POST['pass2'] : '';
        
        // Validate required fields
        if (empty($rp_key) || empty($rp_login) || empty($pass1) || empty($pass2)) {
            $response['message'] = 'All fields are required.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if passwords match
        if ($pass1 !== $pass2) {
            $response['message'] = 'Passwords do not match.';
            wp_send_json($response);
            wp_die();
        }
        
        // Get user by login
        $user = get_user_by('login', $rp_login);
        
        if (!$user) {
            $response['message'] = 'Invalid username.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check the reset key
        $check = check_password_reset_key($rp_key, $rp_login);
        
        if (is_wp_error($check)) {
            $response['message'] = 'The reset link has expired or is invalid. Please request a new password reset link.';
            wp_send_json($response);
            wp_die();
        }
        
        // Reset the password
        reset_password($user, $pass1);
        
        $response['success'] = true;
        $response['message'] = 'Your password has been reset successfully. You can now login with your new password.';
        $response['redirect'] = wp_login_url();
        
        wp_send_json($response);
        wp_die();
    }

    /**
     * Process profile update
     *
     * @since    1.0.0
     */
    public function process_profile_update() {
        // Check nonce for security
        check_ajax_referer('update_profile_nonce', 'security');
        
        $response = array(
            'success' => false,
            'message' => '',
            'refresh' => false
        );
        
        // Get current user
        $user_id = get_current_user_id();
        
        if (!$user_id) {
            $response['message'] = 'You must be logged in to update your profile.';
            wp_send_json($response);
            wp_die();
        }
        
        // Get form data
        $action_type = isset($_POST['action_type']) ? sanitize_text_field($_POST['action_type']) : 'update_profile';
        $current_password = isset($_POST['current_password']) ? $_POST['current_password'] : '';
        
        // Verify current password
        $user = get_user_by('id', $user_id);
        
        // Handle different action types
        if ($action_type === 'update_profile') {
            // Get profile data
            $first_name = isset($_POST['first_name']) ? sanitize_text_field($_POST['first_name']) : '';
            $last_name = isset($_POST['last_name']) ? sanitize_text_field($_POST['last_name']) : '';
            $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
            
            // Check if email is already in use by another user
            if ($email !== $user->user_email) {
                $existing_user = get_user_by('email', $email);
                
                if ($existing_user && $existing_user->ID !== $user_id) {
                    $response['message'] = 'This email address is already in use by another user.';
                    wp_send_json($response);
                    wp_die();
                }
            }
            
            // Update user data
            $userdata = array(
                'ID' => $user_id,
                'user_email' => $email,
                'first_name' => $first_name,
                'last_name' => $last_name
            );
            
            // Update user
            $result = wp_update_user($userdata);
            
            if (is_wp_error($result)) {
                $response['message'] = $result->get_error_message();
            } else {
                $response['success'] = true;
                $response['message'] = 'Profile updated successfully.';
            }
        } else if ($action_type === 'change_password') {
            // Get password data
            $new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';
            $confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';
            
            // Verify current password for password changes
            if (empty($current_password)) {
                $response['message'] = 'Current password is required to change your password.';
                wp_send_json($response);
                wp_die();
            }
            
            if (!wp_check_password($current_password, $user->data->user_pass, $user_id)) {
                $response['message'] = 'Current password is incorrect.';
                wp_send_json($response);
                wp_die();
            }
            
            // Validate new password
            if (empty($new_password)) {
                $response['message'] = 'New password cannot be empty.';
                wp_send_json($response);
                wp_die();
            }
            
            // Check if passwords match
            if ($new_password !== $confirm_password) {
                $response['message'] = 'New passwords do not match.';
                wp_send_json($response);
                wp_die();
            }
            
            // Update user password
            $userdata = array(
                'ID' => $user_id,
                'user_pass' => $new_password
            );
            
            // Update user
            $result = wp_update_user($userdata);
            
            if (is_wp_error($result)) {
                $response['message'] = $result->get_error_message();
            } else {
                $response['success'] = true;
                $response['message'] = 'Password changed successfully. You will be redirected to login again.';
                $response['refresh'] = true;
            }
        }
        
        wp_send_json($response);
        wp_die();
    }

    /**
     * Process billing information update
     */
    public function process_billing_update() {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array('message' => __('You must be logged in to update billing information.', 'subscription-system')));
            return;
        }
        
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subs_sys_nonce')) {
            wp_send_json_error(array('message' => __('Security check failed.', 'subscription-system')));
            return;
        }
        
        // Get current user ID
        $user_id = get_current_user_id();
        
        // Fields to update
        $billing_fields = array(
            'billing_first_name',
            'billing_last_name',
            'billing_company',
            'billing_address_1',
            'billing_address_2',
            'billing_city',
            'billing_state',
            'billing_postcode',
            'billing_country',
            'billing_email',
            'billing_phone'
        );
        
        // Update each field
        $updated = false;
        foreach ($billing_fields as $field) {
            if (isset($_POST[$field])) {
                $value = sanitize_text_field($_POST[$field]);
                $current_value = get_user_meta($user_id, $field, true);
                
                // Only update if value has changed
                if ($value !== $current_value) {
                    update_user_meta($user_id, $field, $value);
                    $updated = true;
                }
            }
        }
        
        // Log the update for debugging
        error_log('Billing info update for user ' . $user_id . ': ' . ($updated ? 'Updated' : 'No changes'));
        
        // Return success response
        wp_send_json_success(array('message' => __('Billing information updated successfully.', 'subscription-system')));
    }

    /**
     * Process avatar update
     *
     * @since    1.0.0
     */
    public function process_avatar_update() {
        // Check nonce for security
        check_ajax_referer('update_avatar_nonce', 'security');
        
        $response = array(
            'success' => false,
            'data' => array(
                'message' => ''
            )
        );
        
        // Get current user
        $user_id = get_current_user_id();
        
        if (!$user_id) {
            $response['data']['message'] = 'You must be logged in to update your profile picture.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check if file was uploaded
        if (!isset($_FILES['profile_image']) || !is_uploaded_file($_FILES['profile_image']['tmp_name'])) {
            $response['data']['message'] = 'No file was uploaded.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check file type
        $file = $_FILES['profile_image'];
        $allowed_types = array('image/jpeg', 'image/png', 'image/gif');
        
        if (!in_array($file['type'], $allowed_types)) {
            $response['data']['message'] = 'Invalid file type. Please upload a JPEG, PNG, or GIF image.';
            wp_send_json($response);
            wp_die();
        }
        
        // Check file size (max 2MB)
        if ($file['size'] > 2 * 1024 * 1024) {
            $response['data']['message'] = 'File size should be less than 2MB.';
            wp_send_json($response);
            wp_die();
        }
        
        // Include WordPress media handling functions
        if (!function_exists('wp_handle_upload')) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
        }
        
        // Handle file upload
        $upload_overrides = array('test_form' => false);
        $uploaded_file = wp_handle_upload($file, $upload_overrides);
        
        if (isset($uploaded_file['error'])) {
            $response['data']['message'] = $uploaded_file['error'];
            wp_send_json($response);
            wp_die();
        }
        
        // Include image functions
        if (!function_exists('wp_crop_image')) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
        }
        
        // Create attachment
        $attachment = array(
            'guid' => $uploaded_file['url'],
            'post_mime_type' => $uploaded_file['type'],
            'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['name'])),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        // Insert attachment
        $attachment_id = wp_insert_attachment($attachment, $uploaded_file['file']);
        
        if (is_wp_error($attachment_id)) {
            $response['data']['message'] = $attachment_id->get_error_message();
            wp_send_json($response);
            wp_die();
        }
        
        // Generate metadata for the attachment
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $uploaded_file['file']);
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        
        // Update user meta
        update_user_meta($user_id, 'profile_image', $attachment_id);
        
        // Get avatar URL
        $avatar_url = wp_get_attachment_image_url($attachment_id, 'thumbnail');
        
        $response['success'] = true;
        $response['data']['message'] = 'Profile picture updated successfully.';
        $response['data']['avatar_url'] = $avatar_url;
        
        wp_send_json($response);
        wp_die();
    }
    
    /**
     * Subscription plans shortcode
     *
     * @param array $atts Shortcode attributes
     * @return string Shortcode output
     */
    public function subscription_plans_shortcode($atts) {
        // Enqueue necessary scripts
        wp_enqueue_script('jquery');
        
        // Get plans from database
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_plans';
        $plans = $wpdb->get_results("SELECT * FROM $table_name WHERE status = 'active' ORDER BY price ASC");
        
        // Start output buffering
        ob_start();
        
        // Include the template
        include plugin_dir_path(dirname(__FILE__)) . 'public/partials/subscription-plans-display.php';
        
        // Return the buffered content
        return ob_get_clean();
    }

    /**
     * Display subscription success message and details
     * 
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public function subscription_success_shortcode($atts) {
        // Get session ID from URL
        $session_id = isset($_GET['session_id']) ? sanitize_text_field($_GET['session_id']) : '';
        
        if (empty($session_id)) {
            return '<div class="subscription-error">No session ID provided.</div>';
        }
        
        try {
            // Initialize Stripe
            $stripe = new Subs_Sys_Stripe();
            $session = $stripe->get_session($session_id);
            
            if (!$session) {
                return '<div class="subscription-error">Invalid session ID.</div>';
            }
            
            // Get subscription details
            global $wpdb;
            $table_name = $wpdb->prefix . 'subscriptions';
            $subscription = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM $table_name WHERE payment_id = %s",
                $session_id
            ));
            
            if (!$subscription) {
                // Try to create the subscription if it doesn't exist
                $result = $this->create_subscription_from_session($session);
                
                if ($result) {
                    // Get the newly created subscription
                    $subscription = $wpdb->get_row($wpdb->prepare(
                        "SELECT * FROM $table_name WHERE payment_id = %s",
                        $session_id
                    ));
                }
            }
            
            // Get plan details
            $plan_table = $wpdb->prefix . 'subscription_plans';
            $plan = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM $plan_table WHERE id = %d",
                $subscription ? $subscription->plan_id : 0
            ));
            
            // Enqueue the CSS
            wp_enqueue_style('subscription-success-style', plugin_dir_url(dirname(__FILE__)) . 'public/css/subscription-success.css', array(), '1.0.0');
            
            ob_start();
            
            if ($subscription) {
                ?>
                <div class="subscription-success-container">
                    <div class="subscription-success-header">
                        <div class="success-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="64" height="64">
                                <circle cx="12" cy="12" r="11" fill="#4CAF50"/>
                                <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" fill="white"/>
                            </svg>
                        </div>
                        <h2>Thank You for Your Subscription!</h2>
                        <p class="success-message">Your payment has been processed successfully and your subscription is now active.</p>
                    </div>
                    
                    <div class="subscription-details-card">
                        <h3>Subscription Details</h3>
                        <div class="subscription-details-grid">
                            <div class="detail-item">
                                <span class="detail-label">Plan</span>
                                <span class="detail-value"><?php echo esc_html($plan ? $plan->plan_name : 'Unknown'); ?></span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Amount</span>
                                <span class="detail-value">$<?php echo esc_html(number_format($subscription->amount, 2)); ?></span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Status</span>
                                <span class="detail-value status-badge status-<?php echo esc_attr(strtolower($subscription->status)); ?>">
                                    <?php echo esc_html(ucfirst($subscription->status)); ?>
                                </span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Start Date</span>
                                <span class="detail-value"><?php echo esc_html(date('F j, Y', strtotime($subscription->start_date))); ?></span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">End Date</span>
                                <span class="detail-value"><?php echo esc_html(date('F j, Y', strtotime($subscription->end_date))); ?></span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Transaction ID</span>
                                <span class="detail-value"><?php echo esc_html($subscription->payment_id); ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="subscription-actions">
                        <a href="<?php echo esc_url(get_permalink(get_option('account_page'))); ?>" class="subscription-button primary-button">View Your Account</a>
                        <a href="<?php echo esc_url(home_url()); ?>" class="subscription-button secondary-button">Return to Homepage</a>
                    </div>
                    
                    <div class="subscription-help">
                        <p>If you have any questions about your subscription, please <a href="<?php echo esc_url(get_permalink(get_option('contact_page', 0)) ?: home_url('/contact/')); ?>">contact our support team</a>.</p>
                    </div>
                </div>
                <?php
            } else {
                ?>
                <div class="subscription-processing-container">
                    <div class="processing-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="64" height="64">
                            <circle cx="12" cy="12" r="11" fill="#FFC107"/>
                            <path d="M13 9h-2V7h2v2zm0 8h-2v-6h2v6z" fill="white"/>
                        </svg>
                    </div>
                    <h2>Subscription Processing</h2>
                    <p class="processing-message">Your payment has been received, but we're still processing your subscription.</p>
                    <p>This usually takes just a few moments. Please check your account shortly.</p>
                    
                    <div class="subscription-actions">
                        <a href="<?php echo esc_url(get_permalink(get_option('account_page'))); ?>" class="subscription-button primary-button">Go to Your Account</a>
                        <a href="<?php echo esc_url(home_url()); ?>" class="subscription-button secondary-button">Return to Homepage</a>
                    </div>
                </div>
                <?php
            }
            
            return ob_get_clean();
            
        } catch (\Exception $e) {
            return '<div class="subscription-error">Error: ' . esc_html($e->getMessage()) . '</div>';
        }
    }

    /**
     * Stripe checkout button shortcode
     * 
     * @param array $atts Shortcode attributes
     * @return string HTML output
     */
    public function stripe_checkout_button_shortcode($atts) {
        $atts = shortcode_atts(array(
            'plan_id' => 0,
            'button_text' => 'Subscribe Now',
            'price' => '',
            'name' => '',
        ), $atts, 'stripe_checkout');
        
        // If plan ID is provided, get plan details
        if (!empty($atts['plan_id'])) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'subscription_plans';
            $plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $atts['plan_id']));
            
            if ($plan) {
                $atts['name'] = $plan->plan_name;
                $atts['price'] = $plan->price;
            }
        }
        
        // Ensure we have required attributes
        if (empty($atts['name']) || empty($atts['price'])) {
            return '<p class="error">Error: Missing required attributes (name or price).</p>';
        }
        
        // Get Stripe publishable key
        $publishable_key = get_option('subscription_stripe_publishable_key');
        if (empty($publishable_key)) {
            return '<p class="error">Error: Stripe publishable key is not configured.</p>';
        }
        
        // Generate unique ID for this button
        $button_id = 'stripe-checkout-' . uniqid();
        
        // Start output buffering
        ob_start();
        ?>
        <button id="<?php echo esc_attr($button_id); ?>" class="stripe-checkout-button">
            <?php echo esc_html($atts['button_text']); ?>
        </button>
        
        <script src="https://js.stripe.com/v3/"></script>
        <script>
        (function() {
            var stripe = Stripe('<?php echo esc_js($publishable_key); ?>');
            var button = document.getElementById('<?php echo esc_js($button_id); ?>');
            
            button.addEventListener('click', function() {
                // Disable button
                button.disabled = true;
                button.textContent = 'Processing...';
                
                // Create checkout session
                fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'create_direct_checkout',
                        name: '<?php echo esc_js($atts['name']); ?>',
                        price: '<?php echo esc_js($atts['price']); ?>',
                        plan_id: '<?php echo esc_js($atts['plan_id']); ?>',
                        nonce: '<?php echo esc_attr(wp_create_nonce('stripe_checkout_nonce')); ?>'
                    })
                })
                .then(function(response) {
                    return response.json();
                })
                .then(function(session) {
                    if (session.success && session.data.id) {
                        return stripe.redirectToCheckout({ sessionId: session.data.id });
                    } else {
                        throw new Error(session.data.message || 'Could not create checkout session');
                    }
                })
                .then(function(result) {
                    if (result.error) {
                        throw new Error(result.error.message);
                    }
                })
                .catch(function(error) {
                    console.error('Error:', error);
                    alert('Error: ' + error.message);
                    
                    // Re-enable button
                    button.disabled = false;
                    button.textContent = '<?php echo esc_js($atts['button_text']); ?>';
                });
            });
        })();
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * Create subscription from session
     * 
     * @param object $session Stripe session object
     * @return int|false Subscription ID or false on failure
     */
    private function create_subscription_from_session($session) {
        try {
            // Get metadata
            $metadata = isset($session->metadata) ? $session->metadata : new stdClass();
            
            // Try to get plan_id from different sources
            $plan_id = null;
            if (isset($metadata->plan_id)) {
                $plan_id = $metadata->plan_id;
            } elseif (isset($session->client_reference_id)) {
                $plan_id = $session->client_reference_id;
            }
            
            // First check if a user is currently logged in
            $user_id = get_current_user_id();
            
            // If no logged-in user, try to get user_id from metadata
            if (!$user_id && isset($metadata->user_id)) {
                $user_id = $metadata->user_id;
            }
            
            // If still no user ID but have an email, try to find the user
            if (!$user_id && isset($session->customer_details) && isset($session->customer_details->email)) {
                $user = get_user_by('email', $session->customer_details->email);
                if ($user) {
                    $user_id = $user->ID;
                }
                // Removed user creation code - we don't want to create new users automatically
            }
            
            if (!$plan_id) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing plan ID
                error_log('Missing plan_id in session data');
                return false;
            }
            
            if (!$user_id) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing user ID
                error_log('Missing user_id in session data and could not find user by email');
                return false;
            }
            
            // Get customer details
            $customer_email = isset($session->customer_details->email) ? $session->customer_details->email : '';
            $customer_name = isset($session->customer_details->name) ? $session->customer_details->name : '';
            
            // If customer details are empty, get them from the user
            if (empty($customer_email) || empty($customer_name)) {
                $user = get_userdata($user_id);
                if ($user) {
                    $customer_email = empty($customer_email) ? $user->user_email : $customer_email;
                    $customer_name = empty($customer_name) ? $user->display_name : $customer_name;
                }
            }
            
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for subscription creation
            error_log("Creating subscription for user $user_id, plan $plan_id, email $customer_email");
            
            // Get plan details
            $manager = new Subs_Sys_Manager();
            $plan = $manager->get_plan($plan_id);
            
            if (!$plan) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing plan
                error_log('Plan not found with ID: ' . $plan_id);
                return false;
            }
            
            // Calculate end date
            $start_date = current_time('mysql');
            $duration = isset($plan->duration) ? intval($plan->duration) : 30;
            $end_date = date('Y-m-d H:i:s', strtotime("+$duration days", strtotime($start_date)));
            
            // Prepare subscription data
            $subscription_data = array(
                'user_id' => $user_id,
                'plan_id' => $plan_id,
                'customer_email' => $customer_email,
                'customer_name' => $customer_name,
                'payment_id' => $session->id,
                'amount' => isset($plan->price) ? $plan->price : 0,
                'status' => 'active',
                'start_date' => $start_date,
                'end_date' => $end_date,
                'created_at' => current_time('mysql'),
                'updated_at' => current_time('mysql')
            );
            
            // Use the DB class directly for more reliable insertion
            $db = new Subs_Sys_DB();
            return $db->direct_insert_subscription($subscription_data);
            
        } catch (\Exception $e) {
            error_log('Error creating subscription from session: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Render content subscription plans shortcode
     */
    public function render_content_subscription_plans($atts) {
        $atts = shortcode_atts(array(
            'category' => '',
            'tag' => '',
            'post_type' => '',
            'post_id' => '',
            'show_free' => 'true',
            'show_paid' => 'true'
        ), $atts);

        // Check if user is logged in
        if (!is_user_logged_in()) {
            return '<div class="content-subscription-login-required">
                <p>' . __('Please log in to view content subscription plans.', 'subscription-system') . '</p>
                <a href="' . wp_login_url(get_permalink()) . '" class="button button-primary">' . __('Login', 'subscription-system') . '</a>
            </div>';
        }

        $content_manager = new Subs_Sys_Content_Manager();
        $user_id = get_current_user_id();

        // Get applicable content plans based on current context
        $applicable_plans = array();
        
        if (!empty($atts['category'])) {
            $applicable_plans = array_merge($applicable_plans, $content_manager->get_content_plans(array(
                'content_type' => 'category',
                'status' => 'active'
            )));
        }
        
        if (!empty($atts['tag'])) {
            $applicable_plans = array_merge($applicable_plans, $content_manager->get_content_plans(array(
                'content_type' => 'tag',
                'status' => 'active'
            )));
        }

        // If no specific filters, show all active plans
        if (empty($applicable_plans)) {
            $applicable_plans = $content_manager->get_content_plans(array('status' => 'active'));
        }

        // Filter plans based on show_free and show_paid
        $filtered_plans = array();
        foreach ($applicable_plans as $plan) {
            if ($plan->price == 0 && $atts['show_free'] === 'true') {
                $filtered_plans[] = $plan;
            } elseif ($plan->price > 0 && $atts['show_paid'] === 'true') {
                $filtered_plans[] = $plan;
            }
        }

        if (empty($filtered_plans)) {
            return '<div class="content-subscription-no-plans">
                <p>' . __('No content subscription plans available.', 'subscription-system') . '</p>
            </div>';
        }

        ob_start();
        ?>
        <div class="content-subscription-plans-container">
            <h3><?php esc_html_e('Content Subscription Plans', 'subscription-system'); ?></h3>
            <p><?php esc_html_e('Subscribe to get notified when new content is published.', 'subscription-system'); ?></p>
            
            <div class="content-plans-grid">
                <?php foreach ($filtered_plans as $plan): ?>
                    <?php
                    // Check if user is already subscribed
                    $user_subscription = $content_manager->get_user_content_subscription($user_id, $plan->id);
                    $is_subscribed = $user_subscription && $user_subscription->status === 'active';
                    ?>
                    <div class="content-plan-card <?php echo $is_subscribed ? 'subscribed' : ''; ?>">
                        <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-amount">$<?php echo esc_html(number_format($plan->price, 2)); ?></span>
                                    <span class="price-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): ?>
                            <div class="plan-description">
                                <p><?php echo esc_html($plan->description); ?></p>
                            </div>
                        <?php endif; ?>
                        
                        <div class="plan-features">
                            <div class="feature-item">
                                <strong><?php esc_html_e('Content Type:', 'subscription-system'); ?></strong>
                                <?php echo esc_html(ucfirst($plan->content_type)); ?>
                            </div>
                            <div class="feature-item">
                                <strong><?php esc_html_e('Notifications:', 'subscription-system'); ?></strong>
                                <?php echo esc_html(ucfirst($plan->notification_frequency)); ?>
                            </div>
                        </div>
                        
                        <div class="plan-actions">
                            <?php if ($is_subscribed): ?>
                                <div class="subscribed-status">
                                    <span class="status-badge active"><?php esc_html_e('Subscribed', 'subscription-system'); ?></span>
                                    <p><?php esc_html_e('You are already subscribed to this plan.', 'subscription-system'); ?></p>
                                </div>
                            <?php else: ?>
                                <a href="<?php echo esc_url(add_query_arg(array(
                                    'action' => 'content_checkout',
                                    'content_plan_id' => $plan->id
                                ), home_url())); ?>" class="subscribe-button">
                                    <?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; ?>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <style>
        .content-subscription-plans-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }

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

        .content-plan-card {
            background: #fff;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            padding: 20px;
            transition: box-shadow 0.2s;
        }

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

        .content-plan-card.subscribed {
            border-color: #28a745;
            background: #f8fff9;
        }

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

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

        .plan-price {
            text-align: right;
        }

        .price-amount {
            font-size: 20px;
            font-weight: 700;
            color: #1da1f2;
        }

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

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

        .plan-description {
            margin-bottom: 15px;
            color: #666;
        }

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

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

        .feature-item strong {
            color: #333;
        }

        .subscribe-button {
            display: inline-block;
            background: #1da1f2;
            color: white;
            padding: 12px 24px;
            text-decoration: none;
            border-radius: 4px;
            font-weight: 600;
            text-align: center;
            transition: background-color 0.2s;
        }

        .subscribe-button:hover {
            background: #1991db;
            color: white;
        }

        .subscribed-status {
            text-align: center;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

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

        .content-subscription-login-required {
            text-align: center;
            padding: 40px 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #dee2e6;
        }

        .content-subscription-no-plans {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }

        @media (max-width: 768px) {
            .content-plans-grid {
                grid-template-columns: 1fr;
            }
            
            .plan-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .plan-price {
                text-align: left;
                margin-top: 8px;
            }
        }
        </style>
        <?php
        return ob_get_clean();
    }

    /**
     * Render content subscription checkout shortcode
     */
    public function render_content_subscription_checkout($atts) {
        $atts = shortcode_atts(array(
            'plan_id' => '',
            'success_url' => '',
            'cancel_url' => ''
        ), $atts);

        // Get plan_id from URL if not in shortcode
        if (empty($atts['plan_id'])) {
            $atts['plan_id'] = isset($_GET['plan_id']) ? intval($_GET['plan_id']) : 0;
            // Also check for content_plan_id parameter
            if (empty($atts['plan_id'])) {
                $atts['plan_id'] = isset($_GET['content_plan_id']) ? intval($_GET['content_plan_id']) : 0;
            }
        }

        if (empty($atts['plan_id'])) {
            return '<div class="content-subscription-error">
                <p>' . __('Invalid subscription plan.', 'subscription-system') . '</p>
                <a href="' . home_url() . '" class="button">' . __('Go Home', 'subscription-system') . '</a>
            </div>';
        }

        // Check if user is logged in
        if (!is_user_logged_in()) {
            return '<div class="content-subscription-login-required">
                <p>' . __('Please log in to subscribe to content plans.', 'subscription-system') . '</p>
                <a href="' . wp_login_url(get_permalink()) . '" class="button button-primary">' . __('Login', 'subscription-system') . '</a>
            </div>';
        }

        $content_manager = new Subs_Sys_Content_Manager();
        $plan = $content_manager->get_content_plan($atts['plan_id']);

        if (!$plan || $plan->status !== 'active') {
            return '<div class="content-subscription-error">
                <p>' . __('Subscription plan not found or inactive.', 'subscription-system') . '</p>
                <a href="' . home_url() . '" class="button">' . __('Go Home', 'subscription-system') . '</a>
            </div>';
        }

        $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') {
            return '<div class="content-subscription-already-subscribed">
                <h3>' . __('Already Subscribed', 'subscription-system') . '</h3>
                <p>' . __('You are already subscribed to this content plan.', 'subscription-system') . '</p>
                <a href="' . add_query_arg(array('tab' => 'content-subscriptions'), get_permalink()) . '" class="button">' . __('View My Subscriptions', 'subscription-system') . '</a>
            </div>';
        }

        ob_start();
        ?>
        <div class="content-subscription-checkout">
            <h2><?php esc_html_e('Subscribe to Content Plan', 'subscription-system'); ?></h2>
            
            <div class="checkout-plan-summary">
                <h3><?php echo esc_html($plan->plan_name); ?></h3>
                <?php if ($plan->description): ?>
                    <p><?php echo esc_html($plan->description); ?></p>
                <?php endif; ?>
                
                <div class="plan-details">
                    <div class="detail-row">
                        <strong><?php esc_html_e('Content Type:', 'subscription-system'); ?></strong>
                        <span><?php echo esc_html(ucfirst($plan->content_type)); ?></span>
                    </div>
                    <div class="detail-row">
                        <strong><?php esc_html_e('Notifications:', 'subscription-system'); ?></strong>
                        <span><?php echo esc_html(ucfirst($plan->notification_frequency)); ?></span>
                    </div>
                    <div class="detail-row">
                        <strong><?php esc_html_e('Duration:', 'subscription-system'); ?></strong>
                        <span><?php echo esc_html($plan->duration . ' ' . $plan->duration_unit); ?></span>
                    </div>
                </div>
                
                <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->price > 0): ?>
                <!-- Payment Form for Paid Plans -->
                <div class="payment-form">
                    <h3><?php esc_html_e('Payment Information', 'subscription-system'); ?></h3>
                    <form id="content-subscription-payment-form">
                        <input type="hidden" name="plan_id" value="<?php echo esc_attr($plan->id); ?>">
                        <input type="hidden" name="action" value="process_content_subscription_payment">
                        <?php wp_nonce_field('content_subscription_payment', 'payment_nonce'); ?>
                        
                        <div class="form-group">
                            <p><?php esc_html_e('You will be redirected to our secure payment processor to complete your subscription.', 'subscription-system'); ?></p>
                            <div class="payment-info">
                                <div class="payment-method">
                                    <strong><?php esc_html_e('Payment Method:', 'subscription-system'); ?></strong>
                                    <?php esc_html_e('Credit or Debit Card', 'subscription-system'); ?>
                                </div>
                                <div class="payment-security">
                                    <strong><?php esc_html_e('Security:', 'subscription-system'); ?></strong>
                                    <?php esc_html_e('SSL Encrypted & PCI Compliant', 'subscription-system'); ?>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" id="submit-payment" class="payment-button">
                            <span id="button-text"><?php printf(esc_html__('Subscribe for $%s', 'subscription-system'), number_format($plan->price, 2)); ?></span>
                            <span id="spinner" class="spinner" style="display: none;"></span>
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <!-- Free Plan Subscription -->
                <div class="free-subscription">
                    <form id="free-content-subscription-form">
                        <input type="hidden" name="plan_id" value="<?php echo esc_attr($plan->id); ?>">
                        <input type="hidden" name="action" value="subscribe_to_content_plan">
                        <?php wp_nonce_field('subscribe_to_content_plan', 'subscription_nonce'); ?>
                        
                        <p><?php esc_html_e('This is a free content subscription plan. Click below to subscribe and start receiving notifications.', 'subscription-system'); ?></p>
                        
                        <button type="submit" class="free-subscribe-button">
                            <?php esc_html_e('Subscribe for Free', 'subscription-system'); ?>
                        </button>
                    </form>
                </div>
            <?php endif; ?>
        </div>

        <style>
        .content-subscription-checkout {
            max-width: 600px;
            margin: 20px auto;
            padding: 20px;
        }

        .checkout-plan-summary {
            background: #f8f9fa;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .checkout-plan-summary h3 {
            margin: 0 0 10px 0;
            color: #1da1f2;
        }

        .plan-details {
            margin: 15px 0;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .detail-row strong {
            color: #333;
        }

        .plan-price {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e1e8ed;
        }

        .plan-price .price {
            font-size: 28px;
            font-weight: 700;
            color: #1da1f2;
        }

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

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

        .payment-form {
            background: #fff;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            padding: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .payment-info {
            background: #f8f9fa;
            border: 1px solid #e1e8ed;
            border-radius: 6px;
            padding: 15px;
            margin-top: 10px;
        }

        .payment-method, .payment-security {
            margin-bottom: 8px;
            font-size: 14px;
        }

        .payment-method:last-child, .payment-security:last-child {
            margin-bottom: 0;
        }

        .payment-button, .free-subscribe-button {
            width: 100%;
            background: #1da1f2;
            color: white;
            border: none;
            padding: 15px;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .payment-button:hover, .free-subscribe-button:hover {
            background: #1991db;
        }

        .payment-button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }

        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .free-subscription {
            text-align: center;
            padding: 20px;
        }

        .content-subscription-error,
        .content-subscription-login-required,
        .content-subscription-already-subscribed {
            text-align: center;
            padding: 40px 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e1e8ed;
        }

        .content-subscription-error {
            border-color: #dc3545;
            background: #f8d7da;
        }

        .content-subscription-already-subscribed {
            border-color: #28a745;
            background: #d4edda;
        }
        </style>

        <?php if ($plan->price > 0): ?>
        <script>
        // Handle payment form submission for paid plans
        document.addEventListener('DOMContentLoaded', function() {
            const paymentForm = document.getElementById('content-subscription-payment-form');
            if (paymentForm) {
                paymentForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const button = this.querySelector('#submit-payment');
                    const buttonText = this.querySelector('#button-text');
                    const spinner = this.querySelector('#spinner');
                    
                    // Show loading state
                    button.disabled = true;
                    buttonText.style.display = 'none';
                    spinner.style.display = 'inline-block';
                    
                    const formData = new FormData(this);
                    
                    fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            if (data.data.redirect_url) {
                                // Redirect to Stripe checkout
                                window.location.href = data.data.redirect_url;
                            } else {
                                alert('<?php esc_html_e('Payment processed successfully!', 'subscription-system'); ?>');
                                window.location.href = '<?php echo add_query_arg(array('tab' => 'content-subscriptions'), get_permalink()); ?>';
                            }
                        } else {
                            alert(data.data.message || '<?php esc_html_e('Payment failed. Please try again.', 'subscription-system'); ?>');
                        }
                    })
                    .catch(error => {
                        alert('<?php esc_html_e('An error occurred. Please try again.', 'subscription-system'); ?>');
                    })
                    .finally(() => {
                        // Reset button state
                        button.disabled = false;
                        buttonText.style.display = 'inline';
                        spinner.style.display = 'none';
                    });
                });
            }
        });
        </script>
        <?php endif; ?>

        <script>
        // Handle free subscription
        document.getElementById('free-content-subscription-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const button = this.querySelector('button');
            const originalText = button.textContent;
            button.disabled = true;
            button.textContent = '<?php esc_html_e('Processing...', 'subscription-system'); ?>';
            
            const formData = new FormData(this);
            
            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!', 'subscription-system'); ?>');
                    window.location.href = '<?php echo add_query_arg(array('tab' => 'content-subscriptions'), get_permalink()); ?>';
                } 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'); ?>');
            })
            .finally(() => {
                button.disabled = false;
                button.textContent = originalText;
            });
        });
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * Render content subscription success page
     */
    public function render_content_subscription_success($atts) {
        $atts = shortcode_atts(array(
            'show_account_link' => 'yes',
            'show_plans_link' => 'yes',
            'custom_message' => ''
        ), $atts, 'content_subscription_success');

        ob_start();

        // Get success message from URL parameters
        $success_message = '';
        $plan_name = '';
        $user_id = get_current_user_id();
        
        if (isset($_GET['message'])) {
            $success_message = sanitize_text_field(wp_unslash($_GET['message']));
        }
        
        if (isset($_GET['plan_id']) && $user_id) {
            $plan_id = intval($_GET['plan_id']);
            $content_manager = new Subs_Sys_Content_Manager();
            $plan = $content_manager->get_content_plan($plan_id);
            if ($plan) {
                $plan_name = $plan->plan_name;
            }
        }

        // Use custom message if provided, otherwise use URL message or default
        if (!empty($atts['custom_message'])) {
            $success_message = $atts['custom_message'];
        } elseif (empty($success_message)) {
            $success_message = 'Payment successful! Your subscription is now active.';
        }
        ?>
        
        <div class="content-subscription-success-page">
            <div class="success-container">
                <div class="success-header">
                    <div class="success-icon-large">
                        <svg width="80" height="80" 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>
                    <h1 class="success-title">🎉 Subscription Successful!</h1>
                    <p class="success-subtitle"><?php echo esc_html($success_message); ?></p>
                </div>

                <?php if (!empty($plan_name)): ?>
                    <div class="subscription-details">
                        <h2>Subscription Details</h2>
                        <div class="detail-card">
                            <div class="detail-item">
                                <span class="detail-label">Plan Name:</span>
                                <span class="detail-value"><?php echo esc_html($plan_name); ?></span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Status:</span>
                                <span class="detail-value status-active">Active</span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">Start Date:</span>
                                <span class="detail-value"><?php echo esc_html(date_i18n(get_option('date_format'))); ?></span>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="success-actions">
                    <?php if ($atts['show_account_link'] === 'yes'): ?>
                        <a href="<?php echo esc_url(get_permalink(get_option('account_page'))); ?>" class="btn btn-primary">
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M20 21V19C20 17.9391 19.5786 16.9217 18.8284 16.1716C18.0783 15.4214 17.0609 15 16 15H8C6.93913 15 5.92172 15.4214 5.17157 16.1716C4.42143 16.9217 4 17.9391 4 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                <path d="M12 11C14.2091 11 16 9.20914 16 7C16 4.79086 14.2091 3 12 3C9.79086 3 8 4.79086 8 7C8 9.20914 9.79086 11 12 11Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                            View My Account
                        </a>
                    <?php endif; ?>
                    
                    <?php if ($atts['show_plans_link'] === 'yes'): ?>
                        <a href="<?php echo esc_url(home_url()); ?>" class="btn btn-secondary">
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M3 12L5 10M5 10L12 3L19 10M5 10V20C5 20.5523 5.44772 21 6 21H9M19 10L21 12M19 10V20C19 20.5523 18.5523 21 18 21H15M9 21C9.55228 21 10 20.5523 10 20V16C10 15.4477 10.4477 15 11 15H13C13.5523 15 14 15.4477 14 16V20C14 20.5523 14.4477 21 15 21M9 21H15" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                            </svg>
                            Back to Home
                        </a>
                    <?php endif; ?>
                </div>

                <div class="success-info">
                    <div class="info-card">
                        <h3>What happens next?</h3>
                        <ul>
                            <li>✅ Your subscription is now active</li>
                            <li>📧 You'll receive email notifications for new content</li>
                            <li>👤 You can manage your subscription from your account page</li>
                            <li>🎯 Content matching your subscription will be delivered to you</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <style>
        .content-subscription-success-page {
            max-width: 800px;
            margin: 0 auto;
            padding: 40px 20px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
        }

        .success-container {
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            position: relative;
        }

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

        .success-header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            text-align: center;
            padding: 60px 40px;
            position: relative;
        }

        .success-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100%" height="100%" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }

        .success-icon-large {
            width: 80px;
            height: 80px;
            margin: 0 auto 20px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            position: relative;
            z-index: 1;
        }

        .success-title {
            font-size: 36px;
            font-weight: 700;
            margin: 0 0 16px 0;
            position: relative;
            z-index: 1;
        }

        .success-subtitle {
            font-size: 18px;
            opacity: 0.9;
            margin: 0;
            position: relative;
            z-index: 1;
        }

        .subscription-details {
            padding: 40px;
            border-bottom: 1px solid #f0f0f0;
        }

        .subscription-details h2 {
            font-size: 24px;
            font-weight: 600;
            color: #1a202c;
            margin: 0 0 24px 0;
        }

        .detail-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 24px;
        }

        .detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
        }

        .detail-item:last-child {
            border-bottom: none;
        }

        .detail-label {
            font-weight: 500;
            color: #64748b;
        }

        .detail-value {
            font-weight: 600;
            color: #1a202c;
        }

        .status-active {
            background: #dcfce7;
            color: #166534;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 14px;
        }

        .success-actions {
            padding: 40px;
            text-align: center;
            border-bottom: 1px solid #f0f0f0;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 16px 32px;
            margin: 0 8px;
            border-radius: 12px;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            border: none;
            cursor: pointer;
            font-size: 16px;
        }

        .btn-primary {
            background: linear-gradient(90deg, #4a90e2, #357ab8);
            color: white;
            box-shadow: 0 4px 10px rgba(74, 144, 226, 0.2);
        }

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

        .btn-secondary {
            background: #f8fafc;
            color: #64748b;
            border: 1px solid #e2e8f0;
        }

        .btn-secondary:hover {
            background: #f1f5f9;
            color: #475569;
            transform: translateY(-1px);
        }

        .success-info {
            padding: 40px;
        }

        .info-card {
            background: #fefefe;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            padding: 24px;
        }

        .info-card h3 {
            font-size: 20px;
            font-weight: 600;
            color: #1a202c;
            margin: 0 0 16px 0;
        }

        .info-card ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .info-card li {
            padding: 8px 0;
            font-size: 16px;
            color: #4a5568;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .content-subscription-success-page {
                padding: 20px 16px;
            }

            .success-header {
                padding: 40px 24px;
            }

            .success-title {
                font-size: 28px;
            }

            .success-subtitle {
                font-size: 16px;
            }

            .subscription-details,
            .success-actions,
            .success-info {
                padding: 24px;
            }

            .btn {
                display: block;
                width: 100%;
                margin: 8px 0;
                justify-content: center;
            }

            .detail-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
            }
        }
        </style>

        <?php
        return ob_get_clean();
    }

    /**
     * Render subscribe button with category/tag interest popup modal.
     *
     * Usage: [subscriptionsystem_subscribe] or [subscriptionsystem_subscribe button_text="Subscribe"]
     *
     * @param array $atts Shortcode attributes.
     * @return string
     */
    public function render_interest_subscribe_button( $atts ) {
        $atts = shortcode_atts(
            array(
                'button_text' => __( 'Subscribe', 'subscription-system' ),
                'button_class' => '',
            ),
            $atts,
            'subscriptionsystem_subscribe'
        );

        $this->enqueue_interest_subscribe_assets();

        // Gather context (categories/tags) from the current post if applicable.
        $context_categories = array();
        $context_tags       = array();
        if ( is_singular() && get_the_ID() ) {
            if ( get_option( 'subs_modal_context_categories', 1 ) ) {
                $cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );
                $context_categories = array_map( 'intval', is_array( $cats ) ? $cats : array() );
            }
            if ( get_option( 'subs_modal_context_tags', 1 ) ) {
                $tags_list = wp_get_post_tags( get_the_ID(), array( 'fields' => 'ids' ) );
                $context_tags = array_map( 'intval', is_array( $tags_list ) ? $tags_list : array() );
            }
        }

        // Only show categories/tags actually on this post; fall back to all on non-singular pages.
        $display_categories = ! empty( $context_categories )
            ? Subs_Sys_Interest_Subscription::get_categories_by_ids( $context_categories )
            : Subs_Sys_Interest_Subscription::get_available_categories();

        $display_tags = ! empty( $context_tags )
            ? Subs_Sys_Interest_Subscription::get_tags_by_ids( $context_tags )
            : Subs_Sys_Interest_Subscription::get_available_tags();

        $modal_id = 'ss-interest-modal-' . wp_unique_id();
        $args = array(
            'modal_id'           => $modal_id,
            'categories'         => $display_categories,
            'tags'               => $display_tags,
            'plans'              => Subs_Sys_Interest_Subscription::get_content_modal_plans( $context_categories, $context_tags ),
            'plan_source'        => 'content',
            'context_categories' => $context_categories,
            'context_tags'       => $context_tags,
        );

        ob_start();
        ?>
        <div class="ss-interest-subscribe-wrap">
            <button type="button"
                class="ss-interest-subscribe-btn <?php echo esc_attr( $atts['button_class'] ); ?>"
                data-ss-open-interest-modal="#<?php echo esc_attr( $modal_id ); ?>">
                <?php echo esc_html( $atts['button_text'] ); ?>
            </button>
        </div>
        <?php
        include SUBS_SYS_PLUGIN_DIR . 'public/partials/interest-subscribe-modal.php';
        return ob_get_clean();
    }

    /**
     * Enqueue assets for the interest subscribe modal.
     */
    private function enqueue_interest_subscribe_assets() {
        subs_sys_enqueue_interest_modal_assets( $this->plugin_name, $this->version );
    }
}