<?php

namespace FleekDash\API;

use FleekDash\Core\AuthMiddleware;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Plugin Detection API
 *
 * Detects active plugins and their associated roles dynamically
 */
class PluginDetectionAPI
{
    /**
     * Constructor
     *
     * Migrated (v2.2): PluginsRoutes (Phase 2)
     * register_routes() call removed - routes now registered via PluginsController
     */
    public function __construct()
    {
        // Register routes immediately since we're instantiated during rest_api_init
        // $this->register_routes();
    }

    /**
     * Register REST API routes
     */
    public function register_routes()
    {
        // Get plugin role patterns
        \register_rest_route('fleekdash/v1', '/plugin-roles', [
            'methods' => 'GET',
            'callback' => [$this, 'get_plugin_role_patterns'],
            'permission_callback' => [$this, 'check_permissions']
        ]);

        // Get active plugins with their roles
        \register_rest_route('fleekdash/v1', '/active-plugins', [
            'methods' => 'GET',
            'callback' => [$this, 'get_active_plugins'],
            'permission_callback' => [$this, 'check_permissions']
        ]);
    }

    /**
     * Check permissions with AuthMiddleware and graceful fallback
     */
    public function check_permissions()
    {
        try {
            $auth_check = AuthMiddleware::check('admin');
            if (!$auth_check['authenticated']) {
                fleekdash_log_debug("FleekDash: Plugin Detection API access without auth - Reason: " . $auth_check['reason']);
            }
        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: AuthMiddleware error in Plugin Detection API: " . $e->getMessage());
        }

        return true;
    }

    /**
     * Get plugin role patterns
     */
    public function get_plugin_role_patterns(WP_REST_Request $request)
    {
        try {
            $patterns = $this->detect_plugin_role_patterns();

            return \rest_ensure_response([
                'success' => true,
                'data' => $patterns
            ]);
        } catch (\Exception $e) {
            return new WP_Error('get_patterns_failed', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get active plugins with their roles
     */
    public function get_active_plugins(WP_REST_Request $request)
    {
        try {
            $active_plugins = $this->get_active_plugins_with_roles();

            return \rest_ensure_response([
                'success' => true,
                'data' => $active_plugins
            ]);
        } catch (\Exception $e) {
            return new WP_Error('get_plugins_failed', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Detect plugin role patterns dynamically
     */
    private function detect_plugin_role_patterns()
    {
        $patterns = [];
        $active_plugins = \get_option('active_plugins', []);

        // Get all roles from WordPress
        $wp_roles = wp_roles();
        $all_roles = $wp_roles->get_names();

        // Known plugin patterns (can be extended)
        $plugin_patterns = [
            'woocommerce' => [
                'roles' => ['customer', 'shop_manager'],
                'name' => 'WooCommerce',
                'icon' => 'lucide:shopping-cart'
            ],
            'bbpress' => [
                'roles' => ['bbp_keymaster', 'bbp_moderator', 'bbp_participant', 'bbp_spectator', 'bbp_blocked'],
                'name' => 'bbPress',
                'icon' => 'lucide:message-circle'
            ],
            'buddypress' => [
                'roles' => ['bp_moderator', 'bp_member'],
                'name' => 'BuddyPress',
                'icon' => 'lucide:users'
            ],
            'elementor' => [
                'roles' => ['elementor_manager'],
                'name' => 'Elementor',
                'icon' => 'lucide:layers'
            ],
            'gravityforms' => [
                'roles' => ['gravityforms_user'],
                'name' => 'Gravity Forms',
                'icon' => 'lucide:form-input'
            ],
            'wpml' => [
                'roles' => ['wpml_administrator', 'wpml_manager', 'wpml_translator'],
                'name' => 'WPML',
                'icon' => 'lucide:globe'
            ],
            'wpseo' => [
                'roles' => ['wpseo_manager', 'wpseo_editor'],
                'name' => 'Yoast SEO',
                'icon' => 'lucide:search'
            ],
            'jetpack' => [
                'roles' => ['jetpack_admin'],
                'name' => 'Jetpack',
                'icon' => 'lucide:zap'
            ],
            'woocommerce-memberships' => [
                'roles' => ['wc_membership_manager'],
                'name' => 'WooCommerce Memberships',
                'icon' => 'lucide:shield'
            ],
            'woocommerce-subscriptions' => [
                'roles' => ['wc_subscription_manager'],
                'name' => 'WooCommerce Subscriptions',
                'icon' => 'lucide:refresh-cw'
            ]
        ];

        // Check which plugins have roles present (role-based detection)
        foreach ($plugin_patterns as $plugin_key => $plugin_data) {
            $active_roles = array_intersect($plugin_data['roles'], array_keys($all_roles));
            if (!empty($active_roles)) {
                $patterns[$plugin_key] = [
                    'name' => $plugin_data['name'],
                    'icon' => $plugin_data['icon'],
                    'roles' => $active_roles,
                    'active' => true // Always true if roles are present
                ];

            }
        }

        // Add custom roles (roles that don't match any plugin pattern)
        $custom_roles = [];
        $known_roles = array_merge(...array_column($plugin_patterns, 'roles'));
        $known_roles = array_merge($known_roles, ['administrator', 'editor', 'author', 'contributor', 'subscriber']);

        foreach ($all_roles as $role_key => $role_name) {
            if (!in_array($role_key, $known_roles)) {
                $custom_roles[$role_key] = [
                    'name' => $role_name,
                    'icon' => 'lucide:user-cog',
                    'type' => 'custom'
                ];
            }
        }

        return [
            'plugin_patterns' => $patterns,
            'custom_roles' => $custom_roles,
            'all_roles' => $all_roles
        ];
    }

    /**
     * Get active plugins with their roles
     */
    private function get_active_plugins_with_roles()
    {
        $active_plugins = [];
        $plugin_patterns = $this->detect_plugin_role_patterns();

        foreach ($plugin_patterns['plugin_patterns'] as $plugin_key => $plugin_data) {
            if ($plugin_data['active']) {
                $active_plugins[] = [
                    'key' => $plugin_key,
                    'name' => $plugin_data['name'],
                    'icon' => $plugin_data['icon'],
                    'roles' => $plugin_data['roles']
                ];
            }
        }

        return $active_plugins;
    }

    /**
     * Check if a plugin is active
     */
    private function is_plugin_active($plugin_key)
    {
        $active_plugins = \get_option('active_plugins', []);

        // Defensive: Ensure $active_plugins is iterable (get_option can return false)
        if (!is_array($active_plugins)) {
            $active_plugins = [];
        }

        // Check for exact plugin file match
        foreach ($active_plugins as $plugin) {
            if (strpos($plugin, $plugin_key . '/') === 0) {
                return true;
            }
        }

        // Check for plugin directory match
        $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_key;
        if (is_dir($plugin_dir)) {
            // Check if any PHP file in the directory is active
            foreach ($active_plugins as $plugin) {
                if (strpos($plugin, $plugin_key . '/') === 0) {
                    return true;
                }
            }
        }

        return false;
    }
}
