<?php
/**
 * Plugin Name:  Wiaas restful API 
 * Plugin URI: http://www.saburly.com/
 * Description:A custom wordpress REST extension for wiass 
 * Version: 0.1
 * Author: Sabury
 * Author URI: http://www.saburly.com/
 * Text Domain: wiaas
 *
 * @package Wiass
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Fetch user by id
 *
 * @param array $data Options for the function.
 * @return string|null User object from DB or null if user there is no uset with that id.
 */
function fetch_user_by_id( $data ) {
 $user =  get_user_by( 'id', $data['id'] );
 
  if ( empty( $user ) ) {

    return wp_get_current_user();
  }
 
  return $user;
}

/**
 * Fetch current user
 *
 * @return string|null User object from DB or null if user there is no uset with that id.
 */
function fetch_current_user( $data ) {
    if ( empty( wp_get_current_user() ) ) {

        return null;
    }

    return wp_get_current_user();
}

function check_permission($request) {
    return current_user_can( 'do_the_broking' );
}

add_action('rest_api_init', function () {
    register_rest_route('wiaas/v1', '/user/(?P<id>\d+)', array(
        'methods' => 'GET',
        'permission_callback' =>  'check_permission',
        'callback' => 'fetch_user_by_id',
    ));
});

add_action('rest_api_init', function () {
    register_rest_route('wiaas/v1', '/user', array(
        'methods' => 'GET',
        'permission_callback' =>  'check_permission',
        'callback' => 'fetch_user_by_id',
    ));
});
