<?php
/**
 * Admin Data Formatter
 *
 * Shared formatting utilities for Menu and Toolbar APIs
 * Provides consistent field structure across both APIs
 *
 * @package FleekDash\API
 * @since V2.2
 */

namespace FleekDash\API;

/**
 * Admin Data Formatter
 *
 * Common formatting logic for menu and toolbar items
 * Ensures consistent field names and structure
 *
 * @package FleekDash\API
 * @since V2.2
 */
class AdminDataFormatter
{
    /**
     * Add backward compatibility fields to items
     *
     * Adds: title (copy of name), id (copy of unique_id), icon field
     *
     * @param array $items Items to add compatibility fields to
     * @return array Items with compatibility fields
     */
    public static function addBackwardCompatibility(array $items): array
    {
        foreach ($items as &$item) {
            // Add 'title' as alias for 'name' (backward compatibility)
            if (isset($item['name']) && !isset($item['title'])) {
                $item['title'] = $item['name'];
            }

            // Add 'id' as alias for 'unique_id' (backward compatibility)
            if (isset($item['unique_id']) && !isset($item['id'])) {
                $item['id'] = $item['unique_id'];
            }

            // Ensure icon exists
            if (!isset($item['icon'])) {
                $item['icon'] = 'default';
            }

            // Process submenu recursively
            if (isset($item['submenu']) && is_array($item['submenu'])) {
                $item['submenu'] = self::addBackwardCompatibility($item['submenu']);
            }
        }

        return $items;
    }

    /**
     * Load WordPress admin files
     *
     * Required for menu.php and admin bar functionality
     *
     * @return void
     */
    public static function loadAdminFiles(): void
    {
        // Load template functions (includes remove_meta_box, etc)
        if (!function_exists('remove_meta_box')) {
            require_once ABSPATH . 'wp-admin/includes/template.php';
        }

        // Load plugin functions (includes get_plugin_data, etc.)
        if (!\function_exists('get_plugin_data')) {
            \FleekDash\Core\PluginHelper::ensurePluginApiLoaded();
        }
    }

    /**
     * Build error response for invalid role
     *
     * @param string $role The invalid role
     * @param array $available_roles Available roles
     * @return \WP_Error
     */
    public static function buildInvalidRoleError(string $role, array $available_roles): \WP_Error
    {
        return new \WP_Error(
            'invalid_role',
            sprintf(
                'Invalid role: %s. Available roles: %s',
                $role,
                implode(', ', array_keys($available_roles))
            ),
            ['status' => 400]
        );
    }

    /**
     * Build error response for no users found
     *
     * @param string $role The role with no users
     * @return \WP_Error
     */
    public static function buildNoUsersError(string $role): \WP_Error
    {
        return new \WP_Error(
            'no_users_found',
            sprintf('No users found with role: %s', $role),
            ['status' => 404]
        );
    }

    /**
     * Get first user with specific role
     *
     * @param string $role Role slug
     * @return \WP_User|null
     */
    public static function getUserByRole(string $role): ?\WP_User
    {
        $users = get_users([
            'role' => $role,
            'number' => 1,
            'orderby' => 'ID',
            'order' => 'ASC'
        ]);

        return !empty($users) ? $users[0] : null;
    }

    /**
     * Validate role exists
     *
     * @param string $role Role slug
     * @return bool
     */
    public static function isValidRole(string $role): bool
    {
        $available_roles = wp_roles()->get_names();
        return in_array($role, array_keys($available_roles));
    }

    /**
     * Get available WordPress roles
     *
     * @return array Role slugs => Role names
     */
    public static function getAvailableRoles(): array
    {
        return wp_roles()->get_names();
    }
}
