<?php

namespace ModernFields\WordPress\Endpoints;

use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Traits\ChecksPermissions;

use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

/**
 * Handles REST API endpoints for WordPress user roles.
 *
 * @since 1.0.0
 */
class Roles implements Hooks
{
  use ChecksPermissions;

  /**
   * @since 1.0.0
   */
  public function registerHooks(): void
  {
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  /**
   * @since 1.0.0
   */
  public function registerRestEndpoints(): void
  {
    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/roles', [
      'methods'             => 'GET',
      'callback'            => [$this, 'getRoles'],
      'permission_callback' => [$this, 'checkPermissions'],
    ]);
  }

  /**
   * @since 1.0.0
   */
  public function getRoles(WP_REST_Request $request): WP_REST_Response
  {
    $wp_roles = wp_roles();
    $roles = [];

    foreach ($wp_roles->roles as $role_key => $role_details) {
      $roles[] = [
        'slug'         => $role_key,
        'name'         => translate_user_role($role_details['name']),
        'capabilities' => array_keys(array_filter($role_details['capabilities'])),
      ];
    }

    return rest_ensure_response([
      'roles' => $roles,
    ]);
  }


}
