<?php
/**
 * AJAX handlers for Subscription System
 *
 * @link       https://mediahubster.in
 * @since      1.0.0
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 */

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

/**
 * AJAX handlers class
 *
 * Handles all AJAX requests for the subscription system.
 *
 * @since      1.0.0
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 * @author     Joe Youngblood <support@subscriptionplugin.com>
 */
class Subs_Sys_Ajax {

	/**
	 * Initialize the class
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Register AJAX actions
		add_action( 'wp_ajax_process_subscription_payment', array( $this, 'process_subscription_payment' ) );
		add_action( 'wp_ajax_nopriv_process_subscription_payment', array( $this, 'process_subscription_payment' ) );
		add_action( 'wp_ajax_complete_subscription_payment', array( $this, 'complete_subscription_payment' ) );
		add_action( 'wp_ajax_nopriv_complete_subscription_payment', array( $this, 'complete_subscription_payment' ) );
		add_action( 'wp_ajax_cancel_subscription', array( $this, 'cancel_subscription' ) );
		add_action( 'wp_ajax_test_ajax', array( $this, 'test_ajax' ) );
		add_action( 'wp_ajax_nopriv_test_ajax', array( $this, 'test_ajax' ) );
		add_action( 'wp_ajax_test_stripe_connection', array( $this, 'test_stripe_connection' ) );
		add_action( 'wp_ajax_nopriv_test_stripe_connection', array( $this, 'test_stripe_connection' ) );
		add_action( 'wp_ajax_check_session_status', array( $this, 'check_session_status' ) );
		add_action( 'wp_ajax_nopriv_check_session_status', array( $this, 'check_session_status' ) );
		add_action( 'wp_ajax_create_checkout_session', array( $this, 'create_checkout_session' ) );
		add_action( 'wp_ajax_nopriv_create_checkout_session', array( $this, 'create_checkout_session' ) );
		add_action( 'wp_ajax_get_order_details', array( $this, 'get_order_details' ) );
		add_action( 'wp_ajax_get_admin_order_details', array( $this, 'get_admin_order_details' ) );
		add_action( 'wp_ajax_update_order_status', array( $this, 'update_order_status' ) );
		add_action( 'wp_ajax_test_create_subscription', array( $this, 'test_create_subscription' ) );
		add_action( 'wp_ajax_nopriv_test_create_subscription', array( $this, 'test_create_subscription' ) );
		add_action( 'wp_ajax_test_db_connection', array( $this, 'test_db_connection' ) );
		add_action( 'wp_ajax_nopriv_test_db_connection', array( $this, 'test_db_connection' ) );
		add_action( 'wp_ajax_pause_subscription', array( $this, 'pause_subscription' ) );
		add_action( 'wp_ajax_nopriv_pause_subscription', array( $this, 'pause_subscription' ) );
		add_action( 'wp_ajax_resume_subscription', array( $this, 'resume_subscription' ) );
		add_action( 'wp_ajax_nopriv_resume_subscription', array( $this, 'resume_subscription' ) );
		add_action( 'wp_ajax_update_billing_info', array( $this, 'update_billing_info' ) );
		add_action( 'wp_ajax_create_direct_checkout', array( $this, 'create_direct_checkout' ) );
		add_action( 'wp_ajax_handle_webhook_event', array( $this, 'handle_webhook_event' ) );
		add_action( 'wp_ajax_test_direct_subscription', array( $this, 'test_direct_subscription' ) );
		add_action( 'wp_ajax_test_db_structure', array( $this, 'test_db_structure' ) );
		add_action( 'wp_ajax_test_webhook_processing', array( $this, 'test_webhook_processing' ) );
		add_action( 'wp_ajax_check_user_subscription', array( $this, 'check_user_subscription' ) );
		add_action( 'wp_ajax_get_content_options', array( $this, 'get_content_options' ) );
		add_action( 'wp_ajax_subscribe_to_content_plan', array( $this, 'subscribe_to_content_plan' ) );
		add_action( 'wp_ajax_nopriv_subscribe_to_content_plan', array( $this, 'subscribe_to_content_plan' ) );
		add_action( 'wp_ajax_process_content_subscription_payment', array( $this, 'process_content_subscription_payment' ) );
		add_action( 'wp_ajax_unsubscribe_from_content_plan', array( $this, 'unsubscribe_from_content_plan' ) );
		add_action( 'wp_ajax_test_content_ajax', array( $this, 'test_content_ajax' ) );
		add_action( 'wp_ajax_submit_interest_subscription', array( $this, 'submit_interest_subscription' ) );
		add_action( 'wp_ajax_nopriv_submit_interest_subscription', array( $this, 'submit_interest_subscription' ) );
	}

	/**
	 * Process subscription payment using direct API call
	 *
	 * @since 1.0.0
	 */
	public function process_subscription_payment() {
		// Verify nonce for security
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'subscription_checkout_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
			return;
		}

		// Validate and sanitize input
		$plan_id = isset( $_POST['plan_id'] ) ? absint( $_POST['plan_id'] ) : 0;

		if ( empty( $plan_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid plan ID.', 'subscription-system' ) ) );
			return;
		}

		// Get plan details
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_plans';
		$plan = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE id = %d", $plan_id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( ! $plan ) {
			wp_send_json_error( array( 'message' => __( 'Invalid subscription plan.', 'subscription-system' ) ) );
			return;
		}

		// Get success and cancel URLs
		$success_url = get_permalink( get_option( 'account_page' ) );
		$cancel_url = get_permalink( get_option( 'pricing_plans_page' ) );

		// Get Stripe API key
		$api_key = get_option( 'subscription_stripe_secret_key' );

		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => __( 'Stripe API key is not configured.', 'subscription-system' ) ) );
			return;
		}

		// Prepare Stripe checkout session data for RECURRING subscription
		$data = array(
			'payment_method_types' => array( 'card' ),
			'line_items' => array(
				array(
					'price_data' => array(
						'currency' => 'usd',
						'product_data' => array(
							'name' => sanitize_text_field( $plan->plan_name ),
						),
						'unit_amount' => absint( $plan->price * 100 ),
						'recurring' => array(
							'interval' => 'month',
						),
					),
					'quantity' => 1,
				),
			),
			'mode' => 'subscription',
			'success_url' => esc_url_raw( $success_url . '?session_id={CHECKOUT_SESSION_ID}' ),
			'cancel_url' => esc_url_raw( $cancel_url ),
		);

		// Make API call to Stripe using wp_remote_post
		$response = wp_remote_post( 'https://api.stripe.com/v1/checkout/sessions', array(
			'body'    => $data,
			'headers' => array(
				'Authorization' => 'Bearer ' . $api_key,
				'Content-Type'  => 'application/x-www-form-urlencoded',
			),
			'timeout' => 30,
		) );

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => __( 'Error connecting to payment gateway.', 'subscription-system' ) ) );
			return;
		}

		$body = wp_remote_retrieve_body( $response );
		$session_data = json_decode( $body, true );

		if ( isset( $session_data['error'] ) ) {
			wp_send_json_error( array( 'message' => __( 'Payment gateway error: ', 'subscription-system' ) . esc_html( $session_data['error']['message'] ) ) );
			return;
		}

		if ( ! isset( $session_data['url'] ) ) {
			wp_send_json_error( array( 'message' => __( 'Unexpected response from payment gateway.', 'subscription-system' ) ) );
			return;
		}

		// Return success response
		wp_send_json_success( array(
			'checkout_url' => esc_url_raw( $session_data['url'] ),
			'message'      => __( 'Your payment is being processed.', 'subscription-system' ),
		) );
	}

	/**
	 * Send confirmation email
	 *
	 * @param string $email Customer email
	 * @param string $name Customer name
	 * @param object $plan Subscription plan
	 */
	private function send_confirmation_email($email, $name, $plan) {
		// translators: %s is the website name
		$subject = sprintf(__('Your subscription to %s has been confirmed', 'subscription-system'), get_bloginfo('name'));
		
		// translators: %s is the customer name
		$message = sprintf(__('Hello %s,', 'subscription-system'), $name) . "\n\n";
		// translators: %s is the plan name
		$message .= sprintf(__('Thank you for subscribing to the %s plan.', 'subscription-system'), $plan->plan_name) . "\n\n";
		$message .= sprintf(__('Subscription details:', 'subscription-system')) . "\n";
		// translators: %s is the plan name
		$message .= sprintf(__('Plan: %s', 'subscription-system'), $plan->plan_name) . "\n";
		// translators: %s is the formatted price amount
		$message .= sprintf(__('Price: $%s per month', 'subscription-system'), number_format($plan->price, 2)) . "\n";
		// translators: %s is the formatted start date
		$message .= sprintf(__('Start date: %s', 'subscription-system'), date_i18n(get_option('date_format'))) . "\n\n";
		$message .= sprintf(__('If you have any questions, please contact us.', 'subscription-system')) . "\n\n";
		$message .= sprintf(__('Thank you,', 'subscription-system')) . "\n";
		$message .= get_bloginfo('name');
		
		$headers = array('Content-Type: text/plain; charset=UTF-8');
		
		wp_mail($email, $subject, $message, $headers);
	}

	/**
	 * Test Stripe connection
	 */
	public function test_stripe_connection() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(array('message' => 'Security check failed.'));
			return;
		}
		
		try {
			// Initialize Stripe
			$stripe = new Subs_Sys_Stripe();
			
			// Try to get account info
			$account = \Stripe\Account::retrieve();
			
			// If successful, return success message
			wp_send_json_success(array(
				'message' => sprintf(
					// translators: %s is the Stripe account email
					/* translators: %s: Stripe account ID or name */
            __('Connection successful! Connected to Stripe account: %s', 'subscription-system'),
					$account->email
				)
			));
		} catch (Exception $e) {
			// If failed, return error message
			wp_send_json_error(array(
				'message' => sprintf(
					// translators: %s is the error message from Stripe
					__('Connection failed: %s', 'subscription-system'),
					$e->getMessage()
				)
			));
		}
	}

	/**
	 * Complete subscription payment after 3D Secure
	 */
	public function complete_subscription_payment() {
		try {
			// Check nonce
			if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
				wp_send_json_error(array('message' => 'Security check failed.'));
				return;
			}

			// Check required fields
			if (!isset($_POST['subscription_id']) || empty($_POST['subscription_id'])) {
				wp_send_json_error(array('message' => 'Missing subscription ID.'));
				return;
			}

			$subscription_id = sanitize_text_field($_POST['subscription_id']);
			error_log('Completing subscription: ' . $subscription_id);

			// Initialize Stripe
			$stripe = new Subs_Sys_Stripe();

			// Retrieve the subscription
			$subscription = \Stripe\Subscription::retrieve([
				'id' => $subscription_id,
				'expand' => ['customer', 'latest_invoice.payment_intent'],
			]);
			
			error_log('Subscription retrieved, status: ' . $subscription->status);

			// Check subscription status
			if ($subscription->status === 'active' || $subscription->status === 'trialing') {
				// Get metadata
				$metadata = $subscription->metadata->toArray();
				$plan_id = isset($metadata['plan_id']) ? intval($metadata['plan_id']) : 0;
				$customer_email = isset($metadata['customer_email']) ? $metadata['customer_email'] : '';
				$customer_name = isset($metadata['customer_name']) ? $metadata['customer_name'] : '';
				$user_id = isset($metadata['user_id']) ? intval($metadata['user_id']) : get_current_user_id();

				error_log('Subscription metadata: ' . json_encode($metadata));

				// Get plan details
				global $wpdb;
				$table_name = $wpdb->prefix . 'subscription_plans';
				$plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $plan_id));

				if (!$plan) {
					error_log('Invalid plan ID: ' . $plan_id);
					wp_send_json_error(array('message' => 'Invalid subscription plan.'));
					return;
				}

				// Check if subscription already exists for this payment
				$subscription_table = $wpdb->prefix . 'subscriptions';
				$existing = $wpdb->get_var($wpdb->prepare(
					"SELECT id FROM $subscription_table WHERE payment_id = %s",
					$subscription_id
				));

				if ($existing) {
					error_log('Subscription already exists: ' . $subscription_id);
					wp_send_json_success(array(
						'message' => 'Subscription already processed!',
						'subscription_id' => $existing,
						'redirect_url' => get_permalink(get_option('account_page')), // Replace hardcoded my-account URL
					));
					return;
				}

				// Before inserting subscription data
				if (!$this->ensure_subscriptions_table_exists()) {
					wp_send_json_error(['message' => 'Could not create database table. Please contact support.']);
					return;
				}

				// Create subscription record in database
				$result = $wpdb->insert(
					$subscription_table,
					array(
						'user_id' => $user_id,
						'plan_id' => $plan_id,
						'customer_email' => $customer_email,
						'customer_name' => $customer_name,
						'payment_id' => $subscription_id,
						'amount' => $plan->price,
						'status' => 'active',
						'start_date' => date('Y-m-d H:i:s', $subscription->current_period_start),
						'end_date' => date('Y-m-d H:i:s', $subscription->current_period_end),
						'created_at' => current_time('mysql'),
						'updated_at' => current_time('mysql')
					)
				);

				if ($result === false) {
					error_log('Failed to insert subscription: ' . $wpdb->last_error);
					wp_send_json_error(['message' => 'Failed to create subscription record: ' . $wpdb->last_error]);
					return;
				}

				$local_subscription_id = $wpdb->insert_id;
				error_log('Subscription created with ID: ' . $local_subscription_id);

				// Send confirmation email
				$this->send_confirmation_email($customer_email, $customer_name, $plan);

				// Return success response
				wp_send_json_success(array(
					'message' => 'Subscription successful!',
					'subscription_id' => $local_subscription_id,
					'redirect_url' => get_permalink(get_option('account_page')), // Replace hardcoded my-account URL
				));
			} else {
				// Subscription not active
				error_log('Subscription not active. Status: ' . $subscription->status);
				wp_send_json_error(array('message' => 'Subscription is not active. Please try again.'));
			}
		} catch (Exception $e) {
			// Log the error
			error_log('Subscription error: ' . $e->getMessage());
			
			// Return error response
			wp_send_json_error(array('message' => 'Error processing subscription: ' . $e->getMessage()));
		}
	}

	/**
	 * Handle pause subscription AJAX request
	 */
	public function pause_subscription() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ss_admin_nonce')) {
			wp_send_json_error(array('message' => __('Security check failed.', 'subscription-system')));
		}
		
		// Check permissions
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'subscription-system')));
		}
		
		$subscription_id = isset($_POST['subscription_id']) ? absint($_POST['subscription_id']) : 0;
		
		if (empty($subscription_id)) {
			wp_send_json_error(array('message' => __('Invalid subscription ID.', 'subscription-system')));
		}
		
		$subscription_manager = new Subs_Sys_Manager();
		$result = $subscription_manager->update_subscription($subscription_id, array('status' => 'paused'));
		
		if (is_wp_error($result)) {
			wp_send_json_error(array('message' => $result->get_error_message()));
		} else {
			do_action('ss_subscription_paused', $subscription_id);
			wp_send_json_success(array('message' => __('Subscription paused successfully.', 'subscription-system')));
		}
	}

	/**
	 * Handle resume subscription AJAX request
	 */
	public function resume_subscription() {
		// Verify nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subs_sys_nonce')) {
			wp_send_json_error(array('message' => __('Security check failed.', 'subscription-system')));
		}
		
		// Get subscription ID
		$subscription_id = isset($_POST['subscription_id']) ? intval($_POST['subscription_id']) : 0;
		
		if (empty($subscription_id)) {
			wp_send_json_error(array('message' => __('Invalid subscription ID.', 'subscription-system')));
		}
		
		// Get subscription manager
		$subscription_manager = new Subs_Sys_Manager();
		
		// Update subscription status to active
		$result = $subscription_manager->update_subscription($subscription_id, array(
			'status' => 'active'
		));
		
		if (is_wp_error($result)) {
			wp_send_json_error(array('message' => $result->get_error_message()));
		} else {
			// Trigger action for other plugins
			do_action('ss_subscription_resumed', $subscription_id);
			
			wp_send_json_success(array(
				'message' => __('Your subscription has been resumed successfully.', 'subscription-system')
			));
		}
	}

	/**
	 * Handle cancel subscription AJAX request
	 */
	public function cancel_subscription() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ss_admin_nonce')) {
			wp_send_json_error(array('message' => __('Security check failed.', 'subscription-system')));
		}
		
		// Check permissions
		if (!current_user_can('manage_options')) {
			wp_send_json_error(array('message' => __('You do not have permission to perform this action.', 'subscription-system')));
		}
		
		$subscription_id = isset($_POST['subscription_id']) ? absint($_POST['subscription_id']) : 0;
		
		if (empty($subscription_id)) {
			wp_send_json_error(array('message' => __('Invalid subscription ID.', 'subscription-system')));
		}
		
		$subscription_manager = new Subs_Sys_Manager();
		$result = $subscription_manager->cancel_subscription($subscription_id);
		
		if (is_wp_error($result)) {
			wp_send_json_error(array('message' => $result->get_error_message()));
		} else {
			do_action('ss_subscription_cancelled', $subscription_id);
			wp_send_json_success(array('message' => __('Subscription cancelled successfully.', 'subscription-system')));
		}
	}

	/**
	 * Simple test function for AJAX
	 */
	public function test_ajax() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Return success
		wp_send_json_success(['message' => 'AJAX is working correctly.']);
	}

	/**
	 * Check session status and create subscription if needed
	 */
	public function check_session_status() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Get session ID
		$session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
		
		if (empty($session_id)) {
			wp_send_json_error(['message' => 'Missing session ID.']);
			return;
		}
		
		error_log('Checking session status: ' . $session_id);
		
		try {
			// Initialize Stripe
			$stripe = new Subs_Sys_Stripe();
			
			// Retrieve the session
			$session = \Stripe\Checkout\Session::retrieve([
				'id' => $session_id,
				'expand' => ['customer', 'payment_intent', 'line_items']
			]);
			
			error_log('Session retrieved: ' . json_encode($session));
			
			if ($session->status === 'complete') {
				// Check if subscription already exists for this session
				global $wpdb;
				$wpdb->show_errors(); // Enable error display
				
				$subscription_table = $wpdb->prefix . 'subscriptions';
				
				// Log the table structure
				$table_structure = $wpdb->get_results("DESCRIBE $subscription_table");
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table structure
				error_log('Table structure: ' . wp_json_encode($table_structure));
				
				// Check if table exists
				$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$subscription_table'");
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table existence
				error_log('Table exists check: ' . ($table_exists === $subscription_table ? 'Yes' : 'No'));
				
				// Check for existing subscription
				$query = $wpdb->prepare("SELECT id FROM $subscription_table WHERE payment_id = %s", $session_id);
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for existing subscription query
				error_log('Checking existing subscription query: ' . $query);
				
				$existing = $wpdb->get_var($query);
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for existing subscription result
				error_log('Existing subscription check result: ' . ($existing ? $existing : 'None found'));
				
				if ($existing) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for existing subscription
					error_log('Subscription already exists: ' . $existing);
					wp_send_json_success([
						'message' => 'Your subscription has been processed.',
						'subscription_id' => $existing
					]);
					return;
				}
				
				// Get plan ID from client_reference_id or line items
				$plan_id = null;
				if (!empty($session->client_reference_id)) {
					$plan_id = $session->client_reference_id;
				} elseif (!empty($session->line_items->data)) {
					// Try to extract plan ID from product name or description
					$item = $session->line_items->data[0];
					$product_name = $item->description;
					
					// Look up plan by name
					$plans_table = $wpdb->prefix . 'subscription_plans';
					$plan = $wpdb->get_row($wpdb->prepare(
						"SELECT id FROM $plans_table WHERE plan_name = %s LIMIT 1",
						$product_name
					));
					
					if ($plan) {
						$plan_id = $plan->id;
					}
				}
				
				if (!$plan_id) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing plan ID
					error_log('Could not determine plan ID from session');
					wp_send_json_error(['message' => 'Could not determine subscription plan.']);
					return;
				}
				
				// Get user ID
				$user_id = get_current_user_id();
				if (!$user_id) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing user
					error_log('No logged-in user found');
					wp_send_json_error(['message' => 'You must be logged in to complete this subscription.']);
					return;
				}
				
				// Get customer details
				$customer_email = '';
				$customer_name = '';
				
				if (isset($session->customer_details)) {
					$customer_email = $session->customer_details->email;
					$customer_name = $session->customer_details->name;
				} else {
					$user = get_userdata($user_id);
					$customer_email = $user->user_email;
					$customer_name = $user->display_name;
				}
				
				// Test database connection
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for database test
				error_log('Testing database connection...');
				$test_result = $wpdb->get_var("SELECT 1");
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for database test result
				error_log('Database test result: ' . ($test_result ? 'Success' : 'Failed'));
				
				// Create subscription
				$manager = new Subs_Sys_Manager();
				
				// Add debugging before calling create_subscription()
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for subscription creation data
				error_log('About to create subscription with data: ' . wp_json_encode([
					'user_id' => $user_id,
					'plan_id' => $plan_id,
					'payment_id' => $session_id,
					'customer_email' => $customer_email,
					'customer_name' => $customer_name
				]));
				
				// Ensure subscriptions table exists
				if (!$this->ensure_subscriptions_table_exists()) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table creation failure
					error_log('Failed to create subscriptions table');
					wp_send_json_error(['message' => 'Database error: Could not create required tables.']);
					return;
				}
				
				$subscription_id = $manager->create_subscription($user_id, $plan_id, [
					'payment_id' => $session_id,
					'customer_email' => $customer_email,
					'customer_name' => $customer_name,
					'status' => 'active'
				]);
				
				if (is_wp_error($subscription_id)) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for subscription creation error
					error_log('Error creating subscription: ' . $subscription_id->get_error_message());
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for error data
					error_log('Error data: ' . wp_json_encode($subscription_id->get_error_data()));
					wp_send_json_error(['message' => 'Error creating subscription: ' . $subscription_id->get_error_message()]);
					return;
				}
				
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful subscription creation
				error_log('Subscription created successfully: ' . $subscription_id);
				
				// Create an order for this subscription
				$this->create_subscription_order($subscription_id, $session);
				
				wp_send_json_success([
					'message' => 'Your subscription has been activated!',
					'subscription_id' => $subscription_id
				]);
			} else {
				wp_send_json_error(['message' => 'Your payment is still being processed. Please try again later.']);
			}
		} catch (\Exception $e) {
			error_log('Error checking session: ' . $e->getMessage());
			error_log('Exception trace: ' . $e->getTraceAsString());
			wp_send_json_error(['message' => 'Error checking payment status: ' . $e->getMessage()]);
		}
	}

	/**
	 * Create an order for a subscription
	 */
	private function create_subscription_order($subscription_id, $session) {
		global $wpdb;
		
		// Get subscription details
		$subscriptions_table = $wpdb->prefix . 'subscriptions';
		$subscription = $wpdb->get_row($wpdb->prepare(
			"SELECT * FROM $subscriptions_table WHERE id = %d",
			$subscription_id
		));
		
		if (!$subscription) {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing subscription
			error_log('Subscription not found: ' . $subscription_id);
			return;
		}
		
		// Check if orders table exists
		$orders_table = $wpdb->prefix . 'subscription_orders';
		$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$orders_table'");
		
		if ($table_exists != $orders_table) {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing orders table
			error_log('Orders table does not exist, creating it');
			$this->create_orders_table();
		}
		
		// Create order data
		$order_data = [
			'user_id' => $subscription->user_id,
			'subscription_id' => $subscription->id,
			'order_number' => 'ORD-' . time() . '-' . mt_rand(1000, 9999),
			'payment_id' => $session->id,
			'amount' => $subscription->amount,
			'status' => 'completed',
			'payment_method' => 'stripe',
			'billing_name' => $subscription->customer_name,
			'billing_email' => $subscription->customer_email,
			'transaction_date' => current_time('mysql'),
			'created_at' => current_time('mysql'),
			'updated_at' => current_time('mysql')
		];
		
		// Insert order
		$result = $wpdb->insert($orders_table, $order_data);
		
		if ($result === false) {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for order creation failure
			error_log('Failed to create order: ' . $wpdb->last_error);
		} else {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful order creation
			error_log('Order created successfully: ' . $wpdb->insert_id);
		}
	}

	/**
	 * Create orders table if it doesn't exist
	 */
	private function create_orders_table() {
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_orders';
		
		$charset_collate = $wpdb->get_charset_collate();
		
		$sql = "CREATE TABLE $table_name (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			user_id bigint(20) NOT NULL,
			subscription_id mediumint(9) NOT NULL,
			order_number varchar(50) NOT NULL,
			payment_id varchar(100) NOT NULL,
			amount decimal(10,2) NOT NULL,
			status varchar(20) NOT NULL,
			payment_method varchar(50) NOT NULL,
			billing_name varchar(100) NOT NULL,
			billing_email varchar(100) NOT NULL,
			transaction_date datetime NOT NULL,
			created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
			PRIMARY KEY  (id),
			KEY user_id (user_id),
			KEY subscription_id (subscription_id),
			KEY payment_id (payment_id)
		) $charset_collate;";
		
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
	}

	/**
	 * Test creating a subscription
	 */
	public function test_create_subscription() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Get plan ID
		$plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
		
		if ($plan_id <= 0) {
			wp_send_json_error(['message' => 'Invalid plan ID.']);
			return;
		}
		
		// Get plan details
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_plans';
		$plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $plan_id));
		
		if (!$plan) {
			wp_send_json_error(['message' => 'Invalid subscription plan.']);
			return;
		}
		
		// Create test subscription
		$subscription_table = $wpdb->prefix . 'subscriptions';
		
		// Check if table exists
		$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$subscription_table'");
		if ($table_exists != $subscription_table) {
			wp_send_json_error(['message' => 'Subscriptions table does not exist.']);
			return;
		}
		
		// Get current user
		$user_id = get_current_user_id();
		$user = get_userdata($user_id);
		
		if (!$user) {
			wp_send_json_error(['message' => 'User not found.']);
			return;
		}
		
		// Create subscription data
		$subscription_data = array(
			'user_id' => $user_id,
			'plan_id' => $plan_id,
			'customer_email' => $user->user_email,
			'customer_name' => $user->display_name,
			'payment_id' => 'test_' . time(),
			'amount' => $plan->price,
			'status' => 'active',
			'start_date' => current_time('mysql'),
			'end_date' => date('Y-m-d H:i:s', strtotime('+1 month', current_time('timestamp'))),
			'created_at' => current_time('mysql'),
			'updated_at' => current_time('mysql')
		);
		
		// Before inserting subscription data
		if (!$this->ensure_subscriptions_table_exists()) {
			wp_send_json_error(['message' => 'Could not create database table. Please contact support.']);
			return;
		}
		
		// Insert subscription
		$result = $wpdb->insert(
			$subscription_table,
			$subscription_data
		);
		
		if ($result === false) {
			Subscription_System::debug_log('Failed to insert subscription: ' . $wpdb->last_error);
			Subscription_System::debug_log('SQL: ' . $wpdb->last_query);
			Subscription_System::debug_log('Data: ' . print_r($subscription_data, true));
			wp_send_json_error([
				'message' => 'Failed to create subscription: ' . $wpdb->last_error,
				'data' => $subscription_data,
				'table' => $subscription_table
			]);
			return;
		}
		
		$subscription_id = $wpdb->insert_id;
		
		// Return success
		wp_send_json_success([
			'message' => 'Test subscription created successfully.',
			'subscription_id' => $subscription_id
		]);
	}

	/**
	 * Ensure subscriptions table exists
	 */
	private function ensure_subscriptions_table_exists() {
		global $wpdb;
		$subscription_table = $wpdb->prefix . 'subscriptions';
		
		// Check if table exists
		$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$subscription_table'");
		if ($table_exists != $subscription_table) {
			Subscription_System::debug_log('Subscriptions table does not exist, creating it now');
			
			// Create the table
			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE $subscription_table (
				id mediumint(9) NOT NULL AUTO_INCREMENT,
				user_id bigint(20) NOT NULL,
				plan_id mediumint(9) NOT NULL,
				customer_email varchar(100) NOT NULL,
				customer_name varchar(100) NOT NULL,
				payment_id varchar(100) NOT NULL,
				amount decimal(10,2) NOT NULL,
				status varchar(20) NOT NULL,
				start_date datetime NOT NULL,
				end_date datetime NOT NULL,
				created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
				updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
				PRIMARY KEY  (id),
				KEY user_id (user_id),
				KEY payment_id (payment_id)
			) $charset_collate;";
			
			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
			dbDelta($sql);
			
			// Check if table was created
			$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$subscription_table'");
			if ($table_exists != $subscription_table) {
				Subscription_System::debug_log('Failed to create subscriptions table');
				return false;
			}
			
			Subscription_System::debug_log('Subscriptions table created successfully');
		}
		
		return true;
	}

	public function test_simple_insert() {
		global $wpdb;
		$subscription_table = $wpdb->prefix . 'subscriptions';
		
		// Ensure table exists
		$this->ensure_subscriptions_table_exists();
		
		// Simple test data
		$test_data = array(
			'user_id' => 1,
			'plan_id' => 1,
			'customer_email' => 'test@example.com',
			'customer_name' => 'Test User',
			'payment_id' => 'test_' . time(),
			'amount' => 9.99,
			'status' => 'active',
			'start_date' => current_time('mysql'),
			'end_date' => date('Y-m-d H:i:s', strtotime('+1 month', current_time('timestamp'))),
			'created_at' => current_time('mysql'),
			'updated_at' => current_time('mysql')
		);
		
		// Try to insert
		$result = $wpdb->insert($subscription_table, $test_data);
		
		if ($result === false) {
			Subscription_System::debug_log('Test insert failed: ' . $wpdb->last_error);
			return false;
		}
		
		$insert_id = $wpdb->insert_id;
		Subscription_System::debug_log('Test insert succeeded with ID: ' . $insert_id);
		
		// Clean up
		$wpdb->delete($subscription_table, array('id' => $insert_id));
		
		return true;
	}

	/**
	 * Test database connection and plan retrieval
	 */
	public function test_db_connection() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Get plan ID
		$plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
		
		if ($plan_id <= 0) {
			wp_send_json_error(['message' => 'Invalid plan ID.']);
			return;
		}
		
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_plans';
		
		// Check if table exists
		$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
		
		if (!$table_exists) {
			wp_send_json_error([
				'message' => 'Subscription plans table does not exist.',
				'table_name' => $table_name
			]);
			return;
		}
		
		// Try to get plan directly
		$plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $plan_id));
		
		if (!$plan) {
			wp_send_json_error([
				'message' => 'Plan not found in database.',
				'sql_error' => $wpdb->last_error,
				'last_query' => $wpdb->last_query
			]);
			return;
		}
		
		// Return plan data
		wp_send_json_success([
			'message' => 'Plan found successfully.',
			'plan' => $plan
		]);
	}

	/**
	 * Update billing information
	 */
	public function update_billing_info() {
		// 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')));
	}

	/**
	 * Create a direct checkout for one-time payment
	 */
	public function create_direct_checkout() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Get plan ID
		$plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
		
		if (!$plan_id) {
			wp_send_json_error(['message' => 'Invalid plan selected.']);
			return;
		}
		
		// Get plan details
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_plans';
		$plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $plan_id));
		
		if (!$plan) {
			wp_send_json_error(['message' => 'Plan not found.']);
			return;
		}
		
		// Initialize Stripe
		try {
			$stripe = new Subs_Sys_Stripe();
		} catch (\Exception $e) {
			wp_send_json_error(['message' => 'Error initializing payment gateway: ' . $e->getMessage()]);
			return;
		}
		
		// Get current user
		$user_id = get_current_user_id();
		$user = $user_id ? get_userdata($user_id) : null;
		
		// Create metadata
		$metadata = [
			'plan_id' => $plan_id,
			'user_id' => $user_id,
			'customer_email' => $user ? $user->user_email : '',
			'customer_name' => $user ? $user->display_name : ''
		];
		
		// Create checkout session for RECURRING subscription
		try {
			$session = \Stripe\Checkout\Session::create([
				'payment_method_types' => ['card'],
				'line_items' => [[
					'price_data' => [
						'currency' => 'usd',
						'product_data' => [
							'name' => $plan->plan_name,
						],
						'unit_amount' => intval($plan->price * 100),
						'recurring' => [
							'interval' => 'month',
						],
					],
					'quantity' => 1,
				]],
				'mode' => 'subscription',
				'success_url' => get_permalink(get_option('account_page')) . '?session_id={CHECKOUT_SESSION_ID}', // Use account_page setting
				'cancel_url' => get_permalink(get_option('pricing_plans_page')), // Use pricing_plans_page setting
				'metadata' => $metadata,
				'client_reference_id' => (string)$plan_id
			]);
			
			wp_send_json_success([
				'checkout_url' => $session->url,
			]);
			
		} catch (\Exception $e) {
			wp_send_json_error(['message' => 'Error creating checkout session: ' . $e->getMessage()]);
		}
	}

	/**
	 * Handle webhook events
	 */
	public function handle_webhook_event() {
		error_log('Starting webhook event handler');
		
		$payload = @file_get_contents('php://input');
		error_log('Webhook payload length: ' . strlen($payload));
		
		if (!isset($_SERVER['HTTP_STRIPE_SIGNATURE'])) {
			error_log('Missing Stripe signature header');
			http_response_code(400);
			exit('Missing signature header');
		}
		
		$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
		error_log('Stripe signature present: ' . ($sig_header ? 'Yes' : 'No'));
		
		try {
			$stripe = new Subs_Sys_Stripe();
			$webhook_secret = get_option('subscription_stripe_webhook_secret');
			
			if (empty($webhook_secret)) {
				error_log('Webhook secret is not configured');
				http_response_code(400);
				exit('Webhook secret not configured');
			}
			
			error_log('Verifying webhook signature');
			$event = $stripe->verify_webhook($payload, $sig_header, $webhook_secret);
			
			if (!$event) {
				error_log('Invalid webhook signature');
				http_response_code(400);
				exit('Invalid webhook signature');
			}
			
			error_log('Webhook event type: ' . $event->type);
			
			// Handle the event
			switch ($event->type) {
				case 'checkout.session.completed':
					error_log('Processing checkout.session.completed event');
					$session = $event->data->object;
					error_log('Session ID: ' . $session->id);
					
					// Call handle_checkout_completed directly
					$result = $this->handle_checkout_completed($session);
					error_log('handle_checkout_completed result: ' . ($result ? 'Success' : 'Failed'));
					break;
					
				// Other cases...
			}
			
			http_response_code(200);
			exit('Webhook processed successfully');
			
		} catch (\Exception $e) {
			error_log('Webhook error: ' . $e->getMessage());
			error_log('Exception trace: ' . $e->getTraceAsString());
			http_response_code(500);
			exit('Webhook error: ' . esc_html($e->getMessage()));
		}
	}

	/**
	 * Handle checkout.session.completed event
	 */
	public function handle_checkout_completed($session) {
		error_log('Starting handle_checkout_completed');
		error_log('Session data: ' . json_encode($session));
		
		try {
			// Get metadata
			$metadata = isset($session->metadata) ? $session->metadata : new stdClass();
			error_log('Session metadata: ' . json_encode($metadata));
			
			// Try to get plan_id from different sources
			$plan_id = null;
			if (isset($metadata->plan_id)) {
				$plan_id = $metadata->plan_id;
				error_log('Plan ID from metadata: ' . $plan_id);
			} elseif (isset($session->client_reference_id)) {
				$plan_id = $session->client_reference_id;
				error_log('Plan ID from client_reference_id: ' . $plan_id);
			}
			
			// Try to get user_id from different sources
			$user_id = null;
			if (isset($metadata->user_id)) {
				$user_id = $metadata->user_id;
				error_log('User ID from metadata: ' . $user_id);
			}
			
			// If we don't have a 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;
					error_log('User ID found by email: ' . $user_id);
				}
			}
			
			if (!$plan_id) {
				error_log('Missing plan_id in session data');
				return false;
			}
			
			if (!$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;
			}
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for plan details
			error_log('Plan details: ' . wp_json_encode($plan));
			
			// 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')
			);
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for subscription data
			error_log('Subscription data prepared: ' . wp_json_encode($subscription_data));
			
			// Use the DB class directly for more reliable insertion
			$db = new Subs_Sys_DB();
			$subscription_id = $db->direct_insert_subscription($subscription_data);
			
			if (!$subscription_id) {
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for subscription creation failure
				error_log('Failed to create subscription');
				return false;
			}
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful subscription creation
			error_log('Subscription created successfully with ID: ' . $subscription_id);
			
			// Create an order for this subscription
			$this->create_subscription_order($subscription_id, $session);
			
			return true;
		} catch (\Exception $e) {
			error_log('Error in handle_checkout_completed: ' . $e->getMessage());
			error_log('Exception trace: ' . $e->getTraceAsString());
			return false;
		}
	}

	/**
	 * Test direct subscription creation
	 */
	public function test_direct_subscription() {
		// Basic security check
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Permission denied']);
			return;
		}
		
		global $wpdb;
		
		// Get a valid plan ID
		$plans_table = $wpdb->prefix . 'subscription_plans';
		$plan = $wpdb->get_row("SELECT * FROM $plans_table LIMIT 1");
		
		if (!$plan) {
			wp_send_json_error(['message' => 'No subscription plans found']);
			return;
		}
		
		// Get current user
		$user_id = get_current_user_id();
		$user = get_userdata($user_id);
		
		if (!$user) {
			wp_send_json_error(['message' => 'User not found']);
			return;
		}
		
		// Create test data
		$test_data = [
			'user_id' => $user_id,
			'plan_id' => $plan->id,
			'customer_email' => $user->user_email,
			'customer_name' => $user->display_name,
			'payment_id' => 'test_direct_' . time(),
			'amount' => $plan->price,
			'status' => 'active',
			'start_date' => current_time('mysql'),
			'end_date' => date('Y-m-d H:i:s', strtotime('+30 days')),
			'created_at' => current_time('mysql'),
			'updated_at' => current_time('mysql')
		];
		
		// Try to fix the table first
		$manager = new Subs_Sys_Manager();
		$fix_result = $manager->fix_subscriptions_table();
		
		if (!$fix_result) {
			wp_send_json_error(['message' => 'Failed to fix subscriptions table']);
			return;
		}
		
		// Try direct insert
		$subscription_id = $manager->direct_insert_subscription($test_data);
		
		if (!$subscription_id) {
			wp_send_json_error([
				'message' => 'Direct insert failed',
				'error' => $wpdb->last_error,
				'query' => $wpdb->last_query
			]);
			return;
		}
		
		wp_send_json_success([
			'message' => 'Subscription created successfully',
			'subscription_id' => $subscription_id,
			'data' => $test_data
		]);
	}

	/**
	 * Test database structure
	 */
	public function test_db_structure() {
		// Basic security check
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Permission denied']);
			return;
		}
		
		global $wpdb;
		$db = new Subs_Sys_DB();
		
		// Create the table with the correct structure
		$result = $db->create_subscriptions_table();
		
		if (!$result) {
			wp_send_json_error(['message' => 'Failed to create subscriptions table']);
			return;
		}
		
		// Get table structure
		$table_name = $wpdb->prefix . 'subscriptions';
		$columns = $wpdb->get_results("DESCRIBE $table_name", ARRAY_A);
		
		// Test insert
		$test_data = [
			'user_id' => 1,
			'plan_id' => 1,
			'customer_email' => 'test@example.com',
			'customer_name' => 'Test User',
			'payment_id' => 'test_' . time(),
			'amount' => 9.99,
			'status' => 'test',
			'start_date' => current_time('mysql'),
			'end_date' => date('Y-m-d H:i:s', strtotime('+30 days')),
			'created_at' => current_time('mysql'),
			'updated_at' => current_time('mysql')
		];
		
		$subscription_id = $db->direct_insert_subscription($test_data);
		
		if (!$subscription_id) {
			wp_send_json_error([
				'message' => 'Test insert failed',
				'error' => $wpdb->last_error,
				'query' => $wpdb->last_query,
				'table_structure' => $columns
			]);
			return;
		}
		
		// Clean up test data
		$wpdb->delete($table_name, ['id' => $subscription_id]);
		
		wp_send_json_success([
			'message' => 'Database structure is correct and working',
			'table_structure' => $columns
		]);
	}

	/**
	 * Test webhook processing directly
	 */
	public function test_webhook_processing() {
		// Basic security check
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Permission denied']);
			return;
		}
		
		// Get a valid plan ID
		global $wpdb;
		$plans_table = $wpdb->prefix . 'subscription_plans';
		$plan = $wpdb->get_row("SELECT * FROM $plans_table LIMIT 1");
		
		if (!$plan) {
			wp_send_json_error(['message' => 'No subscription plans found']);
			return;
		}
		
		// Get current user
		$user_id = get_current_user_id();
		$user = get_userdata($user_id);
		
		if (!$user) {
			wp_send_json_error(['message' => 'User not found']);
			return;
		}
		
		// Create a mock session object
		$session = new stdClass();
		$session->id = 'test_session_' . time();
		$session->client_reference_id = $plan->id;
		
		// Add metadata
		$session->metadata = new stdClass();
		$session->metadata->plan_id = $plan->id;
		$session->metadata->user_id = $user_id;
		
		// Add customer details
		$session->customer_details = new stdClass();
		$session->customer_details->email = $user->user_email;
		$session->customer_details->name = $user->display_name;
		
		// Process the mock session
		$result = $this->handle_checkout_completed($session);
		
		if (!$result) {
			wp_send_json_error([
				'message' => 'Failed to process mock webhook',
				'session' => $session
			]);
			return;
		}
		
		wp_send_json_success([
			'message' => 'Mock webhook processed successfully',
			'session' => $session
		]);
	}

	/**
	 * Create a checkout session
	 */
	public function create_checkout_session() {
		// Check nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_checkout_nonce')) {
			wp_send_json_error(['message' => 'Security check failed.']);
			return;
		}
		
		// Get plan ID
		$plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
		
		if (!$plan_id) {
			wp_send_json_error(['message' => 'No plan selected.']);
			return;
		}
		
		// Get user
		$user_id = get_current_user_id();
		$user = get_userdata($user_id);
		
		if (!$user) {
			wp_send_json_error(['message' => 'User not logged in.']);
			return;
		}
		
		// Get plan details
		$manager = new Subs_Sys_Manager();
		$plan = $manager->get_plan($plan_id);
		
		if (!$plan) {
			wp_send_json_error(['message' => 'Invalid plan.']);
			return;
		}
		
		// Create metadata with all necessary information
		$metadata = [
			'plan_id' => $plan_id,
			'user_id' => $user_id,
			'customer_email' => $user->user_email,
			'customer_name' => $user->display_name
		];
		
		error_log('Creating checkout session with metadata: ' . json_encode($metadata));
		
		// Create checkout session for RECURRING subscription
		try {
			$stripe = new Subs_Sys_Stripe();
			
			$session = \Stripe\Checkout\Session::create([
				'payment_method_types' => ['card'],
				'line_items' => [[
					'price_data' => [
						'currency' => 'usd',
						'product_data' => [
							'name' => $plan->plan_name,
						],
						'unit_amount' => intval($plan->price * 100),
						'recurring' => [
							'interval' => 'month',
						],
					],
					'quantity' => 1,
				]],
				'mode' => 'subscription',
				'success_url' => get_permalink(get_option('thank_you_page')) . '?session_id={CHECKOUT_SESSION_ID}', // Use thank_you_page setting
				'cancel_url' => get_permalink(get_option('pricing_plans_page')), // Use pricing_plans_page setting
				'metadata' => $metadata,
				'client_reference_id' => (string)$plan_id
			]);
			
			wp_send_json_success([
				'checkout_url' => $session->url,
			]);
			
		} catch (\Exception $e) {
			wp_send_json_error(['message' => 'Error creating checkout session: ' . $e->getMessage()]);
		}
	}

	/**
	 * Check if a user has already subscribed to a plan
	 */
	public function check_user_subscription() {
		// Verify nonce
		if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'subscription_check_nonce')) {
			wp_send_json_error(['message' => 'Security check failed']);
			return;
		}
		
		// Check if plan ID is provided
		if (!isset($_POST['plan_id'])) {
			wp_send_json_error(['message' => 'Plan ID is required']);
			return;
		}
		
		$plan_id = intval($_POST['plan_id']);
		$user_id = get_current_user_id();
		
		// Query the database to check if the user has this subscription
		global $wpdb;
		$table_name = $wpdb->prefix . 'subscription_user_subscriptions';
		
		$subscription = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM $table_name WHERE user_id = %d AND plan_id = %d AND status = 'active'",
				$user_id,
				$plan_id
			)
		);
		
		// Return the result
		wp_send_json_success([
			'has_subscription' => !empty($subscription),
			'subscription' => $subscription
		]);
	}

	/**
	 * Get content options for admin interface
	 */
	public function get_content_options() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'get_content_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'subscription-system' ) ) );
			return;
		}

		$content_type    = isset( $_POST['content_type'] ) ? sanitize_text_field( wp_unslash( $_POST['content_type'] ) ) : '';
		$selected_ids    = isset( $_POST['selected_ids'] ) ? json_decode( stripslashes( $_POST['selected_ids'] ), true ) : array();
		$editing_plan_id = isset( $_POST['plan_id'] ) ? absint( $_POST['plan_id'] ) : 0;

		if ( ! is_array( $selected_ids ) ) {
			$selected_ids = array();
		}

		if ( empty( $content_type ) ) {
			wp_send_json_error( array( 'message' => __( 'Content type is required.', 'subscription-system' ) ) );
			return;
		}

		// Build a map of term/item ID → plan name for already-claimed IDs (category & tag only).
		$claimed = array(); // [ id => plan_name ]
		if ( in_array( $content_type, array( 'category', 'tag' ), true ) && Subs_Sys_DB_Updater::content_tables_exist() ) {
			global $wpdb;
			$table  = $wpdb->prefix . 'subscription_content_plans';
			$query  = $wpdb->prepare(
				"SELECT id, plan_name, content_ids FROM $table WHERE content_type = %s AND status = 'active'",
				$content_type
			);
			if ( $editing_plan_id ) {
				$query = $wpdb->prepare(
					"SELECT id, plan_name, content_ids FROM $table WHERE content_type = %s AND status = 'active' AND id != %d",
					$content_type,
					$editing_plan_id
				);
			}
			$other_plans = $wpdb->get_results( $query );
			foreach ( $other_plans as $op ) {
				$ids = json_decode( $op->content_ids, true ) ?: array();
				foreach ( $ids as $id ) {
					$claimed[ (int) $id ] = $op->plan_name;
				}
			}
		}

		$html = '';

		switch ( $content_type ) {
			case 'category':
				$categories = get_categories( array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC' ) );
				$html = '<div class="content-checkboxes">';
				foreach ( $categories as $category ) {
					$tid        = (int) $category->term_id;
					$is_claimed = isset( $claimed[ $tid ] );
					$checked    = ! $is_claimed && ( in_array( $tid, $selected_ids, true ) || in_array( (string) $tid, $selected_ids, true ) ) ? 'checked' : '';
					if ( $is_claimed ) {
						$html .= sprintf(
							'<label class="ss-claimed-item" title="%s"><input type="checkbox" name="content_ids[]" value="%d" disabled> %s <span class="ss-claimed-badge">%s</span></label><br>',
							esc_attr( sprintf( __( 'Already used by plan: %s', 'subscription-system' ), $claimed[ $tid ] ) ),
							$tid,
							esc_html( $category->name ),
							esc_html( sprintf( __( 'Used by: %s', 'subscription-system' ), $claimed[ $tid ] ) )
						);
					} else {
						$html .= sprintf(
							'<label><input type="checkbox" name="content_ids[]" value="%d" %s> %s <span class="ss-post-count">(%d)</span></label><br>',
							$tid,
							$checked,
							esc_html( $category->name ),
							(int) $category->count
						);
					}
				}
				$html .= '</div>';
				break;

			case 'tag':
				$tags = get_tags( array( 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC' ) );
				$html = '<div class="content-checkboxes">';
				foreach ( $tags as $tag ) {
					$tid        = (int) $tag->term_id;
					$is_claimed = isset( $claimed[ $tid ] );
					$checked    = ! $is_claimed && ( in_array( $tid, $selected_ids, true ) || in_array( (string) $tid, $selected_ids, true ) ) ? 'checked' : '';
					if ( $is_claimed ) {
						$html .= sprintf(
							'<label class="ss-claimed-item" title="%s"><input type="checkbox" name="content_ids[]" value="%d" disabled> %s <span class="ss-claimed-badge">%s</span></label><br>',
							esc_attr( sprintf( __( 'Already used by plan: %s', 'subscription-system' ), $claimed[ $tid ] ) ),
							$tid,
							esc_html( $tag->name ),
							esc_html( sprintf( __( 'Used by: %s', 'subscription-system' ), $claimed[ $tid ] ) )
						);
					} else {
						$html .= sprintf(
							'<label><input type="checkbox" name="content_ids[]" value="%d" %s> %s <span class="ss-post-count">(%d)</span></label><br>',
							$tid,
							$checked,
							esc_html( $tag->name ),
							(int) $tag->count
						);
					}
				}
				$html .= '</div>';
				break;

			case 'post':
				$posts = get_posts( array(
					'numberposts' => 100,
					'post_status' => 'publish',
					'orderby'     => 'title',
					'order'       => 'ASC',
				) );
				$html = '<div class="content-checkboxes">';
				foreach ( $posts as $post ) {
					$checked = in_array( $post->ID, $selected_ids, true ) || in_array( (string) $post->ID, $selected_ids, true ) ? 'checked' : '';
					$html .= sprintf(
						'<label><input type="checkbox" name="content_ids[]" value="%d" %s> %s</label><br>',
						$post->ID,
						$checked,
						esc_html( $post->post_title )
					);
				}
				$html .= '</div>';
				break;

			case 'post_type':
				$post_types = get_post_types( array( 'public' => true ), 'objects' );
				$html = '<div class="content-checkboxes">';
				foreach ( $post_types as $post_type ) {
					$checked = in_array( $post_type->name, $selected_ids, true ) ? 'checked' : '';
					$html .= sprintf(
						'<label><input type="checkbox" name="content_ids[]" value="%s" %s> %s</label><br>',
						esc_attr( $post_type->name ),
						$checked,
						esc_html( $post_type->label )
					);
				}
				$html .= '</div>';
				break;

			default:
				wp_send_json_error( array( 'message' => __( 'Invalid content type.', 'subscription-system' ) ) );
				return;
		}

		wp_send_json_success( $html );
	}

	/**
	 * Subscribe user to content plan
	 */
	public function subscribe_to_content_plan() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'subscribe_to_content_plan' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
			return;
		}

		// Check if user is logged in
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in to subscribe.', 'subscription-system' ) ) );
			return;
		}

		$user_id = get_current_user_id();
		$content_plan_id = isset( $_POST['content_plan_id'] ) ? intval( $_POST['content_plan_id'] ) : 0;

		if ( empty( $content_plan_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid content plan.', 'subscription-system' ) ) );
			return;
		}

		$content_manager = new Subs_Sys_Content_Manager();

		// Check if plan exists and is active
		$plan = $content_manager->get_content_plan( $content_plan_id );
		if ( ! $plan || $plan->status !== 'active' ) {
			wp_send_json_error( array( 'message' => __( 'Content plan not found or inactive.', 'subscription-system' ) ) );
			return;
		}

		// Check if user is already subscribed
		$existing_subscription = $content_manager->get_user_content_subscription( $user_id, $content_plan_id );
		if ( $existing_subscription && $existing_subscription->status === 'active' ) {
			wp_send_json_error( array( 'message' => __( 'You are already subscribed to this content plan.', 'subscription-system' ) ) );
			return;
		}

		// If it's a paid plan, we need to handle payment
		if ( $plan->price > 0 ) {
			// For paid plans, redirect to payment
			$checkout_url = add_query_arg( array(
				'action'          => 'content_checkout',
				'content_plan_id' => $content_plan_id
			), home_url() );
			
			wp_send_json_success( array( 
				'redirect' => $checkout_url,
				'message'  => __( 'Redirecting to payment...', 'subscription-system' )
			) );
			return;
		}

		// Ensure content tables exist
		if ( ! Subs_Sys_DB_Updater::content_tables_exist() ) {
			// Create content tables
			$db_updater = new Subs_Sys_DB_Updater();
			$db_updater->add_content_subscription_tables();
			error_log( 'Content subscription tables created due to missing tables.' );
		}

		// For free plans, subscribe immediately
		$result = $content_manager->subscribe_user_to_content( $user_id, $content_plan_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			return;
		}

		// Log successful subscription for debugging
		error_log( "Content subscription created successfully. User ID: $user_id, Plan ID: $content_plan_id, Subscription ID: $result" );

		wp_send_json_success( array( 
			'message' => __( 'Successfully subscribed to content plan!', 'subscription-system' )
		) );
	}

	/**
	 * Process content subscription payment
	 */
	public function process_content_subscription_payment() {
		// Verify nonce
		if ( ! isset( $_POST['payment_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['payment_nonce'] ) ), 'content_subscription_payment' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
			return;
		}

		// Check if user is logged in
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in to subscribe.', 'subscription-system' ) ) );
			return;
		}

		$user_id = get_current_user_id();
		$content_plan_id = isset( $_POST['plan_id'] ) ? intval( $_POST['plan_id'] ) : 0;

		if ( empty( $content_plan_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid content plan.', 'subscription-system' ) ) );
			return;
		}

		$content_manager = new Subs_Sys_Content_Manager();

		// Check if plan exists and is active
		$plan = $content_manager->get_content_plan( $content_plan_id );
		if ( ! $plan || $plan->status !== 'active' ) {
			wp_send_json_error( array( 'message' => __( 'Content plan not found or inactive.', 'subscription-system' ) ) );
			return;
		}

		// Check if user is already subscribed
		$existing_subscription = $content_manager->get_user_content_subscription( $user_id, $content_plan_id );
		if ( $existing_subscription && $existing_subscription->status === 'active' ) {
			wp_send_json_error( array( 'message' => __( 'You are already subscribed to this content plan.', 'subscription-system' ) ) );
			return;
		}

		// For now, we'll handle free plans immediately
		// For paid plans, you would integrate with Stripe here
		if ( $plan->price == 0 ) {
			// Free plan - subscribe immediately
			$result = $content_manager->subscribe_user_to_content( $user_id, $content_plan_id );

			if ( is_wp_error( $result ) ) {
				wp_send_json_error( array( 'message' => $result->get_error_message() ) );
				return;
			}

			wp_send_json_success( array( 
				'message' => __( 'Successfully subscribed to content plan!', 'subscription-system' ),
				'redirect_url' => add_query_arg( array( 'tab' => 'content-subscriptions' ), get_permalink() )
			) );
		} else {
			// Paid plan - integrate with Stripe
			error_log('Processing paid plan subscription for plan ID: ' . $content_plan_id);
			
			// Check if Stripe is configured
			$stripe_secret_key = get_option('subscription_stripe_secret_key');
			if (empty($stripe_secret_key)) {
				error_log('Stripe secret key not configured');
				wp_send_json_error( array( 'message' => __( 'Payment system not configured. Please contact support.', 'subscription-system' ) ) );
				return;
			}
			
			// Create a Stripe checkout session
			error_log('Initializing Stripe...');
			try {
				$stripe = new Subs_Sys_Stripe();
				error_log('Stripe initialized successfully');
			} catch (Exception $e) {
				error_log('Stripe initialization failed: ' . $e->getMessage());
				wp_send_json_error( array( 'message' => __( 'Payment system error. Please try again later.', 'subscription-system' ) ) );
				return;
			}
			
			try {
				error_log('Creating Stripe checkout session for plan ID: ' . $content_plan_id);
				error_log('Plan price: ' . $plan->price);
				error_log('Plan has Stripe product ID: ' . ($plan->stripe_product_id ? 'Yes' : 'No'));
				
				// Create checkout session with price_data instead of price_id for simplicity
				$checkout_session = \Stripe\Checkout\Session::create([
					'payment_method_types' => ['card'],
					'line_items' => [[
						'price_data' => [
							'currency' => 'usd',
							'product_data' => [
								'name' => $plan->plan_name,
								'description' => $plan->description,
							],
							'unit_amount' => $plan->price * 100, // Convert to cents
							'recurring' => [
								'interval' => $plan->duration_unit === 'months' ? 'month' : 'day',
								'interval_count' => $plan->duration
							],
						],
						'quantity' => 1,
					]],
					'mode' => 'subscription',
					'success_url' => add_query_arg( array(
						'content_subscription_success' => '1',
						'plan_id' => $content_plan_id
					), home_url() ),
					'cancel_url' => add_query_arg( array(
						'content_subscription_cancelled' => '1',
						'plan_id' => $content_plan_id
					), home_url() ),
					'metadata' => array(
						'user_id' => $user_id,
						'content_plan_id' => $content_plan_id,
						'type' => 'content_subscription'
					),
				]);

				error_log('Stripe checkout session created successfully: ' . $checkout_session->url);
				
				wp_send_json_success( array( 
					'redirect_url' => $checkout_session->url,
					'message' => __( 'Redirecting to payment...', 'subscription-system' )
				) );

			} catch ( \Exception $e ) {
				error_log( 'Stripe error: ' . $e->getMessage() );
				wp_send_json_error( array( 'message' => __( 'Payment processing error. Please try again.', 'subscription-system' ) ) );
			}
		}
	}

	/**
	 * Unsubscribe user from content plan
	 */
	public function unsubscribe_from_content_plan() {
		// Verify nonce
		if ( ! isset( $_POST['unsubscribe_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['unsubscribe_nonce'] ) ), 'unsubscribe_from_content_plan' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
			return;
		}

		// Check if user is logged in
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => __( 'You must be logged in to unsubscribe.', 'subscription-system' ) ) );
			return;
		}

		$user_id = get_current_user_id();
		$content_plan_id = isset( $_POST['plan_id'] ) ? intval( $_POST['plan_id'] ) : 0;

		if ( empty( $content_plan_id ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid content plan.', 'subscription-system' ) ) );
			return;
		}

		$content_manager = new Subs_Sys_Content_Manager();

		// Check if user is subscribed to this plan
		$user_subscription = $content_manager->get_user_content_subscription( $user_id, $content_plan_id );
		if ( ! $user_subscription || $user_subscription->status !== 'active' ) {
			wp_send_json_error( array( 'message' => __( 'You are not subscribed to this content plan.', 'subscription-system' ) ) );
			return;
		}

		// Unsubscribe the user
		$result = $content_manager->unsubscribe_user_from_content( $user_id, $content_plan_id );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
			return;
		}

		wp_send_json_success( array( 
			'message' => __( 'Successfully unsubscribed from content plan.', 'subscription-system' )
		) );
	}

	/**
	 * Test AJAX functionality
	 */
	public function test_content_ajax() {
		wp_send_json_success( array( 
			'message' => 'AJAX is working!',
			'post_data' => $_POST
		) );
	}

	/**
	 * Handle interest subscription form submission from the popup modal.
	 */
	public function submit_interest_subscription() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'interest_subscription_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'subscription-system' ) ) );
		}

		if ( ! Subs_Sys_DB_Updater::interest_table_exists() ) {
			$db_updater = new Subs_Sys_DB_Updater();
			$db_updater->add_interest_subscription_table();
		}

		$category_ids = isset( $_POST['category_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['category_ids'] ) ) : array();
		$tag_ids      = isset( $_POST['tag_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['tag_ids'] ) ) : array();
		$plan_id      = isset( $_POST['plan_id'] ) ? absint( $_POST['plan_id'] ) : 0;
		$plan_source  = isset( $_POST['plan_source'] ) && 'content' === sanitize_text_field( wp_unslash( $_POST['plan_source'] ) ) ? 'content' : 'interest';

		$interest = new Subs_Sys_Interest_Subscription();
		$result   = $interest->save_subscription(
			array(
				'name'         => isset( $_POST['subscriber_name'] ) ? wp_unslash( $_POST['subscriber_name'] ) : '',
				'email'        => isset( $_POST['subscriber_email'] ) ? wp_unslash( $_POST['subscriber_email'] ) : '',
				'category_ids' => $category_ids,
				'tag_ids'      => $tag_ids,
				'plan_id'      => $plan_id,
				'plan_source'  => $plan_source,
			)
		);

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		// Look up plan price from the appropriate table.
		if ( 'content' === $plan_source ) {
			$plan = Subs_Sys_Interest_Subscription::get_content_plan_by_id( $plan_id );
		} else {
			$plan = Subs_Sys_Interest_Subscription::get_plan_by_id( $plan_id );
		}
		$is_free = $plan && (float) $plan->price <= 0;

		if ( ! $is_free ) {
			$checkout_url = add_query_arg(
				array(
					'action'                   => 'interest_checkout',
					'interest_subscription_id' => $result,
				),
				home_url( '/' )
			);

			wp_send_json_success(
				array(
					'message'  => __( 'Subscription saved. Redirecting to payment...', 'subscription-system' ),
					'redirect' => $checkout_url,
					'plan_id'  => $plan_id,
					'price'    => $plan ? (float) $plan->price : 0,
				)
			);
		}

		wp_send_json_success(
			array(
				'message' => __( 'You are subscribed! You will receive updates for your selected categories and tags.', 'subscription-system' ),
				'plan_id' => $plan_id,
			)
		);
	}
}