<?php //phpcs:ignore
declare(strict_types=1);

namespace AtlasAiDev\Awfah\Admin;


/**
 * Class MCP_Settings
 * Handles the MCP settings page in WordPress admin.
 */
class MCP_Settings {
    /**
     * The option name in the WordPress options table.
     */
    const OPTION_NAME = 'wordpress_mcp_settings';

    /**
     * The tool states option name.
     */
    const TOOL_STATES_OPTION = 'wordpress_mcp_tool_states';

    /**
     * Initialize the settings page.
     */
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'wp_ajax_wordpress_mcp_save_settings', array( $this, 'ajax_save_settings' ) );
        add_action( 'wp_ajax_wordpress_mcp_toggle_tool', array( $this, 'ajax_toggle_tool' ) );
        add_action( 'wp_ajax_atlas_plugins_refresh', array( $this, 'ajax_refresh_plugins' ) );
        add_filter( 'plugin_action_links_' . plugin_basename( AWFAH_PLUGIN_DIR . 'ai-workflow-automation-ai-agent-hub.php' ), array( $this, 'plugin_action_links' ) );
    }

    /**
     * Add the settings page to the WordPress admin menu.
     */
    public function add_settings_page(): void {
        add_submenu_page(
            'ai-workflow-automation-ai-agent-hub',
            __( 'MCP Auth', 'ai-workflow-automation-ai-agent-hub' ),
            __( 'MCP Auth', 'ai-workflow-automation-ai-agent-hub' ),
            'manage_options',
            'ai-agent-hub-mcp',
            [ $this, 'render_settings_page' ]
        );

        $this->atlasaidev_plugins('atlasagent-other-plugins');

    }

    /**
     * Register the settings and their sanitization callbacks.
     */
    public function register_settings(): void {
        register_setting(
            'wordpress_mcp_settings',
            self::OPTION_NAME,
            array(
                'type'              => 'array',
                'sanitize_callback' => array( $this, 'sanitize_settings' ),
            )
        );
    }

    /**
     * Checks if WordPress Feature API is available.
     *
     * @return bool True if WP Feature API is available, false otherwise.
     */
    private function is_feature_api_available(): bool {
        return defined( 'WP_FEATURE_API_VERSION' );
    }

    /**
     * Enqueue scripts and styles for the React app.
     *
     * @param string $hook The current admin page.
     */
    public function enqueue_scripts( string $hook ): void {
//        if ( 'settings_page_wordpress-mcp-settings' !== $hook ) {
//            return;
//        }

        $asset_file = include AWFAH_PLUGIN_DIR . 'assets/mcp/build/index.asset.php';

        // Enqueue our React app.
        wp_enqueue_script(
            'awfah-mcp-settings',
            AWFAH_PLUGIN_URL . 'assets/mcp/build/index.js',
            $asset_file['dependencies'],
            $asset_file['version'],
            true
        );

        // Enqueue the WordPress components styles CSS.
        wp_enqueue_style(
            'wp-components',
            includes_url( 'css/dist/components/style.css' ),
            array(),
            $asset_file['version'],
        );

        // Enqueue the WordPress MCP settings CSS.
        wp_enqueue_style(
            'awfah-mcp-settings-css',
            AWFAH_PLUGIN_URL . 'assets/mcp/build/style-index.css',
            array(),
            $asset_file['version'],
        );

        // Localize the script with data needed by the React app.
        wp_localize_script(
            'awfah-mcp-settings',
            'wordpressMcpSettings',
            array(
                'apiUrl'              => rest_url( 'awfah/v1/settings' ),
                'nonce'               => wp_create_nonce( 'wordpress_mcp_settings' ),
                'settings'            => get_option( self::OPTION_NAME, array() ), // TODO
                'toolStates'          => get_option( self::TOOL_STATES_OPTION, array() ),
                'featureApiAvailable' => $this->is_feature_api_available(),
                'pluginUrl'           => AWFAH_PLUGIN_URL,
                'siteUrl'             => home_url(),
                'strings'             => array(
                    'enableMcp'                         => __( 'Enable MCP functionality', 'awfah' ),
                    'enableMcpDescription'              => __( 'Toggle to enable or disable the MCP plugin functionality.', 'awfah' ),
                    'enableFeaturesAdapter'             => __( 'Enable WordPress Features Adapter', 'awfah' ),
                    'enableFeaturesAdapterDescription'  => __( 'Enable or disable the WordPress Features Adapter. This option only works when MCP is enabled.', 'awfah' ),
                    'enableCreateTools'                 => __( 'Enable Create Tools', 'awfah' ),
                    'enableCreateToolsDescription'      => __( 'Allow create operations via tools.', 'awfah' ),
                    'enableUpdateTools'                 => __( 'Enable Update Tools', 'awfah' ),
                    'enableUpdateToolsDescription'      => __( 'Allow update operations via tools.', 'awfah' ),
                    'enableDeleteTools'                 => __( 'Enable Delete Tools', 'awfah' ),
                    'enableDeleteToolsDescription'      => __( '⚠️ CAUTION: Allow deletion operations via tools.', 'awfah' ),
                    'enableRestApiCrudTools'            => __( '🧪 Enable REST API CRUD Tools (EXPERIMENTAL)', 'awfah' ),
                    'enableRestApiCrudToolsDescription' => __( '⚠️ EXPERIMENTAL FEATURE: Enable or disable the generic REST API CRUD tools for accessing WordPress endpoints. This is experimental functionality that may change or be removed in future versions. When enabled, all tools that are a rest_alias or have the disabled_by_rest_crud flag will be disabled.', 'awfah' ),
                    'saveSettings'                      => __( 'Save Settings', 'awfah' ),
                    'settingsSaved'                     => __( 'Settings saved successfully!', 'awfah' ),
                    'settingsError'                     => __( 'Error saving settings. Please try again.', 'awfah' ),
                    // translators: %1$s: tool name, %2$s: action (enabled/disabled).
                    'toolEnabled'                       => __( 'Tool %1$s has been %2$s.', 'awfah' ),
                    // translators: %1$s: tool name, %2$s: action (enabled/disabled).
                    'toolDisabled'                      => __( 'Tool %1$s has been %2$s.', 'awfah' ),
                ),
            )
        );
    }

    /**
     * AJAX handler for saving settings.
     */
    public function ajax_save_settings(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'awfah' ) ) );
        }

        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'wordpress_mcp_settings' ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid nonce. Please refresh the page and try again.', 'awfah' ) ) );
        }

        // Sanitize the settings input.
        $settings_raw = isset( $_POST['settings'] ) ? sanitize_text_field( wp_unslash( $_POST['settings'] ) ) : '{}';
        $settings     = $this->sanitize_settings( json_decode( $settings_raw, true ) );
        update_option( self::OPTION_NAME, $settings );

        wp_send_json_success( array( 'message' => __( 'Settings saved successfully!', 'awfah' ) ) );
    }

    /**
     * Sanitize the settings before saving.
     *
     * @param array $input The input array.
     * @return array The sanitized input array.
     */
    public function sanitize_settings( array $input ): array {
        $sanitized = array();

        if ( isset( $input['enabled'] ) ) {
            $sanitized['enabled'] = (bool) $input['enabled'];
        } else {
            $sanitized['enabled'] = false;
        }

        if ( isset( $input['features_adapter_enabled'] ) ) {
            $sanitized['features_adapter_enabled'] = (bool) $input['features_adapter_enabled'];
        } else {
            $sanitized['features_adapter_enabled'] = false;
        }

        if ( isset( $input['enable_create_tools'] ) ) {
            $sanitized['enable_create_tools'] = (bool) $input['enable_create_tools'];
        } else {
            $sanitized['enable_create_tools'] = false;
        }

        if ( isset( $input['enable_update_tools'] ) ) {
            $sanitized['enable_update_tools'] = (bool) $input['enable_update_tools'];
        } else {
            $sanitized['enable_update_tools'] = false;
        }

        if ( isset( $input['enable_delete_tools'] ) ) {
            $sanitized['enable_delete_tools'] = (bool) $input['enable_delete_tools'];
        } else {
            $sanitized['enable_delete_tools'] = false;
        }

        if ( isset( $input['enable_rest_api_crud_tools'] ) ) {
            $sanitized['enable_rest_api_crud_tools'] = (bool) $input['enable_rest_api_crud_tools'];
        } else {
            $sanitized['enable_rest_api_crud_tools'] = false;
        }

        return $sanitized;
    }

    /**
     * Render the settings page.
     */
    public function render_settings_page(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
            <div id="awfah-settings-app"></div>
        </div>
        <?php
    }

    /**
     * Add settings link to plugin actions.
     *
     * @param array $actions An array of plugin action links.
     * @return array
     */
    public function plugin_action_links( array $actions ): array {
        $settings_link = '<a href="' . admin_url( 'admin.php?page=ai-workflow-automation-ai-agent-hub' ) . '">' . __( 'Settings', 'awfah' ) . '</a>';
        $ai_credentials_link = '<a href="' . admin_url( 'options-general.php?page=wp-ai-client' ) . '">' . __( 'AI Credentials', 'awfah' ) . '</a>';
        $mcp_auth_link = '<a href="' . admin_url( 'admin.php?page=ai-agent-hub-mcp#authentication-tokens' ) . '">' . __( 'MCP Auth', 'awfah' ) . '</a>';
        array_unshift( $actions, $settings_link );
        array_unshift( $actions, $mcp_auth_link );
        array_unshift( $actions, $ai_credentials_link );
        return $actions;
    }

    /**
     * AJAX handler for toggling tool state.
     */
    public function ajax_toggle_tool(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'You do not have permission to perform this action.', 'awfah' ) ) );
        }

        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'wordpress_mcp_settings' ) ) {
            wp_send_json_error( array( 'message' => __( 'Invalid nonce. Please refresh the page and try again.', 'awfah' ) ) );
        }

        $tool_name = isset( $_POST['tool'] ) ? sanitize_text_field( wp_unslash( $_POST['tool'] ) ) : '';
        $enabled   = isset( $_POST['tool_enabled'] ) ? filter_var( wp_unslash( $_POST['tool_enabled'] ), FILTER_VALIDATE_BOOLEAN ) : false;

        if ( empty( $tool_name ) ) {
            wp_send_json_error( array( 'message' => __( 'Tool name is required.', 'awfah' ) ) );
        }

        $success = $this->toggle_tool( $tool_name, $enabled );

        if ( ! $success ) {
            wp_send_json_error( array( 'message' => __( 'Failed to toggle tool state.', 'awfah' ) ) );
        }

        wp_send_json_success(
            array(
                'message' => sprintf(
                // translators: %1$s: tool name, %2$s: action (enabled/disabled).
                    __( 'Tool %1$s has been %2$s.', 'awfah' ),
                    $tool_name,
                    $enabled ? __( 'enabled', 'awfah' ) : __( 'disabled', 'awfah' )
                ),
            )
        );
    }

    /**
     * Toggle a tool's state.
     *
     * @param string $tool_name The name of the tool to toggle.
     * @param bool   $enabled   Whether the tool should be enabled.
     * @return bool Whether the operation was successful.
     */
    public function toggle_tool( string $tool_name, bool $enabled ): bool {
        $tool_states               = get_option( self::TOOL_STATES_OPTION, array() );
        $tool_states[ $tool_name ] = $enabled;
        try {
            update_option( self::TOOL_STATES_OPTION, $tool_states, 'no' );
        } catch ( \Exception $e ) {
            error_log( 'Failed to update tool states option: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            return false;
        }
        return true;
    }

    /**
     * Remote URL for the plugins.json file.
     */
    const ATLAS_PLUGINS_REMOTE_URL = 'https://raw.githubusercontent.com/atlasaidev/plugins/main/plugins.json';

    /**
     * Transient key for cached plugin data.
     */
    const ATLAS_PLUGINS_TRANSIENT = 'atlas_plugins_remote_data';

    /**
     * Transient key for WP.org plugin info cache.
     */
    const ATLAS_PLUGINS_WPORG_TRANSIENT = 'atlas_plugins_wporg_info';

    /**
     * Cache duration in seconds (24 hours).
     */
    const ATLAS_PLUGINS_CACHE_TTL = 86400;

    /**
     * Fetch plugin data from GitHub with transient caching.
     *
     * @return array List of plugin objects.
     */
    public static function get_atlas_plugins() {
        $cached = get_transient(self::ATLAS_PLUGINS_TRANSIENT);
        if (false !== $cached && is_array($cached)) {
            return $cached;
        }

        $response = wp_remote_get(self::ATLAS_PLUGINS_REMOTE_URL, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json'),
        ));

        if (!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
            $body = wp_remote_retrieve_body($response);
            $data = json_decode($body, true);
            if (is_array($data) && !empty($data)) {
                set_transient(self::ATLAS_PLUGINS_TRANSIENT, $data, self::ATLAS_PLUGINS_CACHE_TTL);
                return $data;
            }
        }

        // Fallback: hardcoded plugin data.
        return self::get_fallback_plugins();
    }

    /**
     * Hardcoded fallback plugin data in case remote fetch fails.
     *
     * @return array
     */
    private static function get_fallback_plugins() {
        return array(
            array(
                'name'          => 'Text To Speech TTS – AtlasVoice',
                'slug'          => 'text-to-audio',
                'basename'      => 'text-to-audio/text-to-audio.php',
                'icon'          => 'https://ps.w.org/text-to-audio/assets/icon-256x256.gif',
                'learnMoreUrl'  => 'https://atlasaidev.com/plugins/text-to-speech-pro/pricing/',
                'proBasenames'  => array(
                    'text-to-speech-pro/text-to-audio-pro.php',
                    'text-to-speech-pro-premium/text-to-audio-pro.php',
                    'text-to-audio-pro/text-to-audio-pro.php',
                    'text-to-audio-pro-premium/text-to-audio-pro.php',
                ),
                'proUrl'        => 'https://atlasaidev.com/plugins/text-to-speech-pro/pricing/',
                'configureSlug' => 'text-to-audio',
                'isNew'         => false,
                'complementary' => array('ai-workflow-automation-ai-agent-hub', 'smart-local-ai'),
                'priority'      => 1,
                'description'   => 'The most user-friendly Text-to-Speech accessibility plugin for WordPress. Automatically adds an audio player with no API required.',
                'features'      => array(
                    'Unlimited text-to-speech conversion',
                    '80+ languages, 20-300+ voices',
                    'Customizable player design',
                    'Shortcode support with flexible attributes',
                    'Custom Post Type & ACF compatibility',
                    'No external API required (browser SpeechSynthesis)',
                    'Multilingual support (WPML, GTranslate)',
                    'Analytics & engagement tracking',
                ),
            ),
            array(
                'name'          => '3D Model Viewer – AtlasAR',
                'slug'          => 'ar-vr-3d-model-try-on',
                'basename'      => 'ar-vr-3d-model-try-on/ar-vr-3d-model-try-on.php',
                'icon'          => 'https://ps.w.org/ar-vr-3d-model-try-on/assets/icon-256x256.gif',
                'learnMoreUrl'  => 'https://wpaugmentedreality.com/pricing/',
                'proBasenames'  => array(
                    'ar-vr-3d-model-try-on-pro/ar-vr-3d-model-try-on-premium.php',
                    'ar-vr-3d-model-try-on-premium/ar-vr-3d-model-try-on-premium.php',
                ),
                'proUrl'        => 'https://wpaugmentedreality.com/pricing/',
                'configureSlug' => 'ar-vr-3d-model-try-on',
                'isNew'         => false,
                'complementary' => array('text-to-audio', 'smart-local-ai'),
                'priority'      => 2,
                'description'   => 'Display interactive 3D models and augmented reality on your WordPress & WooCommerce site for enhanced product visualization.',
                'features'      => array(
                    'Interactive 3D model display',
                    'Augmented Reality (AR) support',
                    'WordPress & WooCommerce integration',
                    'Mobile-optimized viewing',
                    'Customizable display options',
                    'Reduces return rates with realistic visualization',
                    'Easy product page embedding',
                ),
            ),
            array(
                'name'          => 'AI Workflow Automation – AtlasAgent',
                'slug'          => 'ai-workflow-automation-ai-agent-hub',
                'basename'      => 'ai-workflow-automation-ai-agent-hub/ai-workflow-automation-ai-agent-hub.php',
                'icon'          => 'https://ps.w.org/ai-workflow-automation-ai-agent-hub/assets/icon-256x256.gif',
                'learnMoreUrl'  => 'https://wordpress.org/plugins/ai-workflow-automation-ai-agent-hub/',
                'proBasenames'  => array(
                    'ai-workflow-automation-ai-agent-hub-pro/ai-workflow-automation-ai-agent-hub-pro.php',
                ),
                'proUrl'        => 'https://atlasaidev.com/ai-agent-hub-pro/',
                'configureSlug' => 'ai-workflow-automation-ai-agent-hub',
                'isNew'         => false,
                'complementary' => array('text-to-audio', 'smart-local-ai'),
                'priority'      => 1,
                'description'   => 'Transform WordPress into an AI-powered control center with 70+ abilities, MCP server support, and workflow builder.',
                'features'      => array(
                    '70+ abilities across 9 modules',
                    'Built-in MCP Server (JSON-RPC 2.0)',
                    'JWT authentication',
                    'Drag-and-drop workflow builder',
                    'Multi-provider AI support (OpenAI, Gemini, Claude)',
                    'WooCommerce AI Store Manager',
                    'Post editor AI integration',
                ),
            ),
            array(
                'name'          => 'Smart Local AI – AtlasAI',
                'slug'          => 'smart-local-ai',
                'basename'      => 'smart-local-ai/smart-local-ai.php',
                'icon'          => 'https://ps.w.org/smart-local-ai/assets/icon-256x256.png',
                'learnMoreUrl'  => 'https://atlasaidev.com/smart-local-ai-pro/',
                'proBasenames'  => array(
                    'smart-local-ai-pro/smart-local-ai-pro.php',
                ),
                'proUrl'        => 'https://atlasaidev.com/smart-local-ai-pro/',
                'configureSlug' => 'smart-local-ai',
                'isNew'         => true,
                'complementary' => array('ai-workflow-automation-ai-agent-hub', 'text-to-audio'),
                'priority'      => 1,
                'description'   => 'Browser-based private AI tools for WordPress. Semantic related posts, personalized recommendations, and automatic alt text generation — all running on-device with zero cloud costs.',
                'features'      => array(
                    'RelevantFlow: Semantic content recommendations',
                    'PersonaFlow: Personalized recommendations based on visitor behavior',
                    'AltGenius: Automatic alt text generation for images',
                    'Zero cost — no API keys or subscriptions needed',
                    'Privacy by architecture — all AI runs in-browser',
                    'WebGPU + WASM hardware-accelerated inference',
                    'Works with any post type including WooCommerce products',
                    'GDPR compliant — no external data transmission',
                ),
            ),
        );
    }

    /**
     * Fetch WP.org plugin info (rating, installs) for all atlas plugins.
     *
     * @param array $plugins List of plugin data from get_atlas_plugins().
     * @return array Keyed by slug: { rating, num_ratings, active_installs }
     */
    public static function get_wporg_info($plugins) {
        $cached = get_transient(self::ATLAS_PLUGINS_WPORG_TRANSIENT);
        if (false !== $cached && is_array($cached)) {
            return $cached;
        }

        $info = array();
        foreach ($plugins as $plugin) {
            $slug = $plugin['slug'];
            $url  = 'https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&request[slug]=' . urlencode($slug) . '&request[fields][active_installs]=1&request[fields][rating]=1&request[fields][num_ratings]=1&request[fields][sections]=0&request[fields][description]=0';
            $response = wp_remote_get($url, array('timeout' => 5));
            if (!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
                $data = json_decode(wp_remote_retrieve_body($response), true);
                if (is_array($data) && !empty($data['slug'])) {
                    $info[$slug] = array(
                        'rating'          => isset($data['rating']) ? (int) $data['rating'] : 0,
                        'num_ratings'     => isset($data['num_ratings']) ? (int) $data['num_ratings'] : 0,
                        'active_installs' => isset($data['active_installs']) ? (int) $data['active_installs'] : 0,
                    );
                }
            }
            if (!isset($info[$slug])) {
                $info[$slug] = array('rating' => 0, 'num_ratings' => 0, 'active_installs' => 0);
            }
        }

        set_transient(self::ATLAS_PLUGINS_WPORG_TRANSIENT, $info, self::ATLAS_PLUGINS_CACHE_TTL);
        return $info;
    }

    /**
     * Detect which plugins have their Pro version installed or active.
     *
     * @param array $plugins     List of plugin data from get_atlas_plugins().
     * @param array $all_plugins All installed plugin basenames.
     * @param array $active_plugins Active plugin basenames.
     * @return array { pro_installed: string[], pro_active: string[] }
     */
    public static function detect_pro_status($plugins, $all_plugins, $active_plugins) {
        $pro_installed = array();
        $pro_active    = array();

        foreach ($plugins as $plugin) {
            $slug = $plugin['slug'];
            if (empty($plugin['proBasenames']) || !is_array($plugin['proBasenames'])) {
                continue;
            }
            foreach ($plugin['proBasenames'] as $pro_basename) {
                if (in_array($pro_basename, $all_plugins, true)) {
                    $pro_installed[] = $slug;
                    if (in_array($pro_basename, $active_plugins, true)) {
                        $pro_active[] = $slug;
                    }
                    break; // Found one match, no need to check other basenames.
                }
            }
        }

        return array(
            'pro_installed' => array_unique($pro_installed),
            'pro_active'    => array_unique($pro_active),
        );
    }

    public function atlasaidev_plugins($menu_slug = 'atlasagent-other-plugins', $plugin_slug = 'ai-workflow-automation-ai-agent-hub') {
        // Atlas Plugins submenu
        if (!empty($_REQUEST['page']) && $_REQUEST['page'] === $menu_slug) {
            $js  = AWFAH_PLUGIN_URL . 'assets/js/atlas-plugins.js';
            wp_enqueue_script(
                'atlas-plugins',
                $js,
                array('wp-i18n', 'updates'),
                AWFAH_VERSION,
                true
            );
            wp_set_script_translations(
                'atlas-plugins',
                'ai-workflow-automation-ai-agent-hub',
                plugin_dir_path(dirname(__FILE__)) . 'languages'
            );

            // Fetch plugin list from remote (cached).
            $atlas_plugins = self::get_atlas_plugins();

            // Build basenames map dynamically from remote data.
            $atlas_basenames = array();
            foreach ($atlas_plugins as $plugin) {
                if (!empty($plugin['slug']) && !empty($plugin['basename'])) {
                    $atlas_basenames[$plugin['slug']] = $plugin['basename'];
                }
            }

            // Determine installed and active plugin statuses.
            if (!function_exists('get_plugins')) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }
            $all_plugins    = array_keys(get_plugins());
            $active_plugins = (array) get_option('active_plugins', array());

            $installed_slugs = array();
            $active_slugs    = array();
            $activate_urls   = array();
            foreach ($atlas_basenames as $slug => $basename) {
                if (in_array($basename, $all_plugins, true)) {
                    $installed_slugs[] = $slug;
                    if (!in_array($basename, $active_plugins, true)) {
                        $activate_urls[$slug] = html_entity_decode(wp_nonce_url(
                            admin_url('plugins.php?action=activate&plugin=' . urlencode($basename)),
                            'activate-plugin_' . $basename
                        ));
                    }
                }
                if (in_array($basename, $active_plugins, true)) {
                    $active_slugs[] = $slug;
                }
            }

            // Fetch WP.org info (ratings, installs) — cached.
            $wporg_info = self::get_wporg_info($atlas_plugins);

            // Detect Pro plugin install/active status.
            $pro_status = self::detect_pro_status($atlas_plugins, $all_plugins, $active_plugins);

            // Find the current plugin's display name for the banner.
            $current_plugin_name = '';
            foreach ($atlas_plugins as $p) {
                if (!empty($p['slug']) && $p['slug'] === $plugin_slug) {
                    $current_plugin_name = $p['name'];
                    break;
                }
            }

            wp_localize_script('atlas-plugins', 'atlasPluginsData', array(
                'current_plugin_slug' => $plugin_slug,
                'current_plugin_name' => $current_plugin_name,
                'plugins'             => $atlas_plugins,
                'installed_plugins'   => $installed_slugs,
                'active_plugins'      => $active_slugs,
                'activate_urls'       => (object) $activate_urls,
                'wporg_info'          => (object) $wporg_info,
                'pro_installed'       => $pro_status['pro_installed'],
                'pro_active'          => $pro_status['pro_active'],
                'admin_url'           => admin_url(),
                'ajax_url'            => admin_url('admin-ajax.php'),
                'refresh_nonce'       => wp_create_nonce('atlas_plugins_refresh'),
            ));
        }
        add_submenu_page(
            'ai-workflow-automation-ai-agent-hub',
            __('Plugins', 'ai-workflow-automation-ai-agent-hub'),
            __('Plugins', 'ai-workflow-automation-ai-agent-hub'),
            'manage_options',
            $menu_slug,
            array($this, 'atlas_plugins_page'),
            34
        );
    }

    /**
     * AJAX handler to refresh plugin data from remote.
     */
    public function ajax_refresh_plugins() {
        check_ajax_referer('atlas_plugins_refresh', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized', 403);
        }

        // Delete cached data and re-fetch.
        delete_transient(self::ATLAS_PLUGINS_TRANSIENT);
        delete_transient(self::ATLAS_PLUGINS_WPORG_TRANSIENT);
        $plugins    = self::get_atlas_plugins();
        $wporg_info = self::get_wporg_info($plugins);

        wp_send_json_success(array(
            'plugins'    => $plugins,
            'wporg_info' => $wporg_info,
        ));
    }

    /**
     * Atlas Plugins page callback.
     */
    public function atlas_plugins_page()
    {
        echo '<div class="wrap"><div id="atlas_plugins_container"></div></div>';
    }
}
