<?php namespace Tussendoor\Reloadify\Http\Endpoints;

use Tussendoor\Reloadify\Concerns\Http\HasAuthentication;
use Tussendoor\Reloadify\Exceptions\FilterException;
use Tussendoor\Reloadify\Http\Filters\InfoFilter;
use WP_Error;
use WP_REST_Request;

class PluginInfoEndpoint
{

    use HasAuthentication;

    /**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wc/v3';

    /**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'reloadify/info';

    /**
	 * Register the routes for this class
	 *
	 * @return void
	 */
	public function register_routes()
	{

        /**
         * To retrieve Reloadify plugin info
         * @see /wp-json/wc/v3/reloadify/info
         */
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			[
                'methods' => \WP_REST_Server::READABLE,
				'callback' => [$this, 'returnPluginInfo'],
                'permission_callback'  => [$this, 'checkPermissions'],
            ]
		);
	}

    /**
	 * Return plugin info
	 *
	 * @param  \WP_REST_Request $request
	 * @return \WP_Error|array
	 */
	public function returnPluginInfo(WP_REST_Request $request)
    {
        try {
            $filter = new InfoFilter($request);
            $pluginInfo = $filter->apply();
        } catch (FilterException $e) {
            return new WP_Error('filter_exception', $e->getMessage(), ['status' => $e->getCode()]);
        }

        return $pluginInfo;
	}

}
