<?php
/**
 * Plugin Name: MCP Server for WordPress – Connect Claude, ChatGPT & Gemini | AtlasAI Connector
 * Plugin URI:  https://atlasaidev.com/
 * Description: MCP server for WordPress to connect Claude, ChatGPT & Gemini via one-click OAuth (PKCE + dynamic client registration). 80+ AI abilities, block editor AI experiments, RBAC, workflow builder, and WooCommerce support.
 * Version:     1.6.6
 * Author:      Azizul Hasan
 * Author URI:  https://atlasaidev.com
 * Text Domain: ai-workflow-automation-ai-agent-hub
 * Domain Path: /languages
 * Requires PHP: 7.4
 * Requires at least: 6.8
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

//// Composer autoloader.
//$awfah_autoload = __DIR__ . '/vendor/autoload.php';

// Load the Jetpack autoloader instead of vendor/autoload.php
$awfah_autoload =  plugin_dir_path(__FILE__) . 'vendor/autoload_packages.php';

if ( file_exists( $awfah_autoload ) ) {
    require_once $awfah_autoload;
} else {
    // Optional: admin notice if vendor missing.
    add_action(
        'admin_notices',
        static function () {
            if ( current_user_can( 'manage_options' ) ) {
                echo '<div class="notice notice-error"><p>';
                echo 'AtlasAI Connector: ' . esc_html__( 'Composer dependencies are missing. Please run "composer install".', 'ai-workflow-automation-ai-agent-hub' );
                echo '</p></div>';
            }
        }
    );
    return;
}

/*
 * AI Client SDK loading (WordPress 7.0 compatibility).
 *
 * WordPress 7.0 ships the AI Client in core (function wp_ai_client_prompt()), with the
 * SDK under WordPress\AiClient\* and its third-party deps scoped to
 * WordPress\AiClientDependencies\*. To avoid the bundled (unscoped) copy hijacking and
 * breaking core's classes, the bundled WordPress\AiClient\* / WordPress\AI_Client\*
 * classes are excluded from the Jetpack autoloader (see bin/strip-ai-client-autoload.php).
 *
 * On WordPress < 7.0 there is no core AI Client, so register the bundled SDK here so the
 * plugin's AI features keep working. On 7.0+ this is skipped and core is used.
 */
if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
    spl_autoload_register(
        static function ( $class ) {
            static $map = array(
                'WordPress\\AiClient\\'  => __DIR__ . '/vendor/wordpress/php-ai-client/src/',
                'WordPress\\AI_Client\\' => __DIR__ . '/vendor/wordpress/wp-ai-client/includes/',
            );
            foreach ( $map as $prefix => $base_dir ) {
                $len = strlen( $prefix );
                if ( strncmp( $class, $prefix, $len ) !== 0 ) {
                    continue;
                }
                $file = $base_dir . str_replace( '\\', '/', substr( $class, $len ) ) . '.php';
                if ( is_readable( $file ) ) {
                    require $file;
                }
                return;
            }
        }
    );
}


// Ensure the Abilities API is loaded when installed as a Composer dependency.
$abilities_bootstrap = plugin_dir_path( __FILE__ ) . 'vendor/wordpress/abilities-api/abilities-api.php';
if ( ! function_exists( 'wp_register_ability' ) && file_exists( $abilities_bootstrap ) ) {
    require_once $abilities_bootstrap;
}

// Load pro-helpers before anything else.
require_once __DIR__ . '/src/Helpers/pro-helpers.php';

// Load the AtlasAiDev usage tracker wrapper (opt-in telemetry).
require_once __DIR__ . '/src/Service/AtlasAiDev_Tracker.php';

// Load the data-driven admin notices system.
require_once __DIR__ . '/src/Admin/Notices.php';

// Load the OAuth 2.1 server (AI-9). Gated behind awfah_oauth_settings['enabled'].
require_once __DIR__ . '/src/OAuth/OAuth_Repository.php';
require_once __DIR__ . '/src/OAuth/Registration_Controller.php';
require_once __DIR__ . '/src/OAuth/Authorize_Controller.php';
require_once __DIR__ . '/src/OAuth/Token_Controller.php';
require_once __DIR__ . '/src/OAuth/Token_Validator.php';
require_once __DIR__ . '/src/OAuth/OAuth_Server.php';

use AtlasAiDev\Awfah\Plugin;
use WordPress\AI_Client\AI_Client;

// Initialize WP AI Client.
add_action(
    'init',
    static function () {
        if ( class_exists( AI_Client::class ) ) {
            AI_Client::init();
        }
    }
);

// Bootstrap plugin.
add_action(
    'plugins_loaded',
    static function () {
        Plugin::instance();
    }
);

/**
 * Record when the plugin was first activated. Used to time the review-request
 * admin notice (shown 7+ days after activation).
 *
 * Set once and never overwritten. The activation hook covers fresh installs;
 * the admin_init backfill covers existing installs updating to this version,
 * since WordPress does not run activation hooks on plugin update.
 */
function awfah_record_activation_timestamp() {
    if ( ! get_option( 'awfah_activated_at' ) ) {
        add_option( 'awfah_activated_at', time(), '', false );
    }
}
register_activation_hook( __FILE__, 'awfah_record_activation_timestamp' );
add_action( 'admin_init', 'awfah_record_activation_timestamp', 5 );

// Initialize the AtlasAiDev usage tracker (opt-in telemetry). Free plugin only —
// when the Pro add-on is active it handles its own telemetry/licensing.
add_action(
    'init',
    static function () {
        if ( function_exists( 'awfah_is_pro_active' ) && awfah_is_pro_active() ) {
            return;
        }
        \AtlasAiDev\Awfah\Service\AtlasAiDev_Tracker::instance()->init();
    },
    9999
);