<?php
ob_start();
/**
 * The admin-specific functionality of the plugin.
 *
 * @since      1.0.0
 * @package    Subs_Sys
 */

class Subs_Sys_Admin {

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

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

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

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param    string    $plugin_name       The name of this plugin.
     * @param    string    $version           The version of this plugin.
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->subscription_manager = new Subs_Sys_Manager();
        
        // Register activation hook
        register_activation_hook(SUBS_SYS_PLUGIN_BASENAME, array($this, 'activate_plugin'));
        
        // Check and update database schema
        add_action('admin_init', array($this, 'check_database_schema'));
        
        // Register all admin menus in proper order
        add_action('admin_menu', array($this, 'register_admin_menus'), 10);
        
        // Add database update handler
        add_action('admin_init', array($this, 'handle_database_update'));
        
        // Register settings
        add_action('admin_init', array($this, 'register_settings'));

        // Register AJAX handlers
        add_action('admin_init', array($this, 'register_ajax_handlers'));

        // Process form submissions
        add_action('admin_init', array($this, 'process_forms'));

        // Register plugin hooks
        add_action('admin_init', array($this, 'register_hooks'));
    }

    /**
     * Register all admin menus in the proper order
     * 
     * @since 1.0.6
     */
    public function register_admin_menus() {
        // 1. Main Dashboard
        $this->add_dashboard_submenu();
        
        // 2. Plans (core feature)
        $this->add_plans_submenu();
        
        // 3. Plan Categories (supporting plans)
        $this->add_plan_categories_submenu();
        
        // 4. Content Plans (content-based subscriptions)
        $this->add_content_plans_submenu();
        
        // 5. Subscribers (user management)
        $this->add_subscribers_submenu();
        
        // 6. Content Subscribers (content-specific subscribers)
        $this->add_content_subscribers_submenu();

        // 6b. Interest Subscribers (category/tag popup subscriptions)
        $this->add_interest_subscribers_submenu();
        
        // 7. Channels
        // $this->add_channels_submenu();
        
        // 8. Work Items
        $this->add_work_items_submenu();
        
        // 9. Work Logs
        $this->add_work_logs_submenu();
        
        // 10. Email Logs (monitoring)
        $this->add_email_logs_submenu();
        
        // 11. Settings (configuration)
        $this->add_settings_submenu();
        
        // 12. Plan Settings (if it doesn't already exist from CPT)
        if (!$this->pricing_settings_menu_exists()) {
            $this->add_pricing_settings_to_cpt();
        }
        
        // 13. Help & Support (help)
        $this->add_help_support_submenu();
    }
    
    /**
     * Check if the pricing settings menu already exists
     */
    private function pricing_settings_menu_exists() {
        global $submenu;
        
        // Check if the submenu for the subscription post type exists
        if (isset($submenu['edit.php?post_type=subscription'])) {
            // Loop through the submenu items
            foreach ($submenu['edit.php?post_type=subscription'] as $item) {
                // Check if the menu slug matches our pricing settings slug
                if (isset($item[2]) && $item[2] === 'subscription-pricing-settings') {
                    return true;
                }
            }
        }
        
        return false;
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        $screen = get_current_screen();
        
        // Always load the main admin CSS
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url(__FILE__) . 'css/subscription-system-admin.css',
            array(),
            $this->version,
            'all'
        );
        
        // Load specific CSS for the subscribers page
        if ($screen && $screen->id === 'subscription_page_subscription-subscribers') {
            wp_enqueue_style(
                $this->plugin_name . '-subscribers',
                plugin_dir_url(__FILE__) . 'css/subscription-system-subscribers.css',
                array($this->plugin_name),
                $this->version,
                'all'
            );
        }
    }

    /**
     * Register the JavaScript for the admin area.
     */
    public function enqueue_scripts() {
        wp_enqueue_script('subscription-admin', plugin_dir_url(__FILE__) . 'js/subscription-admin.js', array('jquery'), $this->version, false);
        
        wp_localize_script('subscription-admin', 'subscription_data', array(
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'nonces' => array(
                'test_stripe_connection' => esc_attr(wp_create_nonce('test_stripe_connection')),
                'install_stripe_sdk' => esc_attr(wp_create_nonce('install_stripe_sdk')),
                'sync_plan_with_stripe' => esc_attr(wp_create_nonce('sync_plan_with_stripe'))
            )
        ));
    }

    /**
     * Add Pricing Settings submenu to the existing Subscriptions custom post type menu
     */
    public function add_pricing_settings_to_cpt() {
        // First, try to remove any existing pricing settings menu items
        remove_submenu_page('edit.php?post_type=subscription', 'subscription-pricing-settings');
        
        // Then add our pricing settings menu
        add_submenu_page(
            'subscription-dashboard', // Parent menu slug
            __('Plan Settings', 'subscription-system'), // Page title
            __('Plan Settings', 'subscription-system'), // Menu title
            'manage_options', // Capability
            'subscription-pricing-settings', // Menu slug
            array($this, 'render_pricing_settings_page') // Callback function
        );
    }

    /**
     * Render the Pricing Settings page content
     */
    public function render_pricing_settings_page() {
        // Get current settings
        $default_layout = get_option('subscription_default_layout', 'layout1');
        
        // Include the pricing settings template only once
        static $included = false;
        if (!$included) {
            include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/pricing-settings-display.php';
            $included = true;
        }
    }

    /**
     * Handle AJAX requests for subscription management.
     *
     * @since    1.0.0
     */
    public function ajax_manage_subscription() {
        // Check nonce
        if (!isset($_POST['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')));
        // }
        
        $action = isset($_POST['ss_action']) ? sanitize_text_field($_POST['ss_action']) : '';
        $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')));
        }
        
        switch ($action) {
            case 'cancel':
                $result = $this->subscription_manager->cancel_subscription($subscription_id);
                
                if (is_wp_error($result)) {
                    wp_send_json_error(array('message' => $result->get_error_message()));
                } else {
                    wp_send_json_success(array('message' => __('Subscription cancelled successfully.', 'subscription-system')));
                }
                break;
                
            case 'pause':
                $result = $this->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 {
                    wp_send_json_success(array('message' => __('Subscription paused successfully.', 'subscription-system')));
                }
                break;
                
            case 'resume':
                $result = $this->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 {
                    wp_send_json_success(array('message' => __('Subscription resumed successfully.', 'subscription-system')));
                }
                break;
                
            case 'delete':
                $db = new Subs_Sys_DB();
                $result = $db->delete_subscription($subscription_id);
                
                if ($result) {
                    wp_send_json_success(array('message' => __('Subscription deleted successfully.', 'subscription-system')));
                } else {
                    wp_send_json_error(array('message' => __('Failed to delete subscription.', 'subscription-system')));
                }
                break;
                
            case 'update_status':
                $status = isset($_POST['status']) ? sanitize_text_field($_POST['status']) : '';
                
                if (empty($status)) {
                    wp_send_json_error(array('message' => __('Invalid status.', 'subscription-system')));
                }
                
                $result = $this->subscription_manager->update_subscription($subscription_id, array('status' => $status));
                
                if (is_wp_error($result)) {
                    wp_send_json_error(array('message' => $result->get_error_message()));
                } else {
                    wp_send_json_success(array('message' => __('Subscription status updated successfully.', 'subscription-system')));
                }
                break;
                
            default:
                wp_send_json_error(array('message' => __('Invalid action.', 'subscription-system')));
                break;
        }
    }

    /**
     * Plugin activation hook.
     *
     * @since    1.0.0
     */
    public function activate_plugin() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // Create subscription plans table
        $table_name = $wpdb->prefix . 'subscription_plans';
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            plan_name varchar(255) NOT NULL,
            category_id mediumint(9) NOT NULL,
            description text NOT NULL,
            price decimal(10,6) NOT NULL,
            duration int(11) NOT NULL,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        
        // Create plan categories table
        $table_name = $wpdb->prefix . 'subscription_plan_categories';
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            category_name varchar(255) NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        dbDelta($sql);
        
        // Create channels table
        $table_name = $wpdb->prefix . 'subscription_channels';
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            description text NOT NULL,
            status varchar(50) NOT NULL DEFAULT 'active',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        dbDelta($sql);
        
        // Create work items table
        $table_name = $wpdb->prefix . 'subscription_work_items';
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            description text NOT NULL,
            status varchar(50) NOT NULL DEFAULT 'active',
            channel_id mediumint(9) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        dbDelta($sql);
        
        // Add default category if none exists
        $categories = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}subscription_plan_categories");
        
        if (empty($categories)) {
            $wpdb->insert(
                $wpdb->prefix . 'subscription_plan_categories',
                array(
                    'category_name' => 'Default'
                ),
                array('%s')
            );
        }
        
        // Force recreation of the plan categories table to ensure it has the correct structure
        $db = new Subs_Sys_DB();
        $db->create_plan_categories_table();
        
        // Set default settings if not already set
        if (!get_option('ss_settings')) {
            update_option('ss_settings', array(
                'currency' => 'USD',
                'currency_position' => 'before',
                'success_page' => 0,
                'cancel_page' => 0,
                'enable_email_notifications' => 1,
                'admin_email' => get_option('admin_email')
            ));
        }
        
        // Initialize default plans
        $this->subscription_manager->get_subscription_plans();
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Get subscription count by status
     * 
     * @param string $status The subscription status to count
     * @return int The number of subscriptions with the given status
     */
    private function get_subscription_count($status) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscriptions';
        
        $count = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM $table_name WHERE status = %s",
                $status
            )
        );
        
        return $count ? $count : 0;
    }

    /**
     * Add Dashboard submenu to the Subscriptions menu
     */
    public function add_dashboard_submenu() {
        add_menu_page(
            esc_html__('Subscription System', 'subscription-system'),
            esc_html__('Subscription System', 'subscription-system'),
            'manage_options',
            'subscription-dashboard',
            array($this, 'render_dashboard_page'),
            'dashicons-cart',
            30
        );

        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Dashboard', 'subscription-system'),
            esc_html__('Dashboard', 'subscription-system'),
            'manage_options',
            'subscription-dashboard',
            array($this, 'render_dashboard_page')
        );
    }

    /**
     * Display orders page
     */
    public function display_orders_page() {
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/partials/orders-display.php';
    }

    /**
     * Render the Dashboard page content
     */
    public function render_dashboard_page() {
        // Get subscription statistics
        $active_subscriptions = $this->get_subscription_count('active');
        $paused_subscriptions = $this->get_subscription_count('paused');
        $total_revenue = $this->get_total_revenue();
        
        // Include the dashboard template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/dashboard-display.php';
    }

    /**
     * Get total revenue from all subscriptions
     * 
     * @return float The total revenue
     */
    private function get_total_revenue() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscriptions';
        
        $total = $wpdb->get_var(
            "SELECT SUM(amount) FROM $table_name WHERE status = 'active'"
        );
        
        return $total ? $total : 0;
    }

    /**
     * Remove unwanted submenu items and keep only the Dashboard, Plan Categories, Plans, and Settings
     */
    public function customize_admin_menu() {
        global $submenu, $menu;
        
        // 1. Keep only specific submenus under Subscriptions
        if (isset($submenu['edit.php?post_type=subscription'])) {
            foreach ($submenu['edit.php?post_type=subscription'] as $key => $item) {

             
                // Keep only these specific submenus
                if ($item[2] !== 'subscription-dashboard' && 
                    $item[2] !== 'subscription-plan-categories' && 
                    $item[2] !== 'subscription-plans' && 
                    $item[2] !== 'subscription-settings') {
                    remove_submenu_page('edit.php?post_type=subscription', $item[2]);
                }
            }
        }
        
        // 2. Remove subscription-related pages from Posts menu
        if (isset($submenu['edit.php'])) {
            foreach ($submenu['edit.php'] as $key => $item) {
                if (strpos($item[2], 'subscription') !== false) {
                    remove_submenu_page('edit.php', $item[2]);
                }
            }
        }
        
        // 3. Remove subscription-related pages from Tools menu
        if (isset($submenu['tools.php'])) {
            foreach ($submenu['tools.php'] as $key => $item) {
                if (strpos($item[2], 'subscription') !== false) {
                    remove_submenu_page('tools.php', $item[2]);
                }
            }
        }
        
        // 4. Remove subscription-related pages from Settings menu
        if (isset($submenu['options-general.php'])) {
            foreach ($submenu['options-general.php'] as $key => $item) {
                if (strpos($item[2], 'subscription') !== false) {
                    remove_submenu_page('options-general.php', $item[2]);
                }
            }
        }
        
        // 5. Check all other top-level menus
        foreach ($menu as $key => $item) {
            $menu_slug = $item[2];
            // Skip the subscription menu itself
            if ($menu_slug === 'edit.php?post_type=subscription') {
                continue;
            }
            
            // Check if this menu has submenus
            if (isset($submenu[$menu_slug])) {
                foreach ($submenu[$menu_slug] as $subkey => $subitem) {
                    if (strpos($subitem[2], 'subscription') !== false) {
                        remove_submenu_page($menu_slug, $subitem[2]);
                    }
                }
            }
        }
        
        // 6. Redirect away from subscription post type pages
        $screen = get_current_screen();
        if (isset($screen) && $screen->post_type === 'subscription' && $screen->base !== 'edit-subscription' && !isset($_GET['page']) && $_GET['page'] !== 'subscription-dashboard') {
            wp_redirect(admin_url('edit.php?post_type=subscription&page=subscription-dashboard'));
            exit;
        }
    }

    /**
     * Redirect subscription post type pages to the dashboard
     */
    public function redirect_subscription_pages() {
        global $pagenow, $post_type;
        
        // Check if we're on a subscription-related page
        if ($post_type === 'subscription') {
            // Allow access to the dashboard, plan categories, plans, and settings pages
            if (isset($_GET['page']) && (
                $_GET['page'] === 'subscription-dashboard' || 
                $_GET['page'] === 'subscription-plan-categories' || 
                $_GET['page'] === 'subscription-plans' || 
                $_GET['page'] === 'subscription-settings'
            )) {
                // Allow access to these pages
                return;
            }
            
            // Use wp_safe_redirect instead of wp_redirect
            wp_safe_redirect(admin_url('edit.php?post_type=subscription&page=subscription-dashboard'));
            exit;
        }
    }

    /**
     * Add Plan Categories submenu to the Subscriptions menu
     */
    public function add_plan_categories_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Plan Categories', 'subscription-system'),
            esc_html__('Plan Categories', 'subscription-system'),
            'manage_options',
            'subscription-plan-categories',
            array($this, 'render_plan_categories_page')
        );
    }

    /**
     * Render the Plan Categories page content
     */
    public function render_plan_categories_page() {
        // Check if we need to recreate the table
        if (isset($_GET['action']) && $_GET['action'] === 'recreate_table' && isset($_GET['_wpnonce'])) {
            if (wp_verify_nonce($_GET['_wpnonce'], 'recreate_categories_table')) {
                $db = new Subs_Sys_DB();
                $db->create_plan_categories_table();
                
                add_settings_error(
                    'subscription_messages',
                    'table_recreated',
                    __('Categories table recreated successfully.', 'subscription-system'),
                    'updated'
                );
            }
        }
        
        // Process form submissions
        $this->process_category_form();
        
        // Get all categories
        $db = new Subs_Sys_DB();
        $categories = $db->get_plan_categories();
        
        // Include the plan categories template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/plan-categories-display.php';
    }

    /**
     * Process category form submissions (add, edit, delete)
     */
    private function process_category_form() {
        $db = new Subs_Sys_DB();
        
        // Add new category
        if (isset($_POST['add_category']) && isset($_POST['category_name'])) {
            check_admin_referer('subscription_add_category', 'subscription_nonce');
            
            $category_name = sanitize_text_field(wp_unslash($_POST['category_name']));
            $category_description = isset($_POST['category_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['category_description'])) : '';
            
            if (!empty($category_name)) {
                $result = $db->add_plan_category($category_name, $category_description);
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'category_added',
                        __('Category added successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'category_add_failed',
                        __('Failed to add category.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'category_name_empty',
                    __('Category name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Edit category
        if (isset($_POST['edit_category']) && isset($_POST['category_id']) && isset($_POST['category_name'])) {
            check_admin_referer('subscription_edit_category', 'subscription_nonce');
            
            $category_id = intval($_POST['category_id']);
            $category_name = sanitize_text_field(wp_unslash($_POST['category_name']));
            $category_description = isset($_POST['category_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['category_description'])) : '';
            
            if (!empty($category_name)) {
                $result = $db->update_plan_category($category_id, $category_name, $category_description);
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'category_updated',
                        __('Category updated successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'category_update_failed',
                        __('Failed to update category.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'category_name_empty',
                    __('Category name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Delete category
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['category_id']) && isset($_GET['_wpnonce'])) {
            $category_id = intval($_GET['category_id']);
            
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_category_' . $category_id)) {
                $result = $db->delete_plan_category($category_id);
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'category_deleted',
                        __('Category deleted successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'category_delete_failed',
                        __('Failed to delete category.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'invalid_nonce',
                    __('Security check failed.', 'subscription-system'),
                    'error'
                );
            }
        }
    }

    /**
     * Add Plans submenu to the Subscriptions menu
     */
    public function add_plans_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Plans', 'subscription-system'),
            esc_html__('Plans', 'subscription-system'),
            'manage_options',
            'subscription-plans',
            array($this, 'render_plans_page')
        );
    }

    /**
     * Render the Plans page content
     */
    public function render_plans_page() {
   
        // Handle form submissions only when POST data is present
        if (!empty($_POST)) {
            $this->handle_plan_actions();
        }
        
        // Get all subscription plans
        $plans = $this->subscription_manager->get_subscription_plans();
        
        // Get plan categories for the dropdown
        $categories = $this->subscription_manager->get_plan_categories();

        // Include the plans template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/plans-display.php';
    }

    /**
     * Handle plan management
     */
    public function handle_plan_actions() {
        // Check if this is a POST request
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            return;
        }

        // Handle add plan form
        if (isset($_POST['add_plan']) && isset($_POST['subscription_nonce'])) {
            if (wp_verify_nonce($_POST['subscription_nonce'], 'subscription_add_plan')) {
                $plan_data = array(
                    'plan_name' => isset($_POST['plan_name']) ? sanitize_text_field($_POST['plan_name']) : '',
                    'description' => isset($_POST['description']) ? sanitize_text_field($_POST['description']) : '',
                    'price' => isset($_POST['price']) ? floatval($_POST['price']) : 0,
                    'duration' => isset($_POST['duration']) ? intval($_POST['duration']) : 30,
                    'category_id' => isset($_POST['category_id']) ? intval($_POST['category_id']) : 0,
                    'status' => 'active'
                );
                
                $result = $this->subscription_manager->add_subscription_plan($plan_data);
                
                if (is_wp_error($result)) {
                    add_settings_error('subscription_messages', 'plan_add_error', $result->get_error_message(), 'error');
                } else {
                    add_settings_error('subscription_messages', 'plan_added', __('Plan added successfully.', 'subscription-system'), 'updated');
                    set_transient('subscription_messages', get_settings_errors('subscription_messages'), 30);
                    wp_redirect(admin_url('admin.php?page=subscription-plans&settings-updated=1'));
                    exit;
                }
            }
            return;
        }
        
        // Handle edit plan form
        if (isset($_POST['edit_plan']) && isset($_POST['subscription_nonce'])) {
            if (wp_verify_nonce($_POST['subscription_nonce'], 'subscription_edit_plan')) {
                $plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
                
                if ($plan_id > 0) {
                    $plan_data = array(
                        'plan_name' => isset($_POST['plan_name']) ? sanitize_text_field($_POST['plan_name']) : '',
                        'description' => isset($_POST['description']) ? sanitize_text_field($_POST['description']) : '',
                        'price' => isset($_POST['price']) ? floatval($_POST['price']) : 0,
                        'duration' => isset($_POST['duration']) ? intval($_POST['duration']) : 30,
                        'category_id' => isset($_POST['category_id']) ? intval($_POST['category_id']) : 0,
                        'updated_at' => current_time('mysql')
                    );
                    
                    $result = $this->subscription_manager->update_subscription_plan($plan_id, $plan_data);
                    
                    if (is_wp_error($result)) {
                        add_settings_error('subscription_messages', 'plan_update_error', $result->get_error_message(), 'error');
                    } else {
                        add_settings_error('subscription_messages', 'plan_updated', __('Plan updated successfully.', 'subscription-system'), 'updated');
                        set_transient('subscription_messages', get_settings_errors('subscription_messages'), 30);
                        wp_redirect(admin_url('admin.php?page=subscription-plans&settings-updated=1'));
                        exit;
                    }
                }
            }
            return;
        }

        // Check if we have an action (for AJAX requests)
        if (!isset($_POST['action'])) {
            return;
        }

        // Verify nonce
        if (!isset($_POST['subscription_nonce']) || !wp_verify_nonce($_POST['subscription_nonce'], 'subscription_' . $_POST['action'] . '_plan')) {
            wp_send_json_error(array(
                'message' => esc_html__('Security check failed.', 'subscription-system')
            ));
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => esc_html__('You do not have permission to perform this action.', 'subscription-system')
            ));
        }

        $action = sanitize_text_field($_POST['action']);
        
        switch ($action) {
            case 'add':
                $plan_data = $this->validate_plan_data($_POST);
                if (is_wp_error($plan_data)) {
                    wp_send_json_error(array(
                        'message' => esc_html($plan_data->get_error_message())
                    ));
                }

                if ($this->add_plan($plan_data)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Plan added successfully', 'subscription-system'),
                        'redirect' => esc_url_raw(admin_url('edit.php?post_type=subscription&page=subscription-plans'))
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to add plan. Please try again.', 'subscription-system')
                    ));
                }
                break;

            case 'update':
                $plan_id = isset($_POST['id']) ? intval($_POST['id']) : 0;
                if (!$plan_id) {
                    wp_send_json_error(array(
                        'message' => esc_html__('Invalid plan ID', 'subscription-system')
                    ));
                }

                $plan_data = $this->validate_plan_data($_POST);
                if (is_wp_error($plan_data)) {
                    wp_send_json_error(array(
                        'message' => esc_html($plan_data->get_error_message())
                    ));
                }

                if ($this->update_plan($plan_id, $plan_data)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Plan updated successfully', 'subscription-system'),
                        'redirect' => esc_url_raw(admin_url('edit.php?post_type=subscription&page=subscription-plans'))
                    ));
                }
                break;

            case 'delete':
                $plan_id = isset($_POST['id']) ? intval($_POST['id']) : 0;
                
                if ($this->delete_plan($plan_id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Plan deleted successfully.', 'subscription-system')
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to delete plan. Please try again.', 'subscription-system')
                    ));
                }
                break;

            default:
                wp_send_json_error(array(
                    'message' => esc_html__('Invalid action.', 'subscription-system')
                ));
                break;
        }
    }

    /**
     * Validate plan data
     */
    private function validate_plan_data($data) {
        $required_fields = array('name', 'price', 'duration');
        
        foreach ($required_fields as $field) {
            if (!isset($data[$field]) || empty($data[$field])) {
                /* translators: %s: name of the required field that is missing */
                return new WP_Error('missing_field', sprintf(
                    esc_html__('Missing required field: %s', 'subscription-system'),
                    esc_html($field)
                ));
            }
        }

        return array(
            'name' => sanitize_text_field($data['name']),
            'price' => floatval($data['price']),
            'duration' => intval($data['duration']),
            'description' => isset($data['description']) ? sanitize_textarea_field($data['description']) : '',
            'features' => isset($data['features']) ? array_map('sanitize_text_field', $data['features']) : array()
        );
    }

    /**
     * Add Settings submenu to the Subscriptions menu
     */
    public function add_settings_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Settings', 'subscription-system'),
            esc_html__('Settings', 'subscription-system'),
            'manage_options',
            'subscription-settings',
            array($this, 'render_settings_page')
        );
    }

    /**
     * Add Content Subscribers submenu to the Subscriptions menu
     */
    public function add_content_subscribers_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Content Subscribers', 'subscription-system'),
            esc_html__('Content Subscribers', 'subscription-system'),
            'manage_options',
            'content-subscribers',
            array($this, 'render_content_subscribers_page')
        );
    }

    /**
     * Render the Content Subscribers page content
     */
    public function render_content_subscribers_page() {
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/content-subscribers-display.php';
    }

    /**
     * Add Interest Subscribers submenu.
     */
    public function add_interest_subscribers_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__( 'Interest Subscribers', 'subscription-system' ),
            esc_html__( 'Interest Subscribers', 'subscription-system' ),
            'manage_options',
            'interest-subscribers',
            array( $this, 'render_interest_subscribers_page' )
        );
    }

    /**
     * Render Interest Subscribers admin page.
     */
    public function render_interest_subscribers_page() {
        include plugin_dir_path( dirname( __FILE__ ) ) . 'admin/partials/interest-subscribers-display.php';
    }

    /**
     * Add Email Logs submenu to the Subscriptions menu
     */
    public function add_email_logs_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Email Logs', 'subscription-system'),
            esc_html__('Email Logs', 'subscription-system'),
            'manage_options',
            'subscription-email-logs',
            array($this, 'render_email_logs_page')
        );
    }

    /**
     * Render the Email Logs page content
     */
    public function render_email_logs_page() {
        // Enqueue email logs specific CSS
        wp_enqueue_style(
            'subs-sys-email-logs',
            plugin_dir_url(__FILE__) . 'css/email-logs.css',
            array(),
            SUBS_SYS_VERSION,
            'all'
        );
        
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/email-logs-display.php';
    }

    /**
     * Render the Settings page content
     */
    public function render_settings_page() {
        // Get current tab
        $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'general';
        
        // Include the settings template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/settings-display.php';
    }

    /**
     * Register settings for the plugin.
     */
    public function register_settings() {
        // General settings
        register_setting('subscription_general_settings', 'enable_subscriptions');
        register_setting('subscription_general_settings', 'show_pause_button');
        register_setting('subscription_general_settings', 'show_cancel_button');
        register_setting('subscription_general_settings', 'default_pricing_layout');
        
        // Payment settings
        register_setting('subscription_payment_settings', 'enable_stripe');
        register_setting('subscription_payment_settings', 'stripe_mode', array(
            'default' => 'test'
        ));
        register_setting('subscription_payment_settings', 'stripe_api_key', array(
            'sanitize_callback' => array($this, 'validate_stripe_api_key_setting')
        ));
        register_setting('subscription_payment_settings', 'stripe_publishable_key');
        register_setting('subscription_payment_settings', 'stripe_webhook_secret');
        
        // Communication settings
        register_setting('subscription_communication_settings', 'enable_email_notifications');
        register_setting('subscription_communication_settings', 'admin_email');
        register_setting('subscription_communication_settings', 'subscription_from_email');
        register_setting('subscription_communication_settings', 'subscription_from_name');
        register_setting('subscription_communication_settings', 'subscription_enable_smtp');
        register_setting('subscription_communication_settings', 'subscription_smtp_host');
        register_setting('subscription_communication_settings', 'subscription_smtp_port');
        register_setting('subscription_communication_settings', 'subscription_smtp_encryption');
        register_setting('subscription_communication_settings', 'subscription_smtp_auth');
        register_setting('subscription_communication_settings', 'subscription_smtp_username');
        register_setting('subscription_communication_settings', 'subscription_smtp_password');
        
        // Pages settings
        register_setting('subscription_pages_settings', 'login_page');
        register_setting('subscription_pages_settings', 'account_page');
        register_setting('subscription_pages_settings', 'register_page');
        register_setting('subscription_pages_settings', 'thank_you_page');
        register_setting('subscription_pages_settings', 'pricing_plans_page');
        register_setting('subscription_pages_settings', 'edit_profile_page');
        register_setting('subscription_pages_settings', 'forgot_password_page');
        register_setting('subscription_pages_settings', 'contact_page');
        register_setting('subscription_pages_settings', 'subscription_cancel_page');
        register_setting('subscription_pages_settings', 'content_subscription_success_page');
        
        // Reset Password Page
        register_setting(
            'subs_sys_settings',
            'subscription_reset_password_page',
            array(
                'type' => 'integer',
                'sanitize_callback' => 'absint',
                'default' => 0,
            )
        );

        // Subscribe Button & Modal settings
        register_setting( 'subscription_modal_settings', 'subs_modal_auto_open', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_auto_open_delay', array( 'sanitize_callback' => 'absint', 'default' => 3 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_floating_btn', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_floating_btn_text', array( 'sanitize_callback' => 'sanitize_text_field', 'default' => 'Subscribe' ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_floating_btn_position', array( 'sanitize_callback' => 'sanitize_text_field', 'default' => 'bottom-right' ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_all_posts', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_all_pages', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_single_posts', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_single_pages', array( 'sanitize_callback' => 'absint', 'default' => 0 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_post_types', array(
            'sanitize_callback' => function( $val ) {
                return is_array( $val ) ? array_map( 'sanitize_key', $val ) : array();
            },
            'default' => array(),
        ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_display_specific_pages', array(
            'sanitize_callback' => function( $val ) {
                return is_array( $val ) ? array_map( 'absint', $val ) : array();
            },
            'default' => array(),
        ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_context_categories', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_context_tags', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );
        register_setting( 'subscription_modal_settings', 'subs_modal_hide_fields_logged_in', array( 'sanitize_callback' => 'absint', 'default' => 1 ) );

        // Pause subscription setting
        register_setting('subs_sys_settings', 'show_pause_button');

        // Register settings
        register_setting('subs_sys_settings', 'subscription_stripe_test_mode');
        register_setting('subs_sys_settings', 'subscription_stripe_test_publishable_key');
        register_setting('subs_sys_settings', 'subscription_stripe_test_secret_key');
        register_setting('subs_sys_settings', 'subscription_stripe_live_publishable_key');
        register_setting('subs_sys_settings', 'subscription_stripe_live_secret_key');
        register_setting('subs_sys_settings', 'subscription_stripe_webhook_secret');
        register_setting('subs_sys_settings', 'show_pause_button');
    }

    /**
     * Validate Stripe API key setting
     * 
     * @param string $key The API key to validate
     * @return string The sanitized API key
     */
    public function validate_stripe_api_key_setting($key) {
        $key = sanitize_text_field($key);
        
        if (!empty($key)) {
            $validation = $this->validate_stripe_api_key($key);
            
            if ($validation !== true) {
                add_settings_error(
                    'stripe_api_key',
                    'invalid_stripe_api_key',
                    $validation,
                    'error'
                );
                
                // Return the old value
                return get_option('stripe_api_key');
            }
        }
        
        return $key;
    }

    /**
     * Add Help & Support submenu to the Subscriptions menu
     */
    public function add_help_support_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Help & Support', 'subscription-system'),
            esc_html__('Help & Support', 'subscription-system'),
            'manage_options',
            'subscription-help',
            array($this, 'render_help_support_page')
        );

        // Only show Developer Mode in non-production environments
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Developer Mode', 'subscription-system'),
            esc_html__('Developer Mode', 'subscription-system'),
            'manage_options',
            'subscription-developer',
            array($this, 'render_developer_mode_page')
        );
    }

    /**
     * Render the Help & Support page content
     */
    public function render_help_support_page() {
        // Include the help & support template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/help-support-display.php';
    }

    /**
     * Render the Developer Mode page content
     */
    public function render_developer_mode_page() {
        // Include the developer mode template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/developer-mode-display.php';
    }

    /**
     * Sync a plan with Stripe
     * 
     * @param int $plan_id The plan ID
     * @return array|WP_Error The result data or WP_Error on failure
     */
    public function sync_plan_with_stripe($plan_id) {
        // Check if Stripe is configured
        $stripe_check = $this->check_stripe_configuration();
        if (is_wp_error($stripe_check)) {
            return $stripe_check;
        }
        
        // Get the plan details
        $plan = $this->subscription_manager->get_plan($plan_id);
        if (!$plan) {
            return new WP_Error('plan_not_found', 'Plan not found.');
        }
        
        // Get the API key based on the selected mode
        $api_key = get_option('subscription_stripe_secret_key');
        
        // Debug log the API key (mask it for security)
        if (!empty($api_key)) {
            $masked_key = substr($api_key, 0, 4) . '...' . substr($api_key, -4);
            error_log('Using Stripe API key: ' . $masked_key);
        } else {
            error_log('Stripe API key is empty!');
            return new WP_Error('missing_api_key', 'Stripe API key is not set. Please configure it in the Payment Settings.');
        }
        
        try {
            // Set the API key
            \Stripe\Stripe::setApiKey($api_key);
            
            // Create a unique ID for the product based on the plan
            $product_id = 'prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            
            // Try to retrieve the product first (in case it already exists)
            try {
                $product = \Stripe\Product::retrieve($product_id);
                
                // Update the existing product
                $product->name = $plan->plan_name;
                $product->description = $plan->description;
                $product->save();
            } catch (\Exception $e) {
                // Product doesn't exist, create a new one
                $product = \Stripe\Product::create([
                    'id' => $product_id,
                    'name' => $plan->plan_name,
                    'description' => $plan->description,
                    'metadata' => [
                        'plan_id' => $plan_id,
                        'category_id' => $plan->category_id
                    ]
                ]);
            }
            
            // Create a unique ID for the price based on the plan
            $price_id = 'price_' . substr(md5('plan_' . $plan_id . '_' . $plan->price), 0, 10);
            
            // Determine the interval and interval count based on duration
            $interval = 'month'; // Default
            $interval_count = 1; // Default
            
            // If billing_cycle exists, use it
            if (isset($plan->billing_cycle)) {
                switch ($plan->billing_cycle) {
                    case 'monthly':
                        $interval = 'month';
                        $interval_count = 1;
                        break;
                    case 'quarterly':
                        $interval = 'month';
                        $interval_count = 3;
                        break;
                    case 'biannually':
                        $interval = 'month';
                        $interval_count = 6;
                        break;
                    case 'annually':
                        $interval = 'year';
                        $interval_count = 1;
                        break;
                }
            } else {
                // Use duration field to determine interval
                $duration = isset($plan->duration) ? intval($plan->duration) : 30;
                
                if ($duration <= 31) {
                    $interval = 'month';
                    $interval_count = 1;
                } else if ($duration <= 93) {
                    $interval = 'month';
                    $interval_count = 3;
                } else if ($duration <= 186) {
                    $interval = 'month';
                    $interval_count = 6;
                } else {
                    $interval = 'year';
                    $interval_count = 1;
                }
            }
            
            // Try to retrieve the price first (in case it already exists)
            try {
                $price = \Stripe\Price::retrieve($price_id);
                
                // If price exists but details have changed, create a new price
                // (Stripe doesn't allow updating prices)
                if ($price->unit_amount != intval($plan->price * 100)) {
                    // Create a new price with updated details
                    $price = \Stripe\Price::create([
                        'product' => $product->id,
                        'unit_amount' => intval($plan->price * 100), // Convert to cents
                        'currency' => strtolower(get_option('subscription_currency', 'usd')),
                        'recurring' => [
                            'interval' => $interval,
                            'interval_count' => $interval_count
                        ],
                        'metadata' => [
                            'plan_id' => $plan_id
                        ]
                    ]);
                    
                    // Update the price ID in the database
                    $this->subscription_manager->update_plan($plan_id, [
                        'stripe_price_id' => $price->id
                    ]);
                }
            } catch (\Exception $e) {
                // Price doesn't exist, create a new one
                $price = \Stripe\Price::create([
                    'product' => $product->id,
                    'unit_amount' => intval($plan->price * 100), // Convert to cents
                    'currency' => strtolower(get_option('subscription_currency', 'usd')),
                    'recurring' => [
                        'interval' => $interval,
                        'interval_count' => $interval_count
                    ],
                    'metadata' => [
                        'plan_id' => $plan_id
                    ]
                ]);
                
                // Update the price ID in the database
                $this->subscription_manager->update_plan($plan_id, [
                    'stripe_price_id' => $price->id
                ]);
            }
            
            // Update the product ID in the database
            $this->subscription_manager->update_plan($plan_id, [
                'stripe_product_id' => $product->id,
                'stripe_price_id' => $price->id
            ]);
            
            error_log('Syncing plan with Stripe: ' . $plan_id);
            error_log('Sync result: ' . print_r($result, true));
            
            return [
                'product_id' => $product->id,
                'price_id' => $price->id,
                'mock_mode' => false,
                'message' => 'Plan successfully synced with Stripe.'
            ];
        } catch (\Exception $e) {
            // If Stripe SDK is not available or there's an error, use mock implementation
            // Generate mock IDs
            $mock_product_id = 'mock_prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            $mock_price_id = 'mock_price_' . substr(md5('plan_' . $plan_id . '_price'), 0, 10);
            
            // Update the plan with mock IDs
            $this->subscription_manager->update_plan($plan_id, [
                'stripe_product_id' => $mock_product_id,
                'stripe_price_id' => $mock_price_id
            ]);
            
            error_log('Syncing plan with Stripe: ' . $plan_id);
            error_log('Sync result: ' . print_r($result, true));
            
            return [
                'product_id' => $mock_product_id,
                'price_id' => $mock_price_id,
                'mock_mode' => true,
                'message' => 'Plan successfully synced with mock Stripe implementation. Error: ' . $e->getMessage(),
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Register AJAX handlers
     */
    public function register_ajax_handlers() {
        add_action('wp_ajax_sync_plan_with_stripe', array($this, 'ajax_sync_plan_with_stripe'));
        add_action('wp_ajax_sync_content_plan_with_stripe', array($this, 'ajax_sync_content_plan_with_stripe'));
        add_action('wp_ajax_test_stripe_connection', array($this, 'ajax_test_stripe_connection'));
        add_action('wp_ajax_install_stripe_sdk', array($this, 'ajax_install_stripe_sdk'));
        add_action('wp_ajax_check_stripe_api_key', array($this, 'ajax_check_stripe_api_key'));
        add_action('wp_ajax_manage_subscription', array($this, 'ajax_manage_subscription'));
        add_action('wp_ajax_download_subscription_log', array($this, 'ajax_download_log'));
        add_action('wp_ajax_get_work_items_by_channel', array($this, 'ajax_get_work_items_by_channel'));
    }

    /**
     * Process form submissions
     */
    public function process_forms() {
        // Check if we're on the right page
        if (!isset($_GET['post_type']) || $_GET['post_type'] !== 'subscription') {
            return;
        }
        
        // Process add plan form
        if (isset($_POST['add_plan_submit']) && isset($_POST['add_plan_nonce'])) {
            // Verify nonce
            if (!wp_verify_nonce($_POST['add_plan_nonce'], 'add_plan_nonce')) {
                wp_die(__('Security check failed', 'subscription-system'));
            }
            
            // Get form data
            $raw_features = isset( $_POST['plan_features_json'] ) ? sanitize_text_field( wp_unslash( $_POST['plan_features_json'] ) ) : '';
            $features_arr = json_decode( $raw_features, true );
            if ( ! is_array( $features_arr ) ) {
                $features_arr = array( 'max_categories' => 0, 'max_tags' => 0 );
            }
            $features_arr['max_categories'] = max( 0, (int) ( $features_arr['max_categories'] ?? 0 ) );
            $features_arr['max_tags']       = max( 0, (int) ( $features_arr['max_tags']       ?? 0 ) );

            $plan_data = array(
                'plan_name'   => isset($_POST['plan_name']) ? sanitize_text_field($_POST['plan_name']) : '',
                'description' => isset($_POST['description']) ? wp_kses_post($_POST['description']) : '',
                'price'       => isset($_POST['price']) ? floatval($_POST['price']) : 0,
                'duration'    => isset($_POST['duration']) ? intval($_POST['duration']) : 30,
                'category_id' => isset($_POST['category_id']) ? intval($_POST['category_id']) : 0,
                'status'      => isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'active',
                'features'    => wp_json_encode( $features_arr ),
            );
            
            // Add the plan
            $result = $this->add_plan($plan_data);
            
            if (is_wp_error($result)) {
                // Store error message
                add_settings_error(
                    'subscription_system',
                    'add_plan_error',
                    $result->get_error_message(),
                    'error'
                );
            } else {
                // Store success message
                add_settings_error(
                    'subscription_system',
                    'add_plan_success',
                    __('Plan added successfully', 'subscription-system'),
                    'success'
                );
                
                // Use wp_safe_redirect instead of wp_redirect
                wp_safe_redirect(admin_url('edit.php?post_type=subscription&page=subscription-plans'));
                exit;
            }
        }
        
        // Process edit plan form
        if (isset($_POST['edit_plan_submit']) && isset($_POST['edit_plan_nonce'])) {
            // Verify nonce
            if (!wp_verify_nonce($_POST['edit_plan_nonce'], 'edit_plan_nonce')) {
                wp_die(__('Security check failed', 'subscription-system'));
            }
            
            // Get form data
            $plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
            
            if ($plan_id <= 0) {
                wp_die(__('Invalid plan ID', 'subscription-system'));
            }
            
            $raw_features_edit = isset( $_POST['plan_features_json'] ) ? sanitize_text_field( wp_unslash( $_POST['plan_features_json'] ) ) : '';
            $features_arr_edit = json_decode( $raw_features_edit, true );
            if ( ! is_array( $features_arr_edit ) ) {
                $features_arr_edit = array( 'max_categories' => 0, 'max_tags' => 0 );
            }
            $features_arr_edit['max_categories'] = max( 0, (int) ( $features_arr_edit['max_categories'] ?? 0 ) );
            $features_arr_edit['max_tags']       = max( 0, (int) ( $features_arr_edit['max_tags']       ?? 0 ) );

            $plan_data = array(
                'plan_name'   => isset($_POST['plan_name']) ? sanitize_text_field($_POST['plan_name']) : '',
                'description' => isset($_POST['description']) ? wp_kses_post($_POST['description']) : '',
                'price'       => isset($_POST['price']) ? floatval($_POST['price']) : 0,
                'duration'    => isset($_POST['duration']) ? intval($_POST['duration']) : 30,
                'category_id' => isset($_POST['category_id']) ? intval($_POST['category_id']) : 0,
                'status'      => isset($_POST['status']) ? sanitize_text_field($_POST['status']) : 'active',
                'features'    => wp_json_encode( $features_arr_edit ),
                'updated_at'  => current_time('mysql'),
            );
            
            // Update the plan
            $result = $this->subscription_manager->update_plan($plan_id, $plan_data);
            
            if (is_wp_error($result)) {
                // Store error message
                add_settings_error(
                    'subscription_system',
                    'edit_plan_error',
                    $result->get_error_message(),
                    'error'
                );
            } else {
                // Store success message
                add_settings_error(
                    'subscription_system',
                    'edit_plan_success',
                    __('Plan updated successfully', 'subscription-system'),
                    'success'
                );
                
                // Use wp_safe_redirect instead of wp_redirect
                wp_safe_redirect(admin_url('edit.php?post_type=subscription&page=subscription-plans'));
                exit;
            }
        }
        
        // Process developer mode forms
        $this->process_developer_mode_forms();
    }

    /**
     * Process developer mode form submissions
     */
    private function process_developer_mode_forms() {
        // Check if we're on the developer mode page
        if (!isset($_GET['page']) || $_GET['page'] !== 'subscription-developer-mode') {
            return;
        }
        
        // ... existing code for table recreation and logging options ...
        
        // Process settings reset
        if (isset($_POST['subscription_reset_settings_nonce']) && 
            wp_verify_nonce($_POST['subscription_reset_settings_nonce'], 'subscription_reset_settings') &&
            isset($_POST['reset_settings'])) {
            
            $reset_count = 0;
            
            // Reset general settings
            if (isset($_POST['reset_general_settings'])) {
                $general_options = [
                    'subscription_currency',
                    'subscription_currency_position',
                    'subscription_default_layout',
                    'enable_subscriptions',
                    'show_pause_button',
                    'show_cancel_button',
                    'default_pricing_layout'
                ];
                
                foreach ($general_options as $option) {
                    delete_option($option);
                }
                
                $reset_count++;
            }
            
            // Reset payment settings
            if (isset($_POST['reset_payment_settings'])) {
                $payment_options = [
                    'enable_stripe',
                    'stripe_mode',
                    'stripe_api_key',
                    'stripe_publishable_key',
                    'stripe_webhook_secret',
                    'subscription_stripe_enabled',
                    'subscription_stripe_test_mode',
                    'subscription_stripe_test_secret_key',
                    'subscription_stripe_test_publishable_key',
                    'subscription_stripe_live_secret_key',
                    'subscription_stripe_live_publishable_key',
                    'subscription_stripe_secret_key'
                ];
                
                foreach ($payment_options as $option) {
                    delete_option($option);
                }
                
                $reset_count++;
            }
            
            // Reset email settings
            if (isset($_POST['reset_email_settings'])) {
                $email_options = [
                    'enable_email_notifications',
                    'admin_email',
                    'subscription_email_from_name',
                    'subscription_email_from_address',
                    'subscription_welcome_email_subject',
                    'subscription_welcome_email_body',
                    'subscription_renewal_email_subject',
                    'subscription_renewal_email_body',
                    'subscription_expiration_email_subject',
                    'subscription_expiration_email_body'
                ];
                
                foreach ($email_options as $option) {
                    delete_option($option);
                }
                
                $reset_count++;
            }
            
            // Reset page settings
            if (isset($_POST['reset_page_settings'])) {
                $page_options = [
                    'login_page',
                    'account_page',
                    'register_page',
                    'thank_you_page',
                    'pricing_plans_page',
                    'edit_profile_page',
                    'forgot_password_page',
                    'contact_page',
                    'subscription_cancel_page',
                    'subscription_reset_password_page'
                ];
                
                foreach ($page_options as $option) {
                    delete_option($option);
                }
                
                $reset_count++;
            }
            
            // Reset all plugin options
            if (isset($_POST['reset_all_options'])) {
                global $wpdb;
                
                // Get all options with the plugin prefix
                $options = $wpdb->get_results(
                    "SELECT option_name FROM {$wpdb->options} 
                    WHERE option_name LIKE 'subscription_%' 
                    OR option_name LIKE 'ss_%'
                    OR option_name IN ('enable_stripe', 'stripe_mode', 'stripe_api_key', 'stripe_publishable_key', 'stripe_webhook_secret')"
                );
                
                foreach ($options as $option) {
                    delete_option($option->option_name);
                }
                
                $reset_count++;
            }
            
            // Reset user metadata
            if (isset($_POST['reset_user_metadata'])) {
                global $wpdb;
                
                // Delete all user meta related to subscriptions
                $wpdb->query(
                    "DELETE FROM {$wpdb->usermeta} 
                    WHERE meta_key LIKE 'subscription_%' 
                    OR meta_key LIKE 'ss_%'"
                );
                
                $reset_count++;
            }
            
            if ($reset_count > 0) {
                add_settings_error(
                    'subscription_messages',
                    'settings_reset',
                    __('Selected settings have been reset successfully.', 'subscription-system'),
                    'updated'
                );
            }
        }
    }

    /**
     * Check and update database schema if needed
     */
    public function check_database_schema() {
        global $wpdb;
        
        $charset_collate = $wpdb->get_charset_collate();
        
        // Check if plans table has stripe_product_id and stripe_price_id columns
        $table_name = $wpdb->prefix . 'subscription_plans';
        $columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name");
        
        $has_stripe_product_id = false;
        $has_stripe_price_id = false;
        
        foreach ($columns as $column) {
            if ($column->Field === 'stripe_product_id') {
                $has_stripe_product_id = true;
            }
            if ($column->Field === 'stripe_price_id') {
                $has_stripe_price_id = true;
            }
        }
        
        // Add stripe_product_id column if it doesn't exist
        if (!$has_stripe_product_id) {
            $wpdb->query("ALTER TABLE $table_name ADD COLUMN stripe_product_id VARCHAR(255) DEFAULT NULL");
        }
        
        // Add stripe_price_id column if it doesn't exist
        if (!$has_stripe_price_id) {
            $wpdb->query("ALTER TABLE $table_name ADD COLUMN stripe_price_id VARCHAR(255) DEFAULT NULL");
        }
        
        // Check if channels table exists
        $table_name = $wpdb->prefix . 'subscription_channels';
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the channels table
            $this->create_channels_table();
        }
        
        // Check if work items table exists
        $table_name = $wpdb->prefix . 'subscription_work_items';
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the work items table
            $this->create_work_items_table();
        }
        
        // Check if work logs table exists
        $table_name = $wpdb->prefix . 'subscription_work_logs';
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the work logs table
            $this->create_work_logs_table();
        }
    }

    /**
     * Register hooks and actions
     */
    public function register_hooks() {
        // Register post types
        
        // Admin menus are now registered via register_admin_menus() in the constructor
        
        // Register settings
        add_action('admin_init', array($this, 'register_settings'));
        
        // Handle AJAX requests
        add_action('wp_ajax_subscription_action', array($this, 'handle_ajax_request'));
        add_action('wp_ajax_nopriv_subscription_action', array($this, 'handle_ajax_request'));
        
        // Add Stripe mode indicator to admin bar
        add_action('admin_bar_menu', array($this, 'add_stripe_mode_indicator'), 100);
    }

    /**
     * Ensure Stripe SDK is loaded
     * 
     * @return bool True if Stripe SDK is loaded, false otherwise
     */
    public function ensure_stripe_sdk_loaded() {
        // Check if Stripe SDK is already loaded
        if (class_exists('\Stripe\Stripe')) {
            return true;
        }
        
        // Try to load from Composer autoloader
        $autoloader_paths = [
            // Main plugin directory
            plugin_dir_path(dirname(__FILE__)) . 'vendor/autoload.php',
            // WordPress root directory
            ABSPATH . 'vendor/autoload.php',
            // One level up from plugin directory (for WordPress installations with Composer)
            dirname(plugin_dir_path(dirname(__FILE__))) . '/vendor/autoload.php',
        ];
        
        foreach ($autoloader_paths as $path) {
            if (file_exists($path)) {
                require_once $path;
                if (class_exists('\Stripe\Stripe')) {
                    return true;
                }
            }
        }
        
        // If still not loaded, try to load from plugin includes directory
        $stripe_path = plugin_dir_path(dirname(__FILE__)) . 'includes/stripe-php/init.php';
        if (file_exists($stripe_path)) {
            require_once $stripe_path;
            if (class_exists('\Stripe\Stripe')) {
                return true;
            }
        }
        
        // If all else fails, use mock implementation
        $this->use_mock_stripe_implementation();
        return false;
    }

    /**
     * Use a mock Stripe implementation when the real SDK can't be loaded
     */
    private function use_mock_stripe_implementation() {
        if (!class_exists('\Stripe\Stripe')) {
            // Define the Stripe namespace and classes in memory
            eval('
            namespace Stripe {
                class Stripe {
                    public static $apiKey;
                    
                    public static function setApiKey($apiKey) {
                        self::$apiKey = $apiKey;
                    }
                }
                
                class ApiResource {
                    public static function create($params = null) {
                        return new static();
                    }
                    
                    public static function update($id, $params = null) {
                        return new static();
                    }
                    
                    public static function retrieve($id = null) {
                        return new static();
                    }
                    
                    public function save() {
                        return $this;
                    }
                }
                
                class Account extends ApiResource {
                    public $id = "acct_mock";
                    public $email = "mock@example.com";
                    
                    public static function retrieve() {
                        return new self();
                    }
                }
                
                class Product extends ApiResource {
                    public $id;
                    public $name;
                    public $description;
                    
                    public function __construct() {
                        $this->id = "mock_prod_" . substr(md5(uniqid()), 0, 10);
                    }
                    
                    public static function create($params = null) {
                        $obj = new self();
                        if (isset($params["name"])) $obj->name = $params["name"];
                        if (isset($params["description"])) $obj->description = $params["description"];
                        if (isset($params["id"])) $obj->id = $params["id"];
                        return $obj;
                    }
                    
                    public static function retrieve($id) {
                        $obj = new self();
                        $obj->id = $id;
                        return $obj;
                    }
                }
                
                class Price extends ApiResource {
                    public $id;
                    public $unit_amount;
                    public $currency;
                    public $product;
                    
                    public function __construct() {
                        $this->id = "mock_price_" . substr(md5(uniqid()), 0, 10);
                    }
                    
                    public static function create($params = null) {
                        $obj = new self();
                        if (isset($params["unit_amount"])) $obj->unit_amount = $params["unit_amount"];
                        if (isset($params["currency"])) $obj->currency = $params["currency"];
                        if (isset($params["product"])) $obj->product = $params["product"];
                        return $obj;
                    }
                    
                    public static function retrieve($id) {
                        $obj = new self();
                        $obj->id = $id;
                        return $obj;
                    }
                }
                
                class Balance extends ApiResource {
                    public static function retrieve() {
                        return new self();
                    }
                }
            }
            
            namespace Stripe\\Exception {
                class ApiErrorException extends \\Exception {}
            }
            ');
        }
    }

    /**
     * Validate Stripe API key
     * 
     * @param string $key The API key to validate
     * @return bool|string True if valid, error message if invalid
     */
    private function validate_stripe_api_key($key) {
        // Check if the key is empty
        if (empty($key)) {
            return 'API key cannot be empty.';
        }
        
        // Check if it's a secret key (should start with sk_)
        if (strpos($key, 'sk_') !== 0) {
            return 'Invalid API key format. Secret keys should start with "sk_test_" or "sk_live_".';
        }
        
        // Check minimum length (typical Stripe keys are quite long)
        if (strlen($key) < 20) {
            return 'API key is too short. Stripe secret keys are typically much longer.';
        }
        
        return true;
    }

    /**
     * Check if Stripe is properly configured
     */
    private function check_stripe_configuration() {
        // Check if Stripe is enabled
        if (get_option('enable_stripe') != 1) {
            return new WP_Error('stripe_disabled', 'Stripe is not enabled. Please enable it in the Payment Settings.');
        }
        
        // Get the selected mode
        $mode = get_option('stripe_mode', 'test');
        
        // Check if API key is set
        $api_key = get_option('stripe_api_key');
        if (empty($api_key)) {
            return new WP_Error('missing_api_key', 'Stripe API key is not set. Please configure it in the Payment Settings.');
        }
        
        $key_validation = $this->validate_stripe_api_key($api_key);
        
        if ($key_validation !== true) {
            return new WP_Error('invalid_api_key', $key_validation);
        }
        
        // Check if the API key matches the selected mode
        $is_test_key = (strpos($api_key, 'sk_test_') === 0);
        if (($mode === 'test' && !$is_test_key) || ($mode === 'live' && $is_test_key)) {
            return new WP_Error(
                'mode_key_mismatch',
                sprintf(
                    'Your API key does not match the selected mode. You are in %s mode but using a %s key. Please either change your mode or update your API key.',
                    strtoupper($mode),
                    $is_test_key ? 'TEST' : 'LIVE'
                )
            );
        }
        
        // Try to load Stripe SDK
        $sdk_loaded = $this->ensure_stripe_sdk_loaded();
        
        // If SDK couldn't be loaded, use mock implementation
        if (!$sdk_loaded || !class_exists('\Stripe\Stripe')) {
            $this->use_mock_stripe_implementation();
            // Return true with mock implementation instead of error
            return true;
        }
        
        // Test the API key by making a simple API call
        try {
            \Stripe\Stripe::setApiKey($api_key);
            \Stripe\Balance::retrieve();
            return true;
        } catch (\Exception $e) {
            // If the API key is invalid, provide a helpful error message
            $error_message = $e->getMessage();
            
            if (strpos($error_message, 'Invalid API Key') !== false) {
                return new WP_Error(
                    'invalid_api_key', 
                    'Invalid Stripe API Key. Please check your API key in the Payment Settings. ' . 
                    'Make sure you are using the correct key (test or live) and that it has not expired.'
                );
            } else if (strpos($error_message, 'publishable API key') !== false) {
                return new WP_Error(
                    'publishable_key_used', 
                    'You are using a publishable API key (pk_) instead of a secret API key (sk_). ' . 
                    'Please update your API key in the Payment Settings to use a secret key that starts with "sk_test_" or "sk_live_".'
                );
            }
            
            // Use mock implementation if API call fails
            $this->use_mock_stripe_implementation();
            return true;
        }
    }

    /**
     * AJAX handler for testing Stripe connection
     */
    public function ajax_test_stripe_connection() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'test_stripe_connection')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
            return;
        }
        
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'));
            return;
        }
        
        // Check if Stripe is enabled
        if (get_option('subscription_stripe_enabled', 0) != 1) {
            wp_send_json_error(array('message' => 'Stripe is not enabled. Please enable it first.'));
            return;
        }
        
        // Get the API key based on test mode
        $test_mode = get_option('subscription_stripe_test_mode', 1);
        
        if ($test_mode) {
            $api_key = get_option('subscription_stripe_test_secret_key', '');
        } else {
            $api_key = get_option('subscription_stripe_live_secret_key', '');
        }
        
        // Fallback to the general key if specific one is not set
        if (empty($api_key)) {
            $api_key = get_option('subscription_stripe_secret_key', '');
        }
        
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API key is not set. Please enter a valid Stripe API key.'));
            return;
        }
        
        // Try to load Stripe SDK
        if (!class_exists('\Stripe\Stripe') && !$this->ensure_stripe_sdk_loaded()) {
            wp_send_json_error(array('message' => 'Stripe SDK could not be loaded. Using mock implementation.'));
            return;
        }
        
        // Test the connection
        try {
            \Stripe\Stripe::setApiKey($api_key);
            $account = \Stripe\Account::retrieve();
            
            wp_send_json_success(array(
                'message' => sprintf(
                    'Connection successful! Connected to Stripe account: %s',
                    $account->email ?? $account->id
                )
            ));
        } catch (\Exception $e) {
            wp_send_json_error(array(
                'message' => 'Connection failed: ' . $e->getMessage(),
                'error' => $e->getMessage()
            ));
        }
    }

    /**
     * AJAX handler for manually installing Stripe SDK
     */
    public function ajax_install_stripe_sdk() {
        // Check nonce
        check_ajax_referer('subs_sys_admin', 'security');
        
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'));
            return;
        }
        
        // Try to install the SDK
        $result = $this->manual_install_stripe_sdk();
        
        if (is_wp_error($result)) {
            wp_send_json_error(array(
                'message' => 'Failed to install Stripe SDK: ' . $result->get_error_message(),
                'code' => $result->get_error_code()
            ));
            return;
        }
        
        // Check if Stripe SDK is now available
        if (class_exists('\Stripe\Stripe')) {
            wp_send_json_success(array('message' => 'Stripe SDK installed successfully!'));
        } else {
            wp_send_json_error(array('message' => 'Stripe SDK was downloaded but could not be loaded. Please check file permissions.'));
        }
    }

    /**
     * Manually install Stripe SDK with elevated permissions
     */
    private function manual_install_stripe_sdk() {
        // Define paths
        $includes_dir = plugin_dir_path(dirname(__FILE__)) . 'includes';
        $stripe_dir = $includes_dir . '/stripe-php';
        $zip_file = $includes_dir . '/stripe-php.zip';
        
        // Create includes directory if it doesn't exist
        if (!file_exists($includes_dir)) {
            if (!wp_mkdir_p($includes_dir)) {
                return new WP_Error('directory_creation_failed', 'Could not create includes directory. Please check file permissions.');
            }
        }
        
        // Download the Stripe SDK
        $download_url = 'https://github.com/stripe/stripe-php/archive/refs/tags/v10.13.0.zip';
        $download_result = wp_remote_get($download_url, array(
            'timeout' => 60,
            'sslverify' => false
        ));
        
        if (is_wp_error($download_result)) {
            return new WP_Error('download_failed', 'Failed to download Stripe SDK: ' . $download_result->get_error_message());
        }
        
        if (wp_remote_retrieve_response_code($download_result) !== 200) {
            return new WP_Error('download_failed', 'Failed to download Stripe SDK: Invalid response code');
        }
        
        // Save the ZIP file
        $zip_content = wp_remote_retrieve_body($download_result);
        
        // Initialize WordPress filesystem
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }
        
        if (!$wp_filesystem->put_contents($zip_file, $zip_content)) {
            return new WP_Error('file_write_failed', 'Failed to save Stripe SDK ZIP file. Please check file permissions.');
        }
        
        // Extract the ZIP file
        $unzipped = unzip_file($zip_file, $includes_dir);
        
        // Remove the ZIP file
        @unlink($zip_file);
        
        if (is_wp_error($unzipped)) {
            return new WP_Error('unzip_failed', 'Failed to extract Stripe SDK: ' . $unzipped->get_error_message());
        }
        
        // Rename the directory
        $extracted_dir = $includes_dir . '/stripe-php-10.13.0';
        if (file_exists($extracted_dir)) {
            // Remove existing stripe-php directory if it exists
            if (file_exists($stripe_dir)) {
                $this->recursive_rmdir($stripe_dir);
            }
            
            // Rename the directory
            if (!rename($extracted_dir, $stripe_dir)) {
                return new WP_Error('rename_failed', 'Failed to rename Stripe SDK directory. Please check file permissions.');
            }
        } else {
            return new WP_Error('extraction_failed', 'Stripe SDK was downloaded but extraction directory not found.');
        }
        
        // Try to include the SDK
        if (file_exists($stripe_dir . '/init.php')) {
            require_once $stripe_dir . '/init.php';
            return true;
        }
        
        return new WP_Error('load_failed', 'Stripe SDK was installed but could not be loaded.');
    }

    /**
     * Load Stripe SDK from CDN
     */
    private function load_stripe_sdk_from_cdn() {
        if (!class_exists('\Stripe\Stripe')) {
            // Define the URL to the Stripe SDK
            $stripe_sdk_url = 'https://cdn.jsdelivr.net/gh/stripe/stripe-php@v10.13.0/init.php';
            
            // Create a temporary file
            $temp_file = wp_tempnam('stripe-sdk');
            
            // Download the file
            $response = wp_remote_get($stripe_sdk_url);
            
            if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
                // Get the content
                $content = wp_remote_retrieve_body($response);
                
                // Initialize WordPress filesystem
                global $wp_filesystem;
                if (empty($wp_filesystem)) {
                    require_once ABSPATH . 'wp-admin/includes/file.php';
                    WP_Filesystem();
                }
                
                // Save to the temporary file
                if ($wp_filesystem->put_contents($temp_file, $content)) {
                    // Include the file
                    require_once $temp_file;
                    
                    // Register a shutdown function to delete the temporary file
                    register_shutdown_function(function() use ($temp_file) {
                        @unlink($temp_file);
                    });
                    
                    return true;
                }
            }
        }
        
        return false;
    }

    /**
     * Get the appropriate Stripe API key based on the selected mode
     * 
     * @param string $type The type of key to get ('secret' or 'publishable')
     * @return string The API key
     */
    public function get_stripe_api_key($type = 'secret') {
        $mode = get_option('stripe_mode', 'test');
        
        if ($type === 'secret') {
            return get_option('stripe_api_key', '');
        } else {
            return get_option('stripe_publishable_key', '');
        }
    }

    /**
     * Add Stripe mode indicator to admin bar
     */
    public function add_stripe_mode_indicator($admin_bar) {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        if (get_option('enable_stripe') != 1) {
            return;
        }
        
        $mode = get_option('stripe_mode', 'test');
        $mode_text = strtoupper($mode);
        $mode_class = $mode . '-mode';
        
        $admin_bar->add_node(array(
            'id'    => 'stripe-mode',
            'title' => '<span class="ab-icon"></span><span class="ab-label">Stripe: <span class="stripe-mode-indicator ' . $mode_class . '">' . $mode_text . '</span></span>',
            'href'  => admin_url('edit.php?post_type=subscription&page=subscription-settings&tab=payment'),
            'meta'  => array(
                'title' => 'Stripe is in ' . $mode_text . ' mode. Click to change.',
            ),
        ));
    }

    /**
     * Add a new subscription plan
     * 
     * @param array $plan_data The plan data
     * @return int|WP_Error The plan ID or WP_Error on failure
     */
    public function add_plan($plan_data) {
        global $wpdb;
        
        // Validate required fields
        $required_fields = array('plan_name', 'price');
        
        foreach ($required_fields as $field) {
            if (!isset($plan_data[$field]) || empty($plan_data[$field])) {
                return new WP_Error(
                    'missing_field',
                    sprintf(__('Missing required field: %s', 'subscription-system'), $field)
                );
            }
        }
        
        // Prepare the data
        $data = array(
            'plan_name'   => sanitize_text_field($plan_data['plan_name']),
            'description' => isset($plan_data['description']) ? wp_kses_post($plan_data['description']) : '',
            'price'       => floatval($plan_data['price']),
            'duration'    => isset($plan_data['duration']) ? intval($plan_data['duration']) : 30,
            'category_id' => isset($plan_data['category_id']) ? intval($plan_data['category_id']) : 0,
            'status'      => isset($plan_data['status']) ? sanitize_text_field($plan_data['status']) : 'active',
            'features'    => isset($plan_data['features']) ? $plan_data['features'] : wp_json_encode( array( 'max_categories' => 0, 'max_tags' => 0 ) ),
            'created_at'  => current_time('mysql'),
            'updated_at'  => current_time('mysql'),
        );
        
        // Insert the plan
        $table_name = $wpdb->prefix . 'subscription_plans';
        
        $result = $wpdb->insert(
            $table_name,
            $data,
            array('%s', '%s', '%f', '%d', '%d', '%s', '%s', '%s', '%s')
        );
        
        if ($result === false) {
            return new WP_Error('db_insert_error', 'Failed to add plan: ' . $wpdb->last_error);
        }
        
        return $wpdb->insert_id;
    }

    /**
     * AJAX handler for syncing a plan with Stripe
     */
    public function ajax_sync_plan_with_stripe() {
        // Check nonce
        if (!isset($_POST['security']) && !isset($_POST['nonce'])) {
            error_log('Stripe sync: Security check failed - no nonce provided');
            wp_send_json_error(array(
                'message' => 'Security check failed.',
                'code' => 'invalid_nonce',
                'mock_mode' => true
            ));
            return;
        }
        
        // Check either security or nonce parameter
        $nonce_verified = false;
        if (isset($_POST['security']) && wp_verify_nonce($_POST['security'], 'test_stripe_connection')) {
            $nonce_verified = true;
        } elseif (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'sync_plan_with_stripe')) {
            $nonce_verified = true;
        }
        
        if (!$nonce_verified) {
            error_log('Stripe sync: Security check failed - invalid nonce');
            wp_send_json_error(array(
                'message' => 'Security check failed.',
                'code' => 'invalid_nonce',
                'mock_mode' => true
            ));
            return;
        }
        
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            error_log('Stripe sync: Permission check failed');
            wp_send_json_error(array(
                'message' => 'You do not have permission to perform this action.',
                'code' => 'insufficient_permissions',
                'mock_mode' => true
            ));
            return;
        }
        
        // Get the plan ID
        $plan_id = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
        
        if ($plan_id <= 0) {
            error_log('Stripe sync: Invalid plan ID');
            wp_send_json_error(array(
                'message' => 'Invalid plan ID.',
                'code' => 'invalid_plan_id',
                'mock_mode' => true
            ));
            return;
        }
        
        // Check if Stripe is enabled
        $stripe_enabled = get_option('subscription_stripe_enabled', 0);
        error_log('Stripe sync: Stripe enabled check - ' . ($stripe_enabled ? 'YES' : 'NO'));
        
        if ($stripe_enabled != 1) {
            error_log('Stripe sync: Stripe is not enabled');
            // Instead of returning an error, we'll use mock mode
            $this->use_mock_stripe_implementation();
            
            // Get the 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('Stripe sync: Plan not found');
                wp_send_json_error(array(
                    'message' => 'Plan not found.',
                    'code' => 'plan_not_found',
                    'mock_mode' => true
                ));
                return;
            }
            
            // Generate mock IDs
            $mock_product_id = 'mock_prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            $mock_price_id = 'mock_price_' . substr(md5('plan_' . $plan_id . '_price'), 0, 10);
            
            // Update the plan with mock IDs
            $wpdb->update(
                $table_name,
                array(
                    'stripe_product_id' => $mock_product_id,
                    'stripe_price_id' => $mock_price_id
                ),
                array('id' => $plan_id),
                array('%s', '%s'),
                array('%d')
            );
            
            error_log('Stripe sync: Using mock mode - Product ID: ' . $mock_product_id . ', Price ID: ' . $mock_price_id);
            
            wp_send_json_success(array(
                'product_id' => $mock_product_id,
                'price_id' => $mock_price_id,
                'mock_mode' => true,
                'message' => 'Plan synced with mock Stripe implementation. Enable Stripe in Payment Settings for real integration.'
            ));
            return;
        }
        
        // Get the API key based on test mode
        $test_mode = get_option('subscription_stripe_test_mode', 1);
        error_log('Stripe sync: Test mode - ' . ($test_mode ? 'YES' : 'NO'));
        
        if ($test_mode) {
            $api_key = get_option('subscription_stripe_test_secret_key', '');
            error_log('Stripe sync: Using test mode API key');
        } else {
            $api_key = get_option('subscription_stripe_live_secret_key', '');
            error_log('Stripe sync: Using live mode API key');
        }
        
        // Fallback to the general key if specific one is not set
        if (empty($api_key)) {
            $api_key = get_option('subscription_stripe_secret_key', '');
            error_log('Stripe sync: Falling back to general API key');
        }
        
        if (empty($api_key)) {
            error_log('Stripe sync: API key is not set');
            wp_send_json_error(array(
                'message' => 'API key is not set. Please enter a valid Stripe API key in Payment Settings.',
                'code' => 'missing_api_key',
                'mock_mode' => true
            ));
            return;
        }
        
        // Mask the API key for logging
        $masked_key = substr($api_key, 0, 4) . '...' . substr($api_key, -4);
        error_log('Stripe sync: Using API key: ' . $masked_key);
        
        // Try to load Stripe SDK
        if (!class_exists('\Stripe\Stripe')) {
            error_log('Stripe sync: Stripe class not found, trying to load SDK');
            $sdk_loaded = $this->ensure_stripe_sdk_loaded();
            error_log('Stripe sync: SDK loaded? ' . ($sdk_loaded ? 'YES' : 'NO'));
        } else {
            error_log('Stripe sync: Stripe class already loaded');
            $sdk_loaded = true;
        }
        
        if (!$sdk_loaded) {
            error_log('Stripe sync: Could not load Stripe SDK, using mock implementation');
            // Use mock implementation if SDK can't be loaded
            $this->use_mock_stripe_implementation();
            
            // Get the 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(array(
                    'message' => 'Plan not found.',
                    'code' => 'plan_not_found',
                    'mock_mode' => true
                ));
                return;
            }
            
            // Generate mock IDs
            $mock_product_id = 'mock_prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            $mock_price_id = 'mock_price_' . substr(md5('plan_' . $plan_id . '_price'), 0, 10);
            
            // Update the plan with mock IDs
            $wpdb->update(
                $table_name,
                array(
                    'stripe_product_id' => $mock_product_id,
                    'stripe_price_id' => $mock_price_id
                ),
                array('id' => $plan_id),
                array('%s', '%s'),
                array('%d')
            );
            
            wp_send_json_success(array(
                'product_id' => $mock_product_id,
                'price_id' => $mock_price_id,
                'mock_mode' => true,
                'message' => 'Plan synced with mock Stripe implementation. Stripe SDK could not be loaded.'
            ));
            return;
        }
        
        // Get the 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('Stripe sync: Plan not found in database');
            wp_send_json_error(array(
                'message' => 'Plan not found.',
                'code' => 'plan_not_found',
                'mock_mode' => true
            ));
            return;
        }
        
        error_log('Stripe sync: Found plan - ID: ' . $plan->id . ', Name: ' . $plan->plan_name);
        
        try {
            // Set the API key
            \Stripe\Stripe::setApiKey($api_key);
            error_log('Stripe sync: Set API key');
            
            // Create a unique ID for the product based on the plan
            $product_id = 'prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            error_log('Stripe sync: Generated product ID: ' . $product_id);
            
            // Try to retrieve the product first (in case it already exists)
            try {
                error_log('Stripe sync: Attempting to retrieve existing product');
                $product = \Stripe\Product::retrieve($product_id);
                error_log('Stripe sync: Product exists, updating');
                
                // Update the existing product
                $product->name = $plan->plan_name;
                $product->description = $plan->description;
                $product->save();
                error_log('Stripe sync: Product updated');
            } catch (\Exception $e) {
                error_log('Stripe sync: Product does not exist, creating new one. Error: ' . $e->getMessage());
                // Product doesn't exist, create a new one
                $product = \Stripe\Product::create([
                    'id' => $product_id,
                    'name' => $plan->plan_name,
                    'description' => $plan->description,
                    'metadata' => [
                        'plan_id' => $plan_id,
                        'category_id' => $plan->category_id
                    ]
                ]);
                error_log('Stripe sync: Product created - ID: ' . $product->id);
            }
            
            // Create a unique ID for the price based on the plan
            $price_id = 'price_' . substr(md5('plan_' . $plan_id . '_' . $plan->price), 0, 10);
            error_log('Stripe sync: Generated price ID: ' . $price_id);
            
            // Determine the interval and interval count based on duration
            $interval = 'month'; // Default
            $interval_count = 1; // Default
            
            // Use duration field to determine interval
            $duration = isset($plan->duration) ? intval($plan->duration) : 30;
            
            if ($duration <= 31) {
                $interval = 'month';
                $interval_count = 1;
            } else if ($duration <= 93) {
                $interval = 'month';
                $interval_count = 3;
            } else if ($duration <= 186) {
                $interval = 'month';
                $interval_count = 6;
            } else {
                $interval = 'year';
                $interval_count = 1;
            }
            
            error_log('Stripe sync: Using interval: ' . $interval . ', interval_count: ' . $interval_count);
            
            // Try to retrieve the price first (in case it already exists)
            try {
                error_log('Stripe sync: Attempting to retrieve existing price');
                $price = \Stripe\Price::retrieve($price_id);
                error_log('Stripe sync: Price exists - ID: ' . $price->id);
            } catch (\Exception $e) {
                error_log('Stripe sync: Price does not exist, creating new one. Error: ' . $e->getMessage());
                // Price doesn't exist, create a new one
                $price = \Stripe\Price::create([
                    'product' => $product->id,
                    'unit_amount' => intval($plan->price * 100), // Convert to cents
                    'currency' => strtolower(get_option('subscription_currency', 'usd')),
                    'recurring' => [
                        'interval' => $interval,
                        'interval_count' => $interval_count
                    ],
                    'metadata' => [
                        'plan_id' => $plan_id
                    ]
                ]);
                error_log('Stripe sync: Price created - ID: ' . $price->id);
            }
            
            // Update the product ID in the database
            $result = $wpdb->update(
                $table_name,
                array(
                    'stripe_product_id' => $product->id,
                    'stripe_price_id' => $price->id
                ),
                array('id' => $plan_id),
                array('%s', '%s'),
                array('%d')
            );
            
            error_log('Stripe sync: Database updated - Result: ' . ($result ? 'SUCCESS' : 'FAILED'));
            
            wp_send_json_success(array(
                'product_id' => $product->id,
                'price_id' => $price->id,
                'mock_mode' => false,
                'message' => 'Plan successfully synced with Stripe.'
            ));
        } catch (\Exception $e) {
            error_log('Stripe sync: Exception occurred: ' . $e->getMessage());
            // If there's an error, use mock implementation
            $mock_product_id = 'mock_prod_' . substr(md5('plan_' . $plan_id), 0, 10);
            $mock_price_id = 'mock_price_' . substr(md5('plan_' . $plan_id . '_price'), 0, 10);
            
            // Update the plan with mock IDs
            $wpdb->update(
                $table_name,
                array(
                    'stripe_product_id' => $mock_product_id,
                    'stripe_price_id' => $mock_price_id
                ),
                array('id' => $plan_id),
                array('%s', '%s'),
                array('%d')
            );
            
            error_log('Stripe sync: Falling back to mock implementation - Product ID: ' . $mock_product_id . ', Price ID: ' . $mock_price_id);
            
            wp_send_json_success(array(
                'product_id' => $mock_product_id,
                'price_id' => $mock_price_id,
                'mock_mode' => true,
                'message' => 'Plan synced with mock Stripe implementation. Error: ' . $e->getMessage(),
                'error' => $e->getMessage()
            ));
        }
    }

    /**
     * AJAX handler: sync a content plan with Stripe.
     * Mirrors ajax_sync_plan_with_stripe but operates on subscription_content_plans.
     */
    public function ajax_sync_content_plan_with_stripe() {
        // Nonce check.
        $nonce_ok = ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'sync_content_plan_with_stripe' ) );
        if ( ! $nonce_ok ) {
            wp_send_json_error( array( 'message' => 'Security check failed.', 'mock_mode' => true ) );
            return;
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'Insufficient permissions.', 'mock_mode' => true ) );
            return;
        }

        $plan_id = isset( $_POST['plan_id'] ) ? absint( $_POST['plan_id'] ) : 0;
        if ( ! $plan_id ) {
            wp_send_json_error( array( 'message' => 'Invalid plan ID.', 'mock_mode' => true ) );
            return;
        }

        global $wpdb;
        $table = $wpdb->prefix . 'subscription_content_plans';
        $plan  = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", $plan_id ) );

        if ( ! $plan ) {
            wp_send_json_error( array( 'message' => 'Content plan not found.', 'mock_mode' => true ) );
            return;
        }

        // Helper: save IDs back to DB and return success.
        $save_and_respond = function( $product_id, $price_id, $mock_mode, $message, $extra = array() ) use ( $wpdb, $table, $plan_id ) {
            $wpdb->update(
                $table,
                array( 'stripe_product_id' => $product_id, 'stripe_price_id' => $price_id ),
                array( 'id' => $plan_id ),
                array( '%s', '%s' ),
                array( '%d' )
            );
            wp_send_json_success( array_merge( array(
                'product_id' => $product_id,
                'price_id'   => $price_id,
                'mock_mode'  => $mock_mode,
                'message'    => $message,
            ), $extra ) );
        };

        // Determine billing interval from duration.
        $duration       = (int) ( $plan->duration ?? 30 );
        $interval       = 'month';
        $interval_count = 1;
        if ( $duration <= 31 )       { $interval = 'month'; $interval_count = 1; }
        elseif ( $duration <= 93 )   { $interval = 'month'; $interval_count = 3; }
        elseif ( $duration <= 186 )  { $interval = 'month'; $interval_count = 6; }
        else                         { $interval = 'year';  $interval_count = 1; }

        // Check Stripe is enabled.
        $stripe_enabled = get_option( 'subscription_stripe_enabled', 0 );

        if ( ! $stripe_enabled ) {
            $mock_prod  = 'mock_prod_'  . substr( md5( 'cpln_' . $plan_id ), 0, 10 );
            $mock_price = 'mock_price_' . substr( md5( 'cpln_' . $plan_id . '_price' ), 0, 10 );
            $save_and_respond( $mock_prod, $mock_price, true, 'Content plan synced with mock Stripe. Enable Stripe in Payment Settings for real integration.' );
            return;
        }

        // Resolve API key.
        $test_mode = get_option( 'subscription_stripe_test_mode', 1 );
        $api_key   = $test_mode
            ? get_option( 'subscription_stripe_test_secret_key', '' )
            : get_option( 'subscription_stripe_live_secret_key', '' );
        if ( empty( $api_key ) ) {
            $api_key = get_option( 'subscription_stripe_secret_key', '' );
        }

        if ( empty( $api_key ) ) {
            wp_send_json_error( array( 'message' => 'Stripe API key is not set. Please configure it in Payment Settings.', 'mock_mode' => true ) );
            return;
        }

        // Load Stripe SDK.
        if ( ! class_exists( '\Stripe\Stripe' ) ) {
            $this->ensure_stripe_sdk_loaded();
        }

        if ( ! class_exists( '\Stripe\Stripe' ) ) {
            $mock_prod  = 'mock_prod_'  . substr( md5( 'cpln_' . $plan_id ), 0, 10 );
            $mock_price = 'mock_price_' . substr( md5( 'cpln_' . $plan_id . '_price' ), 0, 10 );
            $save_and_respond( $mock_prod, $mock_price, true, 'Content plan synced with mock Stripe. SDK could not be loaded.' );
            return;
        }

        try {
            \Stripe\Stripe::setApiKey( $api_key );

            $product_id = 'prod_' . substr( md5( 'cpln_' . $plan_id ), 0, 10 );

            // Create or update the Stripe product.
            try {
                $product       = \Stripe\Product::retrieve( $product_id );
                $product->name = $plan->plan_name;
                if ( ! empty( $plan->description ) ) {
                    $product->description = wp_strip_all_tags( $plan->description );
                }
                $product->save();
            } catch ( \Exception $e ) {
                $product = \Stripe\Product::create( array(
                    'id'          => $product_id,
                    'name'        => $plan->plan_name,
                    'description' => wp_strip_all_tags( $plan->description ?? '' ),
                    'metadata'    => array(
                        'content_plan_id' => $plan_id,
                        'content_type'    => $plan->content_type,
                    ),
                ) );
            }

            // Free plans: no Stripe price needed.
            if ( (float) $plan->price <= 0 ) {
                $save_and_respond( $product->id, 'free', false, 'Content plan (free) synced with Stripe as a product.' );
                return;
            }

            $price_id = 'price_' . substr( md5( 'cpln_' . $plan_id . '_' . $plan->price ), 0, 10 );

            // Create or reuse the Stripe price.
            try {
                $price = \Stripe\Price::retrieve( $price_id );
                // If amount changed, create a new price.
                if ( $price->unit_amount !== (int) ( $plan->price * 100 ) ) {
                    $price = \Stripe\Price::create( array(
                        'product'   => $product->id,
                        'unit_amount' => (int) ( $plan->price * 100 ),
                        'currency'  => strtolower( get_option( 'subscription_currency', 'usd' ) ),
                        'recurring' => array( 'interval' => $interval, 'interval_count' => $interval_count ),
                        'metadata'  => array( 'content_plan_id' => $plan_id ),
                    ) );
                }
            } catch ( \Exception $e ) {
                $price = \Stripe\Price::create( array(
                    'product'   => $product->id,
                    'unit_amount' => (int) ( $plan->price * 100 ),
                    'currency'  => strtolower( get_option( 'subscription_currency', 'usd' ) ),
                    'recurring' => array( 'interval' => $interval, 'interval_count' => $interval_count ),
                    'metadata'  => array( 'content_plan_id' => $plan_id ),
                ) );
            }

            $save_and_respond( $product->id, $price->id, false, 'Content plan successfully synced with Stripe.' );

        } catch ( \Exception $e ) {
            $mock_prod  = 'mock_prod_'  . substr( md5( 'cpln_' . $plan_id ), 0, 10 );
            $mock_price = 'mock_price_' . substr( md5( 'cpln_' . $plan_id . '_price' ), 0, 10 );
            $save_and_respond( $mock_prod, $mock_price, true,
                'Content plan synced with mock Stripe. Error: ' . $e->getMessage(),
                array( 'error' => $e->getMessage() )
            );
        }
    }

    /**
     * AJAX handler for checking the Stripe API key
     */
    public function ajax_check_stripe_api_key() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'test_stripe_connection')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
            return;
        }
        
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'));
            return;
        }
        
        // Get the API key based on test mode
        $test_mode = get_option('subscription_stripe_test_mode', 1);
        
        if ($test_mode) {
            $api_key = get_option('subscription_stripe_test_secret_key', '');
            $mode = 'test';
        } else {
            $api_key = get_option('subscription_stripe_live_secret_key', '');
            $mode = 'live';
        }
        
        // Fallback to the general key if specific one is not set
        if (empty($api_key)) {
            $api_key = get_option('subscription_stripe_secret_key', '');
        }
        
        if (empty($api_key)) {
            wp_send_json_error(array('message' => 'API key is not set in the database.'));
            return;
        }
        
        // Check if the key format is correct
        $prefix = $test_mode ? 'sk_test_' : 'sk_live_';
        if (strpos($api_key, $prefix) !== 0) {
            wp_send_json_error(array(
                'message' => sprintf(
                    'API key format is incorrect. %s mode keys should start with "%s"',
                    ucfirst($mode),
                    $prefix
                )
            ));
            return;
        }
        
        $masked_key = substr($api_key, 0, 8) . '...' . substr($api_key, -4);
        wp_send_json_success(array(
            'message' => sprintf(
                'API key is correctly set in the database (%s mode): %s',
                $mode,
                $masked_key
            )
        ));
    }

    /**
     * Add Subscribers submenu to the Subscriptions menu
     */
    public function add_subscribers_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Subscribers', 'subscription-system'),
            esc_html__('Subscribers', 'subscription-system'),
            'manage_options',
            'subscription-subscribers',
            array($this, 'render_subscribers_page')
        );
    }

    /**
     * Render the Subscribers page content
     */
    public function render_subscribers_page() {
        // Get all users with subscription information
        $subscribers = $this->get_all_subscribers();
        
        // Include the subscribers template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/subscribers-display.php';
    }

    /**
     * Get all subscribers with their subscription details
     * 
     * @return array Array of subscribers with their subscription details
     */
    private function get_all_subscribers() {
        global $wpdb;
        
        // Get all users who have subscriptions
        $query = "
            SELECT u.ID, u.user_login, u.user_email, u.display_name, u.user_registered,
                   s.id as subscription_id, s.status, s.plan_id, s.start_date, s.end_date, s.amount,
                   p.plan_name, p.duration
            FROM {$wpdb->users} u
            LEFT JOIN {$wpdb->prefix}subscriptions s ON u.ID = s.user_id
            LEFT JOIN {$wpdb->prefix}subscription_plans p ON s.plan_id = p.id
            ORDER BY u.ID DESC
        ";
        
        $results = $wpdb->get_results($query);
        
        // Organize results by user
        $subscribers = array();
        foreach ($results as $row) {
            $user_id = $row->ID;
            
            if (!isset($subscribers[$user_id])) {
                $subscribers[$user_id] = array(
                    'user_id' => $user_id,
                    'username' => $row->user_login,
                    'email' => $row->user_email,
                    'display_name' => $row->display_name,
                    'registered_date' => $row->user_registered,
                    'subscriptions' => array()
                );
            }
            
            // Add subscription details if they exist
            if (!empty($row->subscription_id)) {
                $subscribers[$user_id]['subscriptions'][] = array(
                    'id' => $row->subscription_id,
                    'status' => $row->status,
                    'plan_id' => $row->plan_id,
                    'plan_name' => $row->plan_name,
                    'start_date' => $row->start_date,
                    'end_date' => $row->end_date,
                    'amount' => $row->amount,
                    'duration' => $row->duration
                );
            }
        }
        
        return $subscribers;
    }

    /**
     * Get all subscription plans
     */
    public function get_all_plans() {
        global $wpdb;
        $plans_table = $wpdb->prefix . 'subscription_plans';
        
        // Check if status column exists
        $columns = $wpdb->get_col("DESCRIBE {$plans_table}", 0);
        
        if (in_array('status', $columns)) {
            return $wpdb->get_results("SELECT * FROM {$plans_table} WHERE status = 'active' ORDER BY price ASC");
        } else {
            return $wpdb->get_results("SELECT * FROM {$plans_table} ORDER BY price ASC");
        }
    }

    /**
     * Get all plan categories
     */
    public function get_all_categories() {
        global $wpdb;
        $categories_table = $wpdb->prefix . 'subscription_plan_categories';
        
        // Check if name column exists
        $columns = $wpdb->get_col("DESCRIBE {$categories_table}", 0);
        
        if (in_array('name', $columns)) {
            return $wpdb->get_results("SELECT * FROM {$categories_table} ORDER BY name ASC");
        } else if (in_array('category_name', $columns)) {
            return $wpdb->get_results("SELECT * FROM {$categories_table} ORDER BY category_name ASC");
        } else {
            return $wpdb->get_results("SELECT * FROM {$categories_table} ORDER BY id ASC");
        }
    }

    /**
     * Check if a plan is connected to Stripe
     * 
     * @param int $plan_id The plan ID
     * @return bool True if connected, false otherwise
     */
    public function is_plan_connected_to_stripe($plan_id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_plans';
        
        $plan = $wpdb->get_row($wpdb->prepare(
            "SELECT stripe_product_id, stripe_price_id FROM $table_name WHERE id = %d",
            $plan_id
        ));
        
        if (!$plan) {
            return false;
        }
        
        // Check if both product ID and price ID are set and not mock IDs
        return !empty($plan->stripe_product_id) && 
               !empty($plan->stripe_price_id) && 
               strpos($plan->stripe_product_id, 'mock_') !== 0;
    }

    /**
     * AJAX handler for downloading the debug log
     */
    public function ajax_download_log() {
        // Check nonce
        if (!isset($_GET['nonce']) || !wp_verify_nonce($_GET['nonce'], 'download_subscription_log')) {
            wp_die(__('Security check failed.', 'subscription-system'));
        }
        
        // Check if user has permission
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have permission to perform this action.', 'subscription-system'));
        }
        
        $log_file = WP_CONTENT_DIR . '/subscription-system-debug.log';
        
        if (file_exists($log_file)) {
            // Set headers for download
            header('Content-Description: File Transfer');
            header('Content-Type: text/plain');
            header('Content-Disposition: attachment; filename="subscription-system-debug.log"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($log_file));
            
            // Clear output buffer
            ob_clean();
            flush();
            
            // Read the file and output it
            readfile($log_file);
            exit;
        } else {
            wp_die(__('Log file not found.', 'subscription-system'));
        }
    }

    /**
     * Log debug information if debug logging is enabled
     * 
     * @param string $message The message to log
     * @param mixed $data Optional data to include in the log
     */
    public function log_debug($message, $data = null) {
        // Check if debug logging is enabled
        if (get_option('subscription_enable_debug_logging', 0) != 1) {
            return;
        }
        
        $log_file = WP_CONTENT_DIR . '/subscription-system-debug.log';
        
        // Format the log entry
        $log_entry = '[' . date('Y-m-d H:i:s') . '] ' . $message;
        
        // Add data if provided
        if ($data !== null) {
            if (is_array($data) || is_object($data)) {
                $log_entry .= "\n" . print_r($data, true);
            } else {
                $log_entry .= ' - ' . $data;
            }
        }
        
        $log_entry .= "\n";
        
        // Initialize WordPress filesystem
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }
        
        // Append to the log file
        $existing_content = '';
        if ($wp_filesystem->exists($log_file)) {
            $existing_content = $wp_filesystem->get_contents($log_file);
        }
        $wp_filesystem->put_contents($log_file, $existing_content . $log_entry);
    }

    /**
     * Add Channels submenu to the Subscriptions menu
     */
    public function add_channels_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Channels', 'subscription-system'),
            esc_html__('Channels', 'subscription-system'),
            'manage_options',
            'subscription-channels',
            array($this, 'render_channels_page')
        );
    }

    /**
     * Render the Channels page content
     */
    public function render_channels_page() {
        // Process channel form submissions (add, edit, delete)
        $this->process_channel_form();
        
        // Get all channels
        $channels = $this->get_all_channels();
        
        // Include the channels template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/channels-display.php';
    }

    /**
     * Process channel form submissions (add, edit, delete)
     */
    private function process_channel_form() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_channels';
        
        // Add new channel
        if (isset($_POST['add_channel']) && isset($_POST['channel_name'])) {
            check_admin_referer('subscription_add_channel', 'subscription_nonce');
            
            $channel_name = sanitize_text_field(wp_unslash($_POST['channel_name']));
            $channel_description = isset($_POST['channel_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['channel_description'])) : '';
            $channel_status = isset($_POST['channel_status']) ? 
                sanitize_text_field(wp_unslash($_POST['channel_status'])) : 'active';
            
            if (!empty($channel_name)) {
                $result = $wpdb->insert(
                    $table_name,
                    array(
                        'name' => $channel_name,
                        'description' => $channel_description,
                        'status' => $channel_status,
                        'created_at' => current_time('mysql')
                    ),
                    array('%s', '%s', '%s', '%s')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'channel_added',
                        __('Channel added successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'channel_add_failed',
                        __('Failed to add channel.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'channel_name_empty',
                    __('Channel name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Edit channel
        if (isset($_POST['edit_channel']) && isset($_POST['channel_id']) && isset($_POST['channel_name'])) {
            check_admin_referer('subscription_edit_channel', 'subscription_nonce');
            
            $channel_id = intval($_POST['channel_id']);
            $channel_name = sanitize_text_field(wp_unslash($_POST['channel_name']));
            $channel_description = isset($_POST['channel_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['channel_description'])) : '';
            $channel_status = isset($_POST['channel_status']) ? 
                sanitize_text_field(wp_unslash($_POST['channel_status'])) : 'active';
            
            if (!empty($channel_name)) {
                $result = $wpdb->update(
                    $table_name,
                    array(
                        'name' => $channel_name,
                        'description' => $channel_description,
                        'status' => $channel_status
                    ),
                    array('id' => $channel_id),
                    array('%s', '%s', '%s'),
                    array('%d')
                );
                
                if ($result !== false) {
                    add_settings_error(
                        'subscription_messages',
                        'channel_updated',
                        __('Channel updated successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'channel_update_failed',
                        __('Failed to update channel.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'channel_name_empty',
                    __('Channel name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Delete channel
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['channel_id']) && isset($_GET['_wpnonce'])) {
            $channel_id = intval($_GET['channel_id']);
            
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_channel_' . $channel_id)) {
                $result = $wpdb->delete(
                    $table_name,
                    array('id' => $channel_id),
                    array('%d')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'channel_deleted',
                        __('Channel deleted successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'channel_delete_failed',
                        __('Failed to delete channel.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'invalid_nonce',
                    __('Security check failed.', 'subscription-system'),
                    'error'
                );
            }
        }
    }

    /**
     * Get all channels
     * 
     * @return array Array of channels
     */
    private function get_all_channels() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_channels';
        
        // Check if the table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the table if it doesn't exist
            $this->create_channels_table();
        }
        
        return $wpdb->get_results("SELECT * FROM $table_name ORDER BY id DESC");
    }

    /**
     * Create the channels table
     */
    private function create_channels_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_channels';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            description text NOT NULL,
            status varchar(50) NOT NULL DEFAULT 'active',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    // Add this after the add_channels_submenu method

    /**
     * Add Work Items submenu to the Subscriptions menu
     */
    public function add_work_items_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Work Items', 'subscription-system'),
            esc_html__('Work Items', 'subscription-system'),
            'manage_options',
            'subscription-work-items',
            array($this, 'render_work_items_page')
        );
    }

    /**
     * Render the Work Items page content
     */
    public function render_work_items_page() {
        // Process work item form submissions (add, edit, delete)
        $this->process_work_item_form();
        
        // Get all work items
        $work_items = $this->get_all_work_items();
        
        // Get all channels for dropdown
        $channels = $this->get_all_channels();
        
        // Include the work items template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/work-items-display.php';
    }

    /**
     * Process work item form submissions (add, edit, delete)
     */
    private function process_work_item_form() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_items';
        
        // Add new work item
        if (isset($_POST['add_work_item']) && isset($_POST['work_item_name'])) {
            check_admin_referer('subscription_add_work_item', 'subscription_nonce');
            
            $work_item_name = sanitize_text_field(wp_unslash($_POST['work_item_name']));
            $work_item_description = isset($_POST['work_item_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['work_item_description'])) : '';
            $work_item_status = isset($_POST['work_item_status']) ? 
                sanitize_text_field(wp_unslash($_POST['work_item_status'])) : 'active';
            $channel_id = isset($_POST['channel_id']) ? 
                intval($_POST['channel_id']) : 0;
            
            if (!empty($work_item_name)) {
                $result = $wpdb->insert(
                    $table_name,
                    array(
                        'name' => $work_item_name,
                        'description' => $work_item_description,
                        'status' => $work_item_status,
                        'channel_id' => $channel_id,
                        'created_at' => current_time('mysql')
                    ),
                    array('%s', '%s', '%s', '%d', '%s')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_added',
                        __('Work item added successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_add_failed',
                        __('Failed to add work item.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'work_item_name_empty',
                    __('Work item name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Edit work item
        if (isset($_POST['edit_work_item']) && isset($_POST['work_item_id']) && isset($_POST['work_item_name'])) {
            check_admin_referer('subscription_edit_work_item', 'subscription_nonce');
            
            $work_item_id = intval($_POST['work_item_id']);
            $work_item_name = sanitize_text_field(wp_unslash($_POST['work_item_name']));
            $work_item_description = isset($_POST['work_item_description']) ? 
                sanitize_textarea_field(wp_unslash($_POST['work_item_description'])) : '';
            $work_item_status = isset($_POST['work_item_status']) ? 
                sanitize_text_field(wp_unslash($_POST['work_item_status'])) : 'active';
            $channel_id = isset($_POST['channel_id']) ? 
                intval($_POST['channel_id']) : 0;
            
            if (!empty($work_item_name)) {
                $result = $wpdb->update(
                    $table_name,
                    array(
                        'name' => $work_item_name,
                        'description' => $work_item_description,
                        'status' => $work_item_status,
                        'channel_id' => $channel_id
                    ),
                    array('id' => $work_item_id),
                    array('%s', '%s', '%s', '%d'),
                    array('%d')
                );
                
                if ($result !== false) {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_updated',
                        __('Work item updated successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_update_failed',
                        __('Failed to update work item.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'work_item_name_empty',
                    __('Work item name cannot be empty.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Delete work item
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['work_item_id']) && isset($_GET['_wpnonce'])) {
            $work_item_id = intval($_GET['work_item_id']);
            
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_work_item_' . $work_item_id)) {
                $result = $wpdb->delete(
                    $table_name,
                    array('id' => $work_item_id),
                    array('%d')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_deleted',
                        __('Work item deleted successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'work_item_delete_failed',
                        __('Failed to delete work item.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'invalid_nonce',
                    __('Security check failed.', 'subscription-system'),
                    'error'
                );
            }
        }
    }

    /**
     * Get all work items
     * 
     * @return array Array of work items
     */
    private function get_all_work_items() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_items';
        
        // Check if the table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the table if it doesn't exist
            $this->create_work_items_table();
        }
        
        // Join with channels table to get channel name
        $query = "
            SELECT w.*, c.name as channel_name 
            FROM $table_name w
            LEFT JOIN {$wpdb->prefix}subscription_channels c ON w.channel_id = c.id
            ORDER BY w.id DESC
        ";
        
        return $wpdb->get_results($query);
    }

    /**
     * Create the work items table
     */
    private function create_work_items_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_items';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            description text NOT NULL,
            status varchar(50) NOT NULL DEFAULT 'active',
            channel_id mediumint(9) DEFAULT 0,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

    /**
     * Add Work Logs submenu to the Subscriptions menu
     */
    public function add_work_logs_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Work Logs', 'subscription-system'),
            esc_html__('Work Logs', 'subscription-system'),
            'read',
            'subscription-work-logs',
            array($this, 'render_work_logs_page')
        );
    }

    /**
     * Add Content Plans submenu to the Subscriptions menu
     */
    public function add_content_plans_submenu() {
        add_submenu_page(
            'subscription-dashboard',
            esc_html__('Content Plans', 'subscription-system'),
            esc_html__('Content Plans', 'subscription-system'),
            'manage_options',
            'subscription-content-plans',
            array($this, 'render_content_plans_page')
        );
    }

    /**
     * Render the Work Logs page content
     */
    public function render_work_logs_page() {
        // Get user ID from URL
        $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
        
        // Get current user ID
        $current_user_id = get_current_user_id();
        
        // Check permissions
        // Admin can view any user's logs, non-admin can only view their own logs
        if (!current_user_can('manage_options')) {
            // If not an admin, ensure user can only view their own logs
            if ($user_id != $current_user_id) {
                wp_die(
                    esc_html__('Sorry, you are not allowed to view this user\'s work logs.', 'subscription-system'),
                    esc_html__('Permission Denied', 'subscription-system'),
                    array('response' => 403)
                );
            }
        }
        
        // If no user_id specified and user is not admin, default to current user
        if ($user_id == 0 && !current_user_can('manage_options')) {
            $user_id = $current_user_id;
        }
        
        // Process work log form submissions (add, edit, delete)
        $this->process_work_log_form();
        
        // Get user information
        $user = get_userdata($user_id);
        
        // Get all work logs for this user
        $work_logs = $this->get_user_work_logs($user_id);
        
        // Get all channels for dropdown
        $channels = $this->get_all_channels();
        
        // Get all work items (will be filtered by JavaScript based on selected channel)
        $work_items = $this->get_all_work_items();
        
        // Include the work logs template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/work-logs-display.php';
    }

    /**
     * Render the Content Plans page content
     */
    public function render_content_plans_page() {
        // Handle form submissions
        $this->process_content_plans_forms();
        
        // Include the content plans template
        include plugin_dir_path(dirname(__FILE__)) . 'admin/partials/content-plans-display.php';
    }

    /**
     * Process content plans form submissions
     */
    private function process_content_plans_forms() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $content_manager = new Subs_Sys_Content_Manager();

        // Handle add/edit content plan
        if (isset($_POST['submit_content_plan']) && wp_verify_nonce($_POST['content_plan_nonce'], 'content_plan_action')) {
            $content_type = sanitize_text_field($_POST['content_type']);
            $content_ids  = isset($_POST['content_ids']) ? array_map('sanitize_text_field', $_POST['content_ids']) : array();
            $plan_id      = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;

            // Conflict check: category and tag IDs must be unique across all active plans.
            if ( in_array( $content_type, array( 'category', 'tag' ), true ) && ! empty( $content_ids ) ) {
                global $wpdb;
                $cp_table    = $wpdb->prefix . 'subscription_content_plans';
                $other_plans = $wpdb->get_results( $wpdb->prepare(
                    "SELECT id, plan_name, content_ids FROM $cp_table WHERE content_type = %s AND status = 'active'" . ( $plan_id ? ' AND id != ' . intval( $plan_id ) : '' ),
                    $content_type
                ) );

                $conflicts = array();
                foreach ( $other_plans as $op ) {
                    $op_ids = json_decode( $op->content_ids, true ) ?: array();
                    $overlapping = array_intersect( array_map( 'intval', $content_ids ), array_map( 'intval', $op_ids ) );
                    if ( ! empty( $overlapping ) ) {
                        // Resolve names for display.
                        $type_fn    = $content_type === 'category' ? 'get_category' : 'get_tag';
                        $term_names = array();
                        foreach ( $overlapping as $tid ) {
                            $term = $type_fn( (int) $tid );
                            $term_names[] = $term ? $term->name : "#$tid";
                        }
                        $conflicts[] = sprintf(
                            /* translators: 1: term names list, 2: conflicting plan name */
                            __( '%1$s (already used by "%2$s")', 'subscription-system' ),
                            implode( ', ', $term_names ),
                            $op->plan_name
                        );
                    }
                }

                if ( ! empty( $conflicts ) ) {
                    $label = $content_type === 'category' ? __( 'categories', 'subscription-system' ) : __( 'tags', 'subscription-system' );
                    add_settings_error(
                        'subscription_messages',
                        'content_plan_conflict',
                        sprintf(
                            /* translators: 1: content type label, 2: conflict details */
                            __( 'The following %1$s are already assigned to another plan and cannot be reused: %2$s', 'subscription-system' ),
                            $label,
                            implode( '; ', $conflicts )
                        ),
                        'error'
                    );
                    return;
                }
            }

            $plan_data = array(
                'plan_name' => sanitize_text_field($_POST['plan_name']),
                'description' => wp_kses_post($_POST['description']),
                'price' => floatval($_POST['price']),
                'duration' => intval($_POST['duration']),
                'duration_unit' => sanitize_text_field($_POST['duration_unit']),
                'content_type' => $content_type,
                'content_ids'  => $content_ids,
                'notification_frequency' => sanitize_text_field($_POST['notification_frequency']),
                'status' => sanitize_text_field($_POST['status'])
            );

            if ($plan_id > 0) {
                // Update existing plan
                $result = $content_manager->update_content_plan($plan_id, $plan_data);
                if (is_wp_error($result)) {
                    add_settings_error('subscription_messages', 'content_plan_update_failed', $result->get_error_message(), 'error');
                } else {
                    add_settings_error('subscription_messages', 'content_plan_updated', __('Content plan updated successfully.', 'subscription-system'), 'updated');
                    set_transient('subscription_messages', get_settings_errors('subscription_messages'), 30);
                    wp_redirect(admin_url('admin.php?page=subscription-content-plans&settings-updated=1'));
                    exit;
                }
            } else {
                // Create new plan
                $result = $content_manager->create_content_plan($plan_data);
                if (is_wp_error($result)) {
                    add_settings_error('subscription_messages', 'content_plan_create_failed', $result->get_error_message(), 'error');
                } else {
                    add_settings_error('subscription_messages', 'content_plan_created', __('Content plan created successfully.', 'subscription-system'), 'updated');
                    set_transient('subscription_messages', get_settings_errors('subscription_messages'), 30);
                    wp_redirect(admin_url('admin.php?page=subscription-content-plans&settings-updated=1'));
                    exit;
                }
            }
        }

        // Handle delete content plan
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['plan_id']) && isset($_GET['_wpnonce'])) {
            $plan_id = intval($_GET['plan_id']);
            
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_content_plan_' . $plan_id)) {
                $result = $content_manager->delete_content_plan($plan_id);
                
                if (is_wp_error($result)) {
                    add_settings_error('subscription_messages', 'content_plan_delete_failed', $result->get_error_message(), 'error');
                } else {
                    add_settings_error('subscription_messages', 'content_plan_deleted', __('Content plan deleted successfully.', 'subscription-system'), 'updated');
                }
                
                set_transient('subscription_messages', get_settings_errors('subscription_messages'), 30);
                wp_redirect(admin_url('admin.php?page=subscription-content-plans&settings-updated=1'));
                exit;
            } else {
                add_settings_error('subscription_messages', 'invalid_nonce', __('Security check failed.', 'subscription-system'), 'error');
            }
        }
    }

    /**
     * Handle manual database update requests
     */
    public function handle_database_update() {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_GET['subs_sys_action']) && $_GET['subs_sys_action'] === 'update_database' && isset($_GET['_wpnonce'])) {
            if (wp_verify_nonce($_GET['_wpnonce'], 'subs_sys_update_db')) {
                Subs_Sys_DB_Updater::force_update();
                add_settings_error('subscription_messages', 'db_updated', __('Database updated successfully!', 'subscription-system'), 'updated');
            } else {
                add_settings_error('subscription_messages', 'invalid_nonce', __('Security check failed.', 'subscription-system'), 'error');
            }
        }
    }

    /**
     * Process work log form submissions (add, edit, delete)
     */
    private function process_work_log_form() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_logs';
        
        // Create the table if it doesn't exist
        $this->create_work_logs_table();
        
        // Add new work log
        if (isset($_POST['add_work_log']) && isset($_POST['user_id'])) {
            check_admin_referer('subscription_add_work_log', 'subscription_nonce');
            
            $user_id = intval($_POST['user_id']);
            $channel_id = isset($_POST['channel_id']) ? intval($_POST['channel_id']) : 0;
            $work_item_id = isset($_POST['work_item_id']) ? intval($_POST['work_item_id']) : 0;
            $importance = isset($_POST['importance']) ? sanitize_text_field(wp_unslash($_POST['importance'])) : '';
            $notes = isset($_POST['notes']) ? wp_kses_post($_POST['notes']) : '';
            $performed_at = isset($_POST['performed_at']) ? sanitize_text_field($_POST['performed_at']) : current_time('mysql');
            
            // Validate performed_at date format
            if (!empty($performed_at)) {
                // Convert to MySQL format if needed
                if (preg_match('/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}$/', $performed_at)) {
                    $performed_at = date('Y-m-d H:i:s', strtotime($performed_at));
                }
            } else {
                $performed_at = current_time('mysql');
            }
            
            if ($user_id > 0) {
                $result = $wpdb->insert(
                    $table_name,
                    array(
                        'user_id' => $user_id,
                        'channel_id' => $channel_id,
                        'work_item_id' => $work_item_id,
                        'importance' => $importance,
                        'notes' => $notes,
                        'performed_at' => $performed_at,
                        'created_at' => current_time('mysql')
                    ),
                    array('%d', '%d', '%d', '%s', '%s', '%s', '%s')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'work_log_added',
                        __('Work log added successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'work_log_add_failed',
                        __('Failed to add work log.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'invalid_user',
                    __('Invalid user ID.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Edit work log
        if (isset($_POST['edit_work_log']) && isset($_POST['work_log_id'])) {
            check_admin_referer('subscription_edit_work_log', 'subscription_nonce');
            
            $work_log_id = intval($_POST['work_log_id']);
            $channel_id = isset($_POST['channel_id']) ? intval($_POST['channel_id']) : 0;
            $work_item_id = isset($_POST['work_item_id']) ? intval($_POST['work_item_id']) : 0;
            $importance = isset($_POST['importance']) ? sanitize_text_field(wp_unslash($_POST['importance'])) : '';
            $notes = isset($_POST['notes']) ? wp_kses_post($_POST['notes']) : '';
            $performed_at = isset($_POST['performed_at']) ? sanitize_text_field($_POST['performed_at']) : current_time('mysql');
            
            // Validate performed_at date format
            if (!empty($performed_at)) {
                // Convert to MySQL format if needed
                if (preg_match('/^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}$/', $performed_at)) {
                    $performed_at = date('Y-m-d H:i:s', strtotime($performed_at));
                }
            } else {
                $performed_at = current_time('mysql');
            }
            
            $result = $wpdb->update(
                $table_name,
                array(
                    'channel_id' => $channel_id,
                    'work_item_id' => $work_item_id,
                    'importance' => $importance,
                    'notes' => $notes,
                    'performed_at' => $performed_at
                ),
                array('id' => $work_log_id),
                array('%d', '%d', '%s', '%s', '%s'),
                array('%d')
            );
            
            if ($result !== false) {
                add_settings_error(
                    'subscription_messages',
                    'work_log_updated',
                    __('Work log updated successfully.', 'subscription-system'),
                    'updated'
                );
            } else {
                add_settings_error(
                    'subscription_messages',
                    'work_log_update_failed',
                    __('Failed to update work log.', 'subscription-system'),
                    'error'
                );
            }
        }
        
        // Delete work log
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['work_log_id']) && isset($_GET['_wpnonce'])) {
            $work_log_id = intval($_GET['work_log_id']);
            $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
            
            if (wp_verify_nonce($_GET['_wpnonce'], 'delete_work_log_' . $work_log_id)) {
                $result = $wpdb->delete(
                    $table_name,
                    array('id' => $work_log_id),
                    array('%d')
                );
                
                if ($result) {
                    add_settings_error(
                        'subscription_messages',
                        'work_log_deleted',
                        __('Work log deleted successfully.', 'subscription-system'),
                        'updated'
                    );
                } else {
                    add_settings_error(
                        'subscription_messages',
                        'work_log_delete_failed',
                        __('Failed to delete work log.', 'subscription-system'),
                        'error'
                    );
                }
            } else {
                add_settings_error(
                    'subscription_messages',
                    'invalid_nonce',
                    __('Security check failed.', 'subscription-system'),
                    'error'
                );
            }
        }
    }

    /**
     * Get all work logs for a specific user
     * 
     * @param int $user_id The user ID
     * @return array Array of work logs
     */
    private function get_user_work_logs($user_id) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_logs';
        
        // Check if the table exists
        if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
            // Create the table if it doesn't exist
            $this->create_work_logs_table();
        }
        
        // Join with channels and work items tables to get names
        $query = "
            SELECT l.*, 
                   c.name as channel_name, 
                   w.name as work_item_name,
                   u.display_name as user_name
            FROM $table_name l
            LEFT JOIN {$wpdb->prefix}subscription_channels c ON l.channel_id = c.id
            LEFT JOIN {$wpdb->prefix}subscription_work_items w ON l.work_item_id = w.id
            LEFT JOIN {$wpdb->users} u ON l.user_id = u.ID
            WHERE l.user_id = %d
            ORDER BY l.performed_at DESC
        ";
        
        return $wpdb->get_results($wpdb->prepare($query, $user_id));
    }

    /**
     * Create the work logs table
     */
    private function create_work_logs_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'subscription_work_logs';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE $table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT,
            user_id bigint(20) NOT NULL,
            channel_id mediumint(9) DEFAULT 0,
            work_item_id mediumint(9) DEFAULT 0,
            importance varchar(255) NOT NULL,
            notes longtext NOT NULL,
            performed_at datetime DEFAULT CURRENT_TIMESTAMP,
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            KEY user_id (user_id)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }

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

    /**
     * Handle AJAX requests
     */
    public function handle_ajax_request() {
        if (!wp_verify_nonce($_POST['nonce'], 'subscription_action_nonce')) {
            wp_send_json_error(array(
                'message' => esc_html__('Security check failed.', 'subscription-system')
            ));
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => esc_html__('You do not have permission to perform this action.', 'subscription-system')
            ));
        }

        $subscription_id = isset($_POST['subscription_id']) ? intval($_POST['subscription_id']) : 0;
        if (!$subscription_id) {
            wp_send_json_error(array(
                'message' => esc_html__('Invalid subscription ID.', 'subscription-system')
            ));
        }

        $action = isset($_POST['action']) ? sanitize_text_field($_POST['action']) : '';
        switch ($action) {
            case 'cancel':
                if ($this->cancel_subscription($subscription_id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Subscription cancelled successfully.', 'subscription-system')
                    ));
                }
                break;

            case 'pause':
                if ($this->pause_subscription($subscription_id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Subscription paused successfully.', 'subscription-system')
                    ));
                }
                break;

            case 'resume':
                if ($this->resume_subscription($subscription_id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Subscription resumed successfully.', 'subscription-system')
                    ));
                }
                break;

            case 'delete':
                if ($this->delete_subscription($subscription_id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Subscription deleted successfully.', 'subscription-system')
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to delete subscription.', 'subscription-system')
                    ));
                }
                break;

            case 'update_status':
                $new_status = isset($_POST['new_status']) ? sanitize_text_field($_POST['new_status']) : '';
                if (empty($new_status)) {
                    wp_send_json_error(array(
                        'message' => esc_html__('Invalid status.', 'subscription-system')
                    ));
                }

                if ($this->update_subscription_status($subscription_id, $new_status)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Subscription status updated successfully.', 'subscription-system')
                    ));
                }
                break;

            default:
                wp_send_json_error(array(
                    'message' => esc_html__('Invalid action.', 'subscription-system')
                ));
                break;
        }
    }

    /**
     * Handle category management
     */
    public function handle_category_actions() {
        if (!wp_verify_nonce($_POST['nonce'], 'category_action_nonce')) {
            wp_send_json_error(array(
                'message' => esc_html__('Security check failed.', 'subscription-system')
            ));
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => esc_html__('You do not have permission to perform this action.', 'subscription-system')
            ));
        }

        $action = sanitize_text_field($_POST['action']);
        switch ($action) {
            case 'add':
                $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
                if (empty($name)) {
                    wp_send_json_error(array(
                        'message' => esc_html__('Category name cannot be empty.', 'subscription-system')
                    ));
                }

                if ($this->add_category($name)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Category added successfully.', 'subscription-system')
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to add category.', 'subscription-system')
                    ));
                }
                break;

            case 'update':
                $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
                $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : '';
                
                if (empty($name)) {
                    wp_send_json_error(array(
                        'message' => esc_html__('Category name cannot be empty.', 'subscription-system')
                    ));
                }

                if ($this->update_category($id, $name)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Category updated successfully.', 'subscription-system')
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to update category.', 'subscription-system')
                    ));
                }
                break;

            case 'delete':
                $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
                
                if ($this->delete_category($id)) {
                    wp_send_json_success(array(
                        'message' => esc_html__('Category deleted successfully.', 'subscription-system')
                    ));
                } else {
                    wp_send_json_error(array(
                        'message' => esc_html__('Failed to delete category.', 'subscription-system')
                    ));
                }
                break;

            default:
                wp_send_json_error(array(
                    'message' => esc_html__('Invalid action.', 'subscription-system')
                ));
                break;
        }
    }
} 