<?php

declare(strict_types=1);

namespace FleekDash\API;

use FleekDash\Core\AuthMiddleware;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * Capability Validation API
 *
 * Provides server-side capability validation for menu items and developer access.
 *
 * @package FleekDash\API
 */
class CapabilityValidationAPI
{
    private const ROUTE_NAMESPACE = 'fleekdash/v1';

    /**
     * Register REST API routes
     */
    public function registerRoutes(): void
    {
        // Check single capability
        \register_rest_route(self::ROUTE_NAMESPACE, '/auth/check-capability', [
            'methods' => 'POST',
            'callback' => [$this, 'checkCapability'],
            'permission_callback' => [$this, 'checkPermissions'],
            'args' => [
                'capability' => [
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                    'description' => 'The capability to check'
                ],
                'menu_item_id' => [
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                    'description' => 'Menu item ID for context'
                ],
                'menu_item_name' => [
                    'required' => false,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                    'description' => 'Menu item name for context'
                ],
                'is_developer_check' => [
                    'required' => false,
                    'type' => 'boolean',
                    'default' => false,
                    'description' => 'Whether this is a developer capability check'
                ]
            ]
        ]);

        // Check multiple capabilities at once
        \register_rest_route(self::ROUTE_NAMESPACE, '/auth/check-capabilities', [
            'methods' => 'POST',
            'callback' => [$this, 'checkMultipleCapabilities'],
            'permission_callback' => [$this, 'checkPermissions'],
            'args' => [
                'capabilities' => [
                    'required' => true,
                    'type' => 'array',
                    'items' => [
                        'type' => 'string'
                    ],
                    'sanitize_callback' => function($capabilities) {
                        return array_map('sanitize_text_field', $capabilities);
                    },
                    'description' => 'Array of capabilities to check'
                ]
            ]
        ]);

        // Get current user capabilities summary
        \register_rest_route(self::ROUTE_NAMESPACE, '/auth/user-capabilities', [
            'methods' => 'GET',
            'callback' => [$this, 'getUserCapabilities'],
            'permission_callback' => [$this, 'checkPermissions']
        ]);
    }

    /**
     * Check permissions for capability validation endpoints
     *
     * @return bool
     */
    public function checkPermissions(): bool
    {
        // Use AuthMiddleware with graceful fallback
        try {
            $auth_check = AuthMiddleware::check('authenticated');
            if (!$auth_check['authenticated']) {
            // Debug-only: unauthenticated access attempt
            fleekdash_log_debug("FleekDash: Capability API access without auth - Reason: " . $auth_check['reason']);
                // Graceful fallback: continue (empty capability set downstream)
            }
        } catch (\Exception $e) {
            // Log e continuar - graceful degradation
            fleekdash_log_error("FleekDash: AuthMiddleware error in Capability API: " . $e->getMessage());
        }

        // Always return true for graceful fallback
        return true;
    }

    /**
     * Check single capability
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function checkCapability(WP_REST_Request $request)
    {
        $response = null;
        try {
            $capability = $request->get_param('capability');
            $menu_item_id = $request->get_param('menu_item_id');
            $menu_item_name = $request->get_param('menu_item_name');
            $is_developer_check = $request->get_param('is_developer_check');

            $validation_error = $this->validateCapabilityInput($capability);
            if ($validation_error instanceof WP_Error) {
                $response = $validation_error;
            } else {
                $user_id = \get_current_user_id();
                $current_user = \wp_get_current_user();
                $user_role = ($current_user && !empty($current_user->roles) && is_array($current_user->roles)) ? $current_user->roles[0] : 'none';

                // Check if user is logged in
                if (!$user_id || !\is_user_logged_in()) {
                    $response = $this->buildNotLoggedInCapabilityResponse((string) $capability);
                } else {
                    // Perform capability check
                    $has_capability = \current_user_can($capability);

                    // LEGACY FEATURE DISABLED - No special handling for developer capability
                    // All capabilities now use standard WordPress capability system

                    $response = $this->buildCapabilitySuccessResponse(
                        (string) $capability,
                        (bool) $has_capability,
                        (int) $user_id,
                        (string) $user_role,
                        $menu_item_id,
                        $menu_item_name,
                        $is_developer_check,
                    );
                }
            }
        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash Capability Check Error: " . $e->getMessage());
            $response = new WP_Error('capability_check_failed', 'Internal server error during capability check', ['status' => 500]);
        }

        return $response;
    }

    private function validateCapabilityInput(mixed $capability): ?WP_Error
    {
        $error = null;
        if (empty($capability)) {
            $error = new WP_Error('missing_capability', 'Capability parameter is required', ['status' => 400]);
        } elseif (!is_string($capability) || strlen($capability) > 100) {
            $error = new WP_Error('invalid_capability', 'Capability must be a valid string (max 100 chars)', ['status' => 400]);
        }

        return $error;
    }

    private function buildNotLoggedInCapabilityResponse(string $capability): WP_REST_Response
    {
        return \rest_ensure_response([
            'success' => false,
            'data' => [
                'capability' => $capability,
                'has_capability' => false,
                'user_id' => 0,
                'user_role' => 'none',
                'reason' => 'not_logged_in'
            ]
        ]);
    }

    private function buildCapabilitySuccessResponse(
        string $capability,
        bool $has_capability,
        int $user_id,
        string $user_role,
        mixed $menu_item_id,
        mixed $menu_item_name,
        mixed $is_developer_check
    ): WP_REST_Response {
        // Log capability check for debugging
        $context = $menu_item_name ? " for menu item '{$menu_item_name}'" : '';
        fleekdash_log_debug(sprintf(
            'FleekDash Capability Check: User %d (%s) %s capability "%s"%s',
            $user_id,
            $user_role,
            $has_capability ? 'HAS' : 'LACKS',
            $capability,
            $context
        ));

        return \rest_ensure_response([
            'success' => true,
            'data' => [
                'capability' => $capability,
                'has_capability' => $has_capability,
                'user_id' => $user_id,
                'user_role' => $user_role,
                'menu_item_id' => $menu_item_id,
                'menu_item_name' => $menu_item_name,
                'is_developer_check' => $is_developer_check,
                'timestamp' => time()
            ]
        ]);
    }

    /**
     * Check multiple capabilities at once
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function checkMultipleCapabilities(WP_REST_Request $request)
    {
        try {
            $capabilities = $request->get_param('capabilities');

            if (!is_array($capabilities) || empty($capabilities)) {
                return new WP_Error('invalid_capabilities', 'Capabilities must be a non-empty array', ['status' => 400]);
            }

            $user_id = \get_current_user_id();
            $current_user = \wp_get_current_user();
            $user_role = ($current_user && !empty($current_user->roles) && is_array($current_user->roles)) ? $current_user->roles[0] : 'none';

            $results = [];

            foreach ($capabilities as $capability) {
                if (is_string($capability) && !empty($capability)) {
                    $has_capability = \current_user_can($capability);

                    // LEGACY FEATURE DISABLED - No special handling for developer capability
                    // All capabilities now use standard WordPress capability system

                    $results[$capability] = [
                        'has_capability' => $has_capability,
                        'capability' => $capability
                    ];
                }
            }

            // Create simplified results object for frontend
            $simpleResults = [];
            foreach ($results as $capability => $data) {
                $simpleResults[$capability] = $data['has_capability'];
            }

            return \rest_ensure_response([
                'success' => true,
                'data' => [
                    'results' => $simpleResults, // Frontend expects 'results'
                    'capabilities' => $results, // Full data for debugging
                    'user_id' => $user_id,
                    'user_role' => $user_role,
                    'capabilities_checked' => count($results),
                    'timestamp' => time()
                ]
            ]);

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash Multiple Capability Check Error: " . $e->getMessage());
            return new WP_Error('capability_check_failed', 'Internal server error during capability check', ['status' => 500]);
        }
    }

    /**
     * Get current user capabilities summary
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response|WP_Error
     */
    public function getUserCapabilities(WP_REST_Request $request)
    {
        unset($request);
        try {
            $user_id = \get_current_user_id();
            $current_user = \wp_get_current_user();

            if (!$user_id || !\is_user_logged_in()) {
                return \rest_ensure_response([
                    'success' => false,
                    'data' => [
                        'user_id' => 0,
                        'user_role' => 'none',
                        'capabilities' => [],
                        'reason' => 'not_logged_in'
                    ]
                ]);
            }

            $user_role = ($current_user && !empty($current_user->roles) && is_array($current_user->roles)) ? $current_user->roles[0] : 'none';
            $all_capabilities = $current_user->allcaps ?? [];
            $user_capabilities = array_keys(array_filter($all_capabilities));

            // LEGACY FEATURE DISABLED - No special developer access check
            $has_developer_access = false; // Disabled

            return \rest_ensure_response([
                'success' => true,
                'data' => [
                    'user_id' => $user_id,
                    'user_role' => $user_role,
                    'user_login' => $current_user->user_login ?? '',
                    'user_email' => $current_user->user_email ?? '',
                    'capabilities' => $user_capabilities,
                    'total_capabilities' => count($user_capabilities),
                    'has_developer_access' => $has_developer_access,
                    'timestamp' => time()
                ]
            ]);

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash User Capabilities Error: " . $e->getMessage());
            return new WP_Error('user_capabilities_failed', 'Internal server error getting user capabilities', ['status' => 500]);
        }
    }

    /**
     * Check if user has developer access
     * LEGACY METHOD - REMOVED
     */
    // LEGACY METHOD REMOVED - Using standard WordPress capabilities only
}
