<?php
/**
 * Subscription Manager Class
 *
 * Handles subscription management functionality.
 *
 * @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;
}

if ( ! class_exists( 'Subs_Sys_Manager' ) ) {
	/**
	 * Handles subscription management functionality.
	 *
	 * @since      1.0.0
	 * @package    Subs_Sys
	 * @subpackage Subs_Sys/includes
	 * @author     Joe Youngblood <support@subscriptionplugin.com>
	 */
	class Subs_Sys_Manager {

		/**
		 * The database handler.
		 *
		 * @since    1.0.0
		 * @access   private
		 * @var      Subs_Sys_DB    $db    The database handler.
		 */
		private $db;

		/**
		 * Initialize the class and set its properties.
		 *
		 * @since    1.0.0
		 */
		public function __construct() {
			if ( ! class_exists( 'WP_Error' ) ) {
				require_once ABSPATH . 'wp-includes/class-wp-error.php';
			}
			$this->db = new Subs_Sys_DB();
		}

		/**
		 * Create a new subscription
		 * 
		 * @since 1.0.0
		 * @param int   $user_id The user ID.
		 * @param int   $plan_id The plan ID.
		 * @param array $args Additional arguments.
		 * @return int|WP_Error The subscription ID or WP_Error on failure.
		 */
		public function create_subscription( $user_id, $plan_id, $args = array() ) {
			global $wpdb;
			
			// Input validation
			$user_id = absint( $user_id );
			$plan_id = absint( $plan_id );
			
			if ( empty( $user_id ) || empty( $plan_id ) ) {
				return new WP_Error( 'invalid_data', __( 'User ID and Plan ID are required.', 'subscription-system' ) );
			}
			
			// Get the plan details
			$plan = $this->get_plan( $plan_id );
			if ( ! $plan ) {
				return new WP_Error( 'invalid_plan', __( 'Invalid plan ID', 'subscription-system' ) );
			}
			
			// Set default values
			$defaults = array(
				'status'         => 'active',
				'start_date'     => current_time( 'mysql' ),
				'amount'         => $plan->price,
				'payment_method' => 'stripe',
				'customer_email' => '',
				'customer_name'  => '',
				'payment_id'     => 'manual_' . time(),
			);
			
			$data = wp_parse_args( $args, $defaults );
			
			// Get user details if not provided
			if ( empty( $data['customer_email'] ) || empty( $data['customer_name'] ) ) {
				$user = get_userdata( $user_id );
				if ( $user ) {
					if ( empty( $data['customer_email'] ) ) {
						$data['customer_email'] = $user->user_email;
					}
					if ( empty( $data['customer_name'] ) ) {
						$data['customer_name'] = $user->display_name;
					}
				}
			}
			
			// Calculate end date
			$duration = isset( $plan->duration ) ? absint( $plan->duration ) : 30;
			$end_timestamp = strtotime( '+' . $duration . ' days', strtotime( $data['start_date'] ) );
			$data['end_date'] = gmdate( 'Y-m-d H:i:s', $end_timestamp );
			
			// Prepare the data for insertion
			$insert_data = array(
				'user_id'        => $user_id,
				'plan_id'        => $plan_id,
				'customer_email' => sanitize_email( $data['customer_email'] ),
				'customer_name'  => sanitize_text_field( $data['customer_name'] ),
				'payment_id'     => sanitize_text_field( $data['payment_id'] ),
				'amount'         => floatval( $data['amount'] ),
				'status'         => sanitize_text_field( $data['status'] ),
				'start_date'     => sanitize_text_field( $data['start_date'] ),
				'end_date'       => sanitize_text_field( $data['end_date'] ),
				'created_at'     => current_time( 'mysql' ),
				'updated_at'     => current_time( 'mysql' ),
			);
			
			// Insert subscription
			$table_name = $wpdb->prefix . 'subscriptions';
			$result = $wpdb->insert( $table_name, $insert_data );
			
			if ( false === $result ) {
				return new WP_Error( 'db_insert_error', $wpdb->last_error );
			}
			
			$subscription_id = $wpdb->insert_id;
			
			// Add a hook for other code to run after subscription creation
			do_action( 'subs_sys_subscription_created', $subscription_id, $insert_data );
			
			return $subscription_id;
		}

		/**
		 * Ensure subscriptions table exists with correct structure
		 */
		private function ensure_subscriptions_table_exists() {
			global $wpdb;
			$subscription_table = $wpdb->prefix . 'subscriptions';
			
			// Test database connection and permissions
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for database testing
			error_log('Testing database connection and permissions...');
			try {
				$test_result = $wpdb->query("SELECT 1");
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for database test
				error_log('Basic database query test: ' . ($test_result !== false ? 'Success' : 'Failed'));
				
				// Test if we can create a temporary table
				$temp_table = $wpdb->prefix . 'temp_test_' . time();
				$create_result = $wpdb->query("CREATE TEMPORARY TABLE $temp_table (id INT)");
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for temp table test
				error_log('Create temporary table test: ' . ($create_result !== false ? 'Success' : 'Failed'));
				
				if ($create_result === false) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for permission error
					error_log('Create table permission error: ' . $wpdb->last_error);
				}
			} catch (Exception $e) {
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for database exception
				error_log('Database test exception: ' . $e->getMessage());
			}
			
			// 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 check
			error_log('Checking if subscriptions table exists: ' . ($table_exists == $subscription_table ? 'Yes' : 'No'));
			
			if ($table_exists != $subscription_table) {
				// Create the table
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table creation
				error_log('Creating subscriptions 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 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) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table creation failure
					error_log('Failed to create subscriptions table');
					return false;
				}
				
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful table creation
				error_log('Subscriptions table created successfully');
			} else {
				// Table exists, check if we can write to it
				try {
					$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' => 'test',
						'start_date' => current_time('mysql'),
						'end_date' => current_time('mysql'),
						'created_at' => current_time('mysql'),
						'updated_at' => current_time('mysql')
					);
					
					$insert_result = $wpdb->insert($subscription_table, $test_data);
					error_log('Test insert result: ' . ($insert_result !== false ? 'Success' : 'Failed'));
					
					if ($insert_result === false) {
						error_log('Insert permission error: ' . $wpdb->last_error);
					} else {
						// Clean up test data
						$test_id = $wpdb->insert_id;
						$wpdb->delete($subscription_table, array('id' => $test_id));
						error_log('Test data cleaned up successfully');
					}
				} catch (Exception $e) {
					error_log('Test insert exception: ' . $e->getMessage());
				}
			}
			
			return true;
		}

		/**
		 * Update a subscription.
		 *
		 * @since    1.0.0
		 * @param    int      $subscription_id      The subscription ID.
		 * @param    array    $subscription_data    The subscription data.
		 * @return   bool|WP_Error                  True on success, WP_Error on failure.
		 */
		public function update_subscription($subscription_id, $subscription_data) {
			// Check if subscription exists
			$subscription = $this->db->get_subscription($subscription_id);
			
			if (!$subscription) {
				return new WP_Error('not_found', __('Subscription not found', 'subscription-system'));
			}
			
			// Update the subscription
			$result = $this->db->update_subscription($subscription_id, $subscription_data);
			
			if (!$result) {
				return new WP_Error('db_error', __('Failed to update subscription', 'subscription-system'));
			}
			
			// Trigger action for other plugins
			do_action('ss_subscription_updated', $subscription_id, $subscription_data, $subscription);
			
			return true;
		}

		/**
		 * Cancel a subscription.
		 *
		 * @since    1.0.0
		 * @param    int      $subscription_id    The subscription ID.
		 * @return   bool|WP_Error                True on success, WP_Error on failure.
		 */
		public function cancel_subscription($subscription_id) {
			// Check if subscription exists
			$subscription = $this->db->get_subscription($subscription_id);
			
			if (!$subscription) {
				return new WP_Error('not_found', __('Subscription not found', 'subscription-system'));
			}
			
			// Update the subscription status
			$result = $this->db->update_subscription($subscription_id, array(
				'status' => 'cancelled',
				'end_date' => current_time('mysql')
			));
			
			if (!$result) {
				return new WP_Error('db_error', __('Failed to cancel subscription', 'subscription-system'));
			}
			
			// Trigger action for other plugins
			do_action('ss_subscription_cancelled', $subscription_id, $subscription);
			
			return true;
		}

		/**
		 * Get a subscription by ID.
		 *
		 * @since    1.0.0
		 * @param    int      $subscription_id    The subscription ID.
		 * @return   object|WP_Error              The subscription object or WP_Error if not found.
		 */
		public function get_subscription($subscription_id) {
			$subscription = $this->db->get_subscription($subscription_id);
			
			if (!$subscription) {
				return new WP_Error('not_found', __('Subscription not found', 'subscription-system'));
			}
			
			return $subscription;
		}

		/**
		 * Get subscriptions by user ID.
		 *
		 * @since    1.0.0
		 * @param    int      $user_id    The user ID.
		 * @return   array                The subscriptions.
		 */
		public function get_user_subscriptions($user_id) {
			return $this->db->get_subscriptions_by_user($user_id);
		}

		/**
		 * Check if a user has an active subscription.
		 *
		 * @since    1.0.0
		 * @param    int      $user_id    The user ID.
		 * @param    string   $plan_id    Optional. The plan ID to check for.
		 * @return   bool                 True if the user has an active subscription, false otherwise.
		 */
		public function has_active_subscription($user_id, $plan_id = '') {
			$subscriptions = $this->db->get_subscriptions_by_user($user_id);
			
			foreach ($subscriptions as $subscription) {
				if ($subscription->status === 'active') {
					if (empty($plan_id) || $subscription->plan_id === $plan_id) {
						return true;
					}
				}
			}
			
			return false;
		}

		/**
		 * Get all subscription plans.
		 *
		 * @since    1.0.0
		 * @param    int      $category_id    Optional category ID to filter plans by.
		 * @return   array                    Array of subscription plan objects.
		 */
		public function get_subscription_plans($category_id = 0) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			// Check if table exists
			if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
				// Table doesn't exist, create it
				$this->create_subscription_plans_table();
			}
			
			// Build the query based on whether a category ID was provided
			$where_clause = "WHERE status = 'active'";
			if ($category_id > 0) {
				$where_clause .= $wpdb->prepare(" AND category_id = %d", $category_id);
			}
			
			$plans = $wpdb->get_results("SELECT * FROM $table_name $where_clause ORDER BY price ASC");
			
			$plans = $plans ? $plans : array();
			
			return apply_filters('ss_subscription_plans', $plans);
		}

		/**
		 * Get a specific subscription plan.
		 *
		 * @since    1.0.0
		 * @param    string   $plan_id    The plan ID.
		 * @return   array|false          The plan data or false if not found.
		 */
		public function get_subscription_plan($plan_id) {
			$plans = $this->get_subscription_plans();
			
			if (isset($plans[$plan_id])) {
				return $plans[$plan_id];
			}
			
			return false;
		}

		/**
		 * Update subscription plans.
		 *
		 * @since    1.0.0
		 * @param    array    $plans    The subscription plans.
		 * @return   bool               True on success, false on failure.
		 */
		public function update_subscription_plans($plans) {
			return update_option('ss_subscription_plans', $plans);
		}

		/**
		 * Get all plan categories.
		 *
		 * @return array Array of plan categories.
		 */
		public function get_plan_categories() {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plan_categories';
			
			// Check if table exists
			if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
				// Table doesn't exist, create it
				$this->create_plan_categories_table();
			}
			
			$categories = $wpdb->get_results("SELECT * FROM $table_name ORDER BY name ASC");
			
			return $categories ? $categories : array();
		}

		/**
		 * Create the plan categories table
		 */
		private function create_plan_categories_table() {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plan_categories';
			
			$charset_collate = $wpdb->get_charset_collate();
			
			$sql = "CREATE TABLE $table_name (
				id mediumint(9) NOT NULL AUTO_INCREMENT,
				category_name varchar(255) NOT NULL,
				category_description text,
				date_created datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
				PRIMARY KEY  (id)
			) $charset_collate;";
			
			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
			dbDelta($sql);
			
			// Add a default category if none exist
			$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
			if ($count == 0) {
				$wpdb->insert(
					$table_name,
					array(
						'category_name' => 'Default',
						'category_description' => 'Default subscription plan category'
					)
				);
			}
		}

		/**
		 * Create the subscription plans table
		 */
		private function create_subscription_plans_table() {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			$charset_collate = $wpdb->get_charset_collate();
			
			$sql = "CREATE TABLE $table_name (
				id mediumint(9) NOT NULL AUTO_INCREMENT,
				plan_name varchar(255) NOT NULL,
				description text,
				price decimal(10,2) NOT NULL DEFAULT 0,
				duration int NOT NULL DEFAULT 30,
				category_id mediumint(9) NOT NULL,
				date_created datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
				PRIMARY KEY  (id)
			) $charset_collate;";
			
			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
			dbDelta($sql);
			
			// Add a default plan if none exist
			$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
			if ($count == 0) {
				// Get the default category ID
				$category_table = $wpdb->prefix . 'subscription_plan_categories';
				$category_id = $wpdb->get_var("SELECT id FROM $category_table LIMIT 1");
				
				if ($category_id) {
					$wpdb->insert(
						$table_name,
						array(
							'plan_name' => 'Basic Plan',
							'description' => 'Basic subscription plan',
							'price' => 9.99,
							'duration' => 30,
							'category_id' => $category_id
						)
					);
				}
			}
		}

		/**
		 * Add a new subscription plan
		 *
		 * @param array $plan_data Plan data
		 * @return int|false The ID of the inserted plan or false on failure
		 */
		public function add_subscription_plan($plan_data) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			// If description is JSON, decode it to ensure it's stored properly
			if (isset($plan_data['description']) && $this->is_json($plan_data['description'])) {
				// Store as a clean JSON string without extra escaping
				$plan_data['description'] = wp_json_encode(json_decode($plan_data['description']));
			}
			
			$result = $wpdb->insert(
				$table_name,
				array(
					'plan_name' => $plan_data['plan_name'],
					'description' => $plan_data['description'],
					'price' => $plan_data['price'],
					'duration' => $plan_data['duration'],
					'category_id' => $plan_data['category_id']
				)
			);
			
			return $result ? $wpdb->insert_id : false;
		}

		/**
		 * Update an existing subscription plan
		 *
		 * @param int $plan_id Plan ID
		 * @param array $plan_data Plan data
		 * @return bool True on success, false on failure
		 */
		public function update_subscription_plan($plan_id, $plan_data) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			// If description is JSON, decode it to ensure it's stored properly
			if (isset($plan_data['description']) && $this->is_json($plan_data['description'])) {
				// Store as a clean JSON string without extra escaping
				$plan_data['description'] = wp_json_encode(json_decode($plan_data['description']));
			}
			
			$result = $wpdb->update(
				$table_name,
				array(
					'plan_name' => $plan_data['plan_name'],
					'description' => $plan_data['description'],
					'price' => $plan_data['price'],
					'duration' => $plan_data['duration'],
					'category_id' => $plan_data['category_id']
				),
				array('id' => $plan_id)
			);
			
			return $result !== false;
		}

		/**
		 * Check if a string is valid JSON
		 *
		 * @param string $string The string to check
		 * @return bool True if valid JSON, false otherwise
		 */
		private function is_json($string) {
			json_decode($string);
			return (json_last_error() == JSON_ERROR_NONE);
		}

		/**
		 * Delete a subscription plan
		 *
		 * @param int $plan_id Plan ID
		 * @return bool True on success, false on failure
		 */
		public function delete_subscription_plan($plan_id) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			$result = $wpdb->delete(
				$table_name,
				array('id' => $plan_id)
			);
			
			return $result !== false;
		}

		// Look for the form submission section in the add_new_plan method
		public function add_new_plan() {
			// ... existing code ...
			
			?>
			<div class="wrap">
				<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
				<form method="post" action="">
					<!-- ... existing form fields ... -->
					
					<?php wp_nonce_field( 'add_plan_nonce', 'add_plan_nonce' ); ?>
					
					<p class="submit">
						<input type="submit" name="submit_plan" class="button button-primary" value="<?php esc_attr_e( 'Add Plan', 'subscription-system' ); ?>">
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=subscription-plans' ) ); ?>" class="button button-secondary"><?php esc_html_e( 'Cancel', 'subscription-system' ); ?></a>
					</p>
				</form>
			</div>
			<?php
			
			// ... existing code ...
		}

		/**
		 * Get a plan category by ID.
		 *
		 * @param int $category_id The category ID.
		 * @return object|null The category object or null if not found.
		 */
		public function get_plan_category($category_id) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plan_categories';
			
			$category = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $category_id));
			
			return $category;
		}

		/**
		 * Update a subscription plan
		 * 
		 * @param int $plan_id The plan ID
		 * @param array $data The plan data
		 * @return bool|WP_Error True on success, WP_Error on failure
		 */
		public function update_plan($plan_id, $data) {
			global $wpdb;
			
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			// Prepare the data for update
			$update_data = array();
			$update_format = array();
			
			// Only include fields that are provided
			if (isset($data['plan_name'])) {
				$update_data['plan_name'] = sanitize_text_field($data['plan_name']);
				$update_format[] = '%s';
			}
			
			if (isset($data['category_id'])) {
				$update_data['category_id'] = intval($data['category_id']);
				$update_format[] = '%d';
			}
			
			if (isset($data['description'])) {
				$update_data['description'] = wp_kses_post($data['description']);
				$update_format[] = '%s';
			}
			
			if (isset($data['features'])) {
				$update_data['features'] = is_array($data['features']) ? serialize($data['features']) : $data['features'];
				$update_format[] = '%s';
			}
			
			if (isset($data['price'])) {
				$update_data['price'] = floatval($data['price']);
				$update_format[] = '%f';
			}
			
			if (isset($data['billing_cycle'])) {
				$update_data['billing_cycle'] = sanitize_text_field($data['billing_cycle']);
				$update_format[] = '%s';
			}
			
			if (isset($data['status'])) {
				$update_data['status'] = sanitize_text_field($data['status']);
				$update_format[] = '%s';
			}
			
			if (isset($data['stripe_product_id'])) {
				$update_data['stripe_product_id'] = sanitize_text_field($data['stripe_product_id']);
				$update_format[] = '%s';
			}
			
			if (isset($data['stripe_price_id'])) {
				$update_data['stripe_price_id'] = sanitize_text_field($data['stripe_price_id']);
				$update_format[] = '%s';
			}
			
			// Update the plan
			$result = $wpdb->update(
				$table_name,
				$update_data,
				array('id' => $plan_id),
				$update_format,
				array('%d')
			);
			
			if ($result === false) {
				return new WP_Error('db_update_error', 'Failed to update plan: ' . $wpdb->last_error);
			}
			
			return true;
		}

		/**
		 * Get a subscription plan by ID
		 * 
		 * @param int $plan_id The plan ID
		 * @return object|null The plan object or null if not found
		 */
		public function get_plan($plan_id) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscription_plans';
			
			$plan = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $plan_id));
			
			return $plan;
		}

		/**
		 * Calculate the renewal date based on start date and duration
		 * 
		 * @param string $start_date The start date in MySQL format
		 * @param int $duration The duration in days
		 * @return string The renewal date in MySQL format
		 */
		public function calculate_renewal_date($start_date, $duration = 30) {
			$start_timestamp = strtotime($start_date);
			$renewal_timestamp = strtotime("+{$duration} days", $start_timestamp);
			return date('Y-m-d H:i:s', $renewal_timestamp);
		}

		/**
		 * Fix subscriptions table structure
		 * 
		 * @return bool True if successful, false otherwise
		 */
		public function fix_subscriptions_table() {
			global $wpdb;
			$subscription_table = $wpdb->prefix . 'subscriptions';
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table fix attempt
			error_log('Attempting to fix subscriptions table structure...');
			
			// Drop the table if it exists (this is a drastic measure, but effective)
			$wpdb->query("DROP TABLE IF EXISTS $subscription_table");
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table drop
			error_log('Dropped existing subscriptions table');
			
			// Create the table with the correct structure
			$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 NOT NULL,
				updated_at datetime 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) {
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for table recreation failure
				error_log('Failed to create subscriptions table');
				return false;
			}
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful table recreation
			error_log('Subscriptions table recreated successfully');
			
			// Test insert
			$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' => 'test',
				'start_date' => current_time('mysql'),
				'end_date' => current_time('mysql'),
				'created_at' => current_time('mysql'),
				'updated_at' => current_time('mysql')
			);
			
			$insert_result = $wpdb->insert($subscription_table, $test_data);
			if ($insert_result === false) {
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for test insert failure
				error_log('Test insert failed: ' . $wpdb->last_error);
				return false;
			}
			
			// Clean up test data
			$test_id = $wpdb->insert_id;
			$wpdb->delete($subscription_table, array('id' => $test_id));
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful test
			error_log('Test insert successful, table is working correctly');
			
			return true;
		}

		/**
		 * Direct insert subscription (simplified version for debugging)
		 * 
		 * @param array $data Subscription data
		 * @return int|false Subscription ID or false on failure
		 */
		public function direct_insert_subscription($data) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'subscriptions';
			
			// Ensure required fields
			$required_fields = ['user_id', 'plan_id', 'customer_email', 'customer_name', 'payment_id', 
								'amount', 'status', 'start_date', 'end_date'];
			
			foreach ($required_fields as $field) {
				if (!isset($data[$field]) || empty($data[$field])) {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for missing field
					error_log("Missing required field: $field");
					return false;
				}
			}
			
			// Add timestamps if not provided
			if (!isset($data['created_at'])) {
				$data['created_at'] = current_time('mysql');
			}
			if (!isset($data['updated_at'])) {
				$data['updated_at'] = current_time('mysql');
			}
			
			// Enable error display
			$wpdb->show_errors();
			
			// Try direct query approach
			$columns = implode(', ', array_keys($data));
			$placeholders = implode(', ', array_fill(0, count($data), '%s'));
			
			$query = $wpdb->prepare(
				"INSERT INTO $table_name ($columns) VALUES ($placeholders)",
				array_values($data)
			);
			
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for direct query
			error_log("Executing direct query: $query");
			
			$result = $wpdb->query($query);
			
			if ($result === false) {
				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for direct insert failure
				error_log("Direct insert failed: " . $wpdb->last_error);
				return false;
			}
			
			$subscription_id = $wpdb->insert_id;
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging for successful direct insert
			error_log("Direct insert successful, ID: $subscription_id");
			
			return $subscription_id;
		}
	}
} 