<?php
/**
 * API controller for REST API initialization.
 *
 * @package Awesomemotive\Rewardswp\Controllers
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Controllers;

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

use Awesomemotive\Rewardswp\Interfaces\ControllerInterface;
use DI\Container;
use Exception;

/**
 * Class ApiController
 *
 * This controller is responsible for loading all API routes.
 *
 * @package Awesomemotive\Rewardswp\Controllers
 */
class ApiController implements ControllerInterface {

	/**
	 * Dependency injection container.
	 *
	 * @var Container
	 */
	protected Container $container;

	/**
	 * ApiController constructor.
	 *
	 * @param Container $container DI container instance.
	 */
	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Hooks the API route registration to the 'rest_api_init' action.
	 */
	public function init() {
		add_action( 'rest_api_init', [ $this, 'register_api_routes' ] );
	}

	/**
	 * Registers all defined API routes from different versions.
	 *
	 * @throws Exception
	 */
	public function register_api_routes() {
		$api_versions = $this->container->get( 'api_versions' );

		foreach ( $api_versions as $version_registrar_class ) {
			$registrar = $this->container->get( $version_registrar_class );
			$registrar->register_routes();
		}
	}
}
