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

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\OAuth\OAuth_Server;
use AtlasAiDev\Awfah\OAuth\OAuth_Repository;

/**
 * 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' ]
        );

        // Link to the WordPress AI Connectors screen (built dynamically so it
        // resolves correctly on any site). No callback — the slug is an existing
        // admin page, so WordPress renders this submenu item as a direct link.
        add_submenu_page(
            'ai-workflow-automation-ai-agent-hub',
            __( 'AI Connectors', 'ai-workflow-automation-ai-agent-hub' ),
            __( 'AI Connectors', 'ai-workflow-automation-ai-agent-hub' ),
            'manage_options',
            'options-connectors.php'
        );

        $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;
        }

        $oauth_notice = '';
        if ( 'POST' === ( $_SERVER['REQUEST_METHOD'] ?? 'GET' ) ) {
            $oauth_notice = $this->handle_oauth_admin();
        }
        ?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
            <?php $this->render_oauth_section( $oauth_notice ); ?>
            <div id="awfah-settings-app"></div>
        </div>
        <?php
    }

    /**
     * Render the built-in OAuth 2.1 "one-click connect" panel (AI-9 / P7).
     *
     * @param string $notice Optional success notice from a prior action.
     * @return void
     */
    private function render_oauth_section( string $notice = '' ): void {
        $oauth_enabled = OAuth_Server::is_enabled();
        $oauth_clients = OAuth_Repository::list_clients();
        $mcp           = \AtlasAiDev\Awfah\Plugin::get_mcp_settings();
        $connect_url   = rest_url( ( $mcp['namespace'] ?? 'awfah_mcp' ) . '/' . ( $mcp['route'] ?? 'mcp' ) );
        ?>
        <div class="card" style="max-width:780px;padding:4px 20px 16px;margin-top:16px;">
            <h2><?php esc_html_e( 'One-click OAuth 2.1 connect (recommended)', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
            <p class="description">
                <?php esc_html_e( 'Let Claude, ChatGPT, Cursor and other MCP clients connect by pasting only your server URL — no manual tokens. Uses OAuth 2.1 with PKCE and dynamic client registration.', 'ai-workflow-automation-ai-agent-hub' ); ?>
            </p>
            <p style="margin:6px 0 0;">
                <a href="<?php echo esc_url( 'https://atlasaidev.com/docs/atlas-ai-connector/usage-setup/connect-claude-to-wordpress-oauth/?utm_source=atlas-ai-connector&utm_medium=plugin&utm_campaign=documentation&utm_content=oauth_guide' ); ?>" target="_blank" rel="noopener noreferrer">
                    <span class="dashicons dashicons-book-alt" style="vertical-align:text-bottom;"></span>
                    <?php esc_html_e( 'Read the full guide: Connect Claude to WordPress with OAuth', 'ai-workflow-automation-ai-agent-hub' ); ?> &rarr;
                </a>
            </p>

            <?php if ( '' !== $notice ) : ?>
                <div class="notice notice-success is-dismissible inline"><p><?php echo esc_html( $notice ); ?></p></div>
            <?php endif; ?>

            <form method="post">
                <?php wp_nonce_field( 'awfah_oauth_admin', 'awfah_oauth_admin_nonce' ); ?>
                <input type="hidden" name="awfah_oauth_action" value="save_enable" />
                <p>
                    <label>
                        <input type="checkbox" name="oauth_enabled" value="1" <?php checked( $oauth_enabled ); ?> />
                        <strong><?php esc_html_e( 'Enable OAuth 2.1 connect for the MCP server', 'ai-workflow-automation-ai-agent-hub' ); ?></strong>
                    </label>
                    &nbsp;<button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                </p>
            </form>

            <?php if ( $oauth_enabled ) : ?>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Add to your AI client', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                        <td>
                            <code><?php echo esc_html( $connect_url ); ?></code>
                            <button type="button" class="button awfah-oauth-copy" data-copy="<?php echo esc_attr( $connect_url ); ?>"><?php esc_html_e( 'Copy', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                            <p class="description"><?php esc_html_e( 'Paste as a custom/remote MCP connector; the client discovers auth and runs consent automatically. Remote clients (e.g. Claude.ai) require your site to be served over HTTPS.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Discovery', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                        <td><code><?php echo esc_html( home_url( '/.well-known/oauth-protected-resource' ) ); ?></code></td>
                    </tr>
                </table>

                <h3><?php esc_html_e( 'Connected clients', 'ai-workflow-automation-ai-agent-hub' ); ?></h3>
                <?php if ( empty( $oauth_clients ) ) : ?>
                    <p class="description"><?php esc_html_e( 'No clients have registered yet. Connect one from your AI client to see it here.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                <?php else : ?>
                    <table class="widefat striped" style="max-width:720px;">
                        <thead><tr>
                            <th><?php esc_html_e( 'Client', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                            <th><?php esc_html_e( 'Granted scope', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                            <th><?php esc_html_e( 'Registered (UTC)', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                            <th></th>
                        </tr></thead>
                        <tbody>
                            <?php foreach ( $oauth_clients as $client ) : ?>
                                <?php
                                // Show the active token's granted scope (what the connection can
                                // actually do now), not the client's broader registration scope.
                                $granted_scope = OAuth_Repository::latest_token_scope( $client['client_id'] );
                                $scope_label   = ( null !== $granted_scope && '' !== $granted_scope ) ? $granted_scope : ( $client['scope'] . ' (registered; no active token)' );
                                ?>
                                <tr>
                                    <td><?php echo esc_html( '' !== $client['client_name'] ? $client['client_name'] : $client['client_id'] ); ?></td>
                                    <td><code><?php echo esc_html( $scope_label ); ?></code></td>
                                    <td><?php echo esc_html( $client['created'] ); ?></td>
                                    <td>
                                        <form method="post" onsubmit="return confirm('<?php echo esc_js( __( 'Revoke this client and all its tokens?', 'ai-workflow-automation-ai-agent-hub' ) ); ?>');">
                                            <?php wp_nonce_field( 'awfah_oauth_admin', 'awfah_oauth_admin_nonce' ); ?>
                                            <input type="hidden" name="awfah_oauth_action" value="revoke" />
                                            <input type="hidden" name="client_id" value="<?php echo esc_attr( $client['client_id'] ); ?>" />
                                            <button type="submit" class="button button-link-delete"><?php esc_html_e( 'Revoke', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
                <script>
                document.addEventListener('click',function(e){
                    if(!e.target.classList.contains('awfah-oauth-copy'))return;
                    var v=e.target.getAttribute('data-copy')||'';
                    if(navigator.clipboard){navigator.clipboard.writeText(v);}
                    var t=e.target.textContent;e.target.textContent='<?php echo esc_js( __( 'Copied', 'ai-workflow-automation-ai-agent-hub' ) ); ?>';
                    setTimeout(function(){e.target.textContent=t;},1200);
                });
                </script>

                <?php if ( function_exists( 'awfah_is_pro_active' ) && awfah_is_pro_active() ) { $this->render_role_policy(); } ?>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Render the per-role OAuth policy panel (Pro). Lets admins choose which roles
     * may authorize an MCP connection and which scopes each role may grant. Saved to
     * awfah_oauth_settings['role_policy']; enforced by Pro's OAuth_Policy. AI-9 / #4.
     *
     * @return void
     */
    private function render_role_policy(): void {
        if ( ! function_exists( 'get_editable_roles' ) ) {
            require_once ABSPATH . 'wp-admin/includes/user.php';
        }
        $roles  = get_editable_roles();
        $scopes = \AtlasAiDev\Awfah\OAuth\OAuth_Server::scopes();
        $policy = (array) ( get_option( 'awfah_oauth_settings', array() )['role_policy'] ?? array() );
        ?>
        <h3><?php esc_html_e( 'Per-role OAuth policy', 'ai-workflow-automation-ai-agent-hub' ); ?> <span class="awfah-pro-badge" style="font-size:11px;background:#ede9fe;color:#6d28d9;padding:1px 6px;border-radius:9px;">PRO</span></h3>
        <p class="description"><?php esc_html_e( 'Choose which roles may authorize an MCP connection and which scopes each role can grant. Leave a role unconfigured to fall back to the default (capability gate).', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
        <form method="post">
            <?php wp_nonce_field( 'awfah_oauth_admin', 'awfah_oauth_admin_nonce' ); ?>
            <input type="hidden" name="awfah_oauth_action" value="save_role_policy" />
            <table class="widefat striped" style="max-width:720px;">
                <thead><tr>
                    <th><?php esc_html_e( 'Role', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                    <th><?php esc_html_e( 'Can authorize', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                    <th><?php esc_html_e( 'Grantable scopes', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                </tr></thead>
                <tbody>
                    <?php foreach ( $roles as $slug => $details ) : ?>
                        <?php
                        $cfg          = $policy[ $slug ] ?? array();
                        $role_obj     = get_role( $slug );
                        $can_default  = $role_obj && $role_obj->has_cap( 'edit_posts' );
                        $can_checked  = array_key_exists( 'can_authorize', $cfg ) ? ! empty( $cfg['can_authorize'] ) : $can_default;
                        $role_scopes  = isset( $cfg['scopes'] ) && is_array( $cfg['scopes'] ) ? $cfg['scopes'] : $scopes; // default: all
                        ?>
                        <tr>
                            <td><strong><?php echo esc_html( $details['name'] ); ?></strong><input type="hidden" name="policy_roles[]" value="<?php echo esc_attr( $slug ); ?>" /></td>
                            <td><input type="checkbox" name="can_authorize[<?php echo esc_attr( $slug ); ?>]" value="1" <?php checked( $can_checked ); ?> /></td>
                            <td>
                                <?php foreach ( $scopes as $scope ) : ?>
                                    <label style="margin-right:10px;white-space:nowrap;">
                                        <input type="checkbox" name="grant_scopes[<?php echo esc_attr( $slug ); ?>][]" value="<?php echo esc_attr( $scope ); ?>" <?php checked( in_array( $scope, $role_scopes, true ) ); ?> />
                                        <code><?php echo esc_html( $scope ); ?></code>
                                    </label>
                                <?php endforeach; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <p><button type="submit" class="button button-primary"><?php esc_html_e( 'Save role policy', 'ai-workflow-automation-ai-agent-hub' ); ?></button></p>
        </form>
        <?php
    }

    /**
     * Handle OAuth 2.1 admin actions (enable toggle, revoke client). AI-9 / P7.
     *
     * @return string Notice message, or '' if nothing was done.
     */
    private function handle_oauth_admin(): string {
        if ( empty( $_POST['awfah_oauth_admin_nonce'] ) ) {
            return '';
        }
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['awfah_oauth_admin_nonce'] ) ), 'awfah_oauth_admin' ) ) {
            return '';
        }
        if ( ! current_user_can( 'manage_options' ) ) {
            return '';
        }

        $action = isset( $_POST['awfah_oauth_action'] ) ? sanitize_text_field( wp_unslash( $_POST['awfah_oauth_action'] ) ) : '';

        if ( 'save_enable' === $action ) {
            $settings            = (array) get_option( 'awfah_oauth_settings', array() );
            $settings['enabled'] = ! empty( $_POST['oauth_enabled'] );
            update_option( 'awfah_oauth_settings', $settings );
            return $settings['enabled']
                ? __( 'OAuth 2.1 connect enabled.', 'ai-workflow-automation-ai-agent-hub' )
                : __( 'OAuth 2.1 connect disabled.', 'ai-workflow-automation-ai-agent-hub' );
        }

        if ( 'revoke' === $action ) {
            $client_id = isset( $_POST['client_id'] ) ? sanitize_text_field( wp_unslash( $_POST['client_id'] ) ) : '';
            if ( '' !== $client_id ) {
                OAuth_Repository::delete_client( $client_id );
                return __( 'Client revoked.', 'ai-workflow-automation-ai-agent-hub' );
            }
        }

        if ( 'save_role_policy' === $action ) {
            $settings       = (array) get_option( 'awfah_oauth_settings', array() );
            $roles_in       = isset( $_POST['policy_roles'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['policy_roles'] ) ) : array();
            $can            = isset( $_POST['can_authorize'] ) ? (array) wp_unslash( $_POST['can_authorize'] ) : array();
            $scopes_in      = isset( $_POST['grant_scopes'] ) ? (array) wp_unslash( $_POST['grant_scopes'] ) : array();
            $allowed_scopes = OAuth_Server::scopes();

            $role_policy = array();
            foreach ( $roles_in as $role ) {
                $posted_scopes        = isset( $scopes_in[ $role ] ) ? array_map( 'sanitize_text_field', (array) $scopes_in[ $role ] ) : array();
                $role_policy[ $role ] = array(
                    'can_authorize' => ! empty( $can[ $role ] ),
                    'scopes'        => array_values( array_intersect( $posted_scopes, $allowed_scopes ) ),
                );
            }
            $settings['role_policy'] = $role_policy;
            update_option( 'awfah_oauth_settings', $settings );
            return __( 'OAuth role policy saved.', 'ai-workflow-automation-ai-agent-hub' );
        }

        return '';
    }

    /**
     * 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-connectors.php' ) . '">' . __( 'AI Connectors', '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'          => 'AtlasAI Connector',
                '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/atlas-ai-connector-pro/?utm_source=atlas-ai-connector&utm_medium=plugin&utm_campaign=pro_upgrade&utm_content=plugins_directory',
                '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',
            __('Our Plugins', 'ai-workflow-automation-ai-agent-hub'),
            __('Our 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>';
    }
}
