<?php
namespace SabaiApps\Directories;

use SabaiApps\Framework\Application\Context as FrameworkContext;

/**
 * AdminRoutingController class for handling admin-specific routing logic.
 * Provides methods for retrieving admin routes, processing access and title callbacks,
 * and executing admin route logic with access checks.
 */
class AdminRoutingController extends AbstractRoutingController {

	/**
	 * Gets the default admin route.
	 *
	 * @return Route
	 */
	protected function _getDefaultRoute() {
		return new Route( '/', array( 'controller_class' => '\SabaiApps\Directories\AdminIndexController' ) );
	}

	/**
	 * Gets component admin routes for a given root path.
	 *
	 * @param string $rootPath
	 * @return array
	 */
	protected function _getComponentRoutes( $rootPath ) {
		return $this->_application->getComponent( 'System' )->getAdminRoutes( $rootPath );
	}

	/**
	 * Processes the access callback for an admin route.
	 *
	 * @param Context $context
	 * @param array   $route
	 * @param int     $accessType
	 * @return bool
	 */
	protected function _processAccessCallback( Context $context, array &$route, $accessType ) {
		return $this->_application->getComponent( $route['callback_component'] )->systemOnAccessAdminRoute(
			$context,
			$route['callback_path'],
			$accessType,
			$route
		);
	}

	/**
	 * Processes the title callback for an admin route.
	 *
	 * @param Context $context
	 * @param array   $route
	 * @param int     $titleType
	 * @return string|null
	 */
	protected function _processTitleCallback( Context $context, array $route, $titleType ) {
		return $this->_application->getComponent( $route['callback_component'] )->systemAdminRouteTitle(
			$context,
			$route['callback_path'],
			$titleType,
			$route
		);
	}

	/**
	 * Processes the route and sets the controller class for admin routes.
	 *
	 * @param array $route
	 * @return void
	 */
	protected function _processRoute( array &$route ) {
		$route['controller_class'] = '\SabaiApps\Directories\Component\\' . $route['controller_component'] . '\Controller\Admin\\' . $route['controller'];
	}

	/**
	 * Executes the admin routing logic, checking for admin access and authentication.
	 *
	 * @param FrameworkContext $context
	 * @return void
	 */
	public function execute( FrameworkContext $context ) {
		if ( ! $this->getPlatform()->isAdmin() ) {
			$context->setForbiddenError();
			return;
		}
		if ( $this->getUser()->isAnonymous() ) {
			$context->setUnauthorizedError( $this->AdminUrl() );
			return;
		}

		parent::execute( $context );
	}
}
