<?php
/**
 * REST API controller for V1 endpoints.
 *
 * @package Awesomemotive\Rewardswp\Api\V1
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Api\V1;

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

/**
 * Class RestController
 *
 * @package RewardsWP
 */
class RestController extends \WP_REST_Controller {
	/**
	 * REST namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'rewardswp/v1';

	/**
	 * Registers the routes for the objects of the controller.
	 *
	 * @see register_rest_route()
	 */
	public function register_routes() {
		// Example route.
		register_rest_route(
			$this->namespace,
			'/rewards',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_rewards' ),
				'permission_callback' => array( $this, 'get_rewards_permissions_check' ),
			)
		);
	}

	/**
	 * Handle GET /rewards.
	 *
	 * @param \WP_REST_Request $request Request object.
	 *
	 * @return \WP_Error|\WP_REST_Response
	 */
	public function get_rewards( $request ) {
		return new \WP_REST_Response( array( 'message' => __( 'Hello World!', 'rewardswp' ) ) );
	}

	/**
	 * Permissions for GET /rewards.
	 *
	 * @param \WP_REST_Request $request Request object.
	 *
	 * @return \WP_Error|bool
	 */
	public function get_rewards_permissions_check( $request ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				esc_html__( 'You do not have permission to access this endpoint.', 'rewardswp' ),
				[ 'status' => 403 ]
			);
		}

		return true;
	}
}
