<?php

namespace GemBoards\Ajax;

use GemBoards\Classes\AbstractAjaxHandler;

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

class BoardMembers extends AbstractAjaxHandler {

	/**
	 * @TODO: `add_member`, `get_board_members` and `remove_member` should be implemented on later.
	 */
	public function __construct() {
		$this->actions = [
			'get_user' => [ //@TODO: Remove this after implementing API to get all users
				'callback'   => [ $this, 'get_user' ],
				'capability' => 'list_users',
				'fields'     => [
					'email' => 'string',
				],
			],
		];
	}

	public function get_user( $request ) {
		// @TODO: Remove this after implementing API to get all users
		$email = $request['email'];
		if ( ! $email ) {
			wp_send_json_error( __( 'Email is required', 'gemboards' ) );
		}

		$user = get_user_by( 'email', $email );
		if ( ! $user ) {
			wp_send_json_error( __( 'User not found', 'gemboards' ) );
		}

		wp_send_json_success( [
			'ID'       => $user->ID,
			'username' => $user->user_login,
			'email'    => $user->user_email,
			'name'     => $user->display_name,
			'role'     => $user->roles,
			'avatar'   => get_avatar_url( $user->ID ),
		] );
	}

}
