<?php

namespace Planaday\Html\Tags\Course\NotFoundRedirect;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Config\Course\Detail\DetailSettings;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\Course\Exception\CourseNotFoundException;
use Planaday\Html\Tags\Tag;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\GeneralTermEnum;
use Planaday\Utility\PluginData;

class NotFoundRedirect extends Tag {
	const TAG = 'course-not-found-redirect';

	const DEFAULT_TEMPLATE = '';

	protected UrlHandler $urlHandler;
	protected PluginData $pluginData;
	protected CourseController $courseController;
	protected DetailSettings $detailSettings;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct( Container $registry ) {
		$this->urlHandler = $registry->getInstance(UrlHandler::class);
		$this->pluginData = $registry->getInstance(PluginData::class);
		$this->courseController = $registry->getInstance(CourseController::class);
		$this->detailSettings = $registry->getInstance(DetailSettings::class);
		parent::__construct( __DIR__, self::DEFAULT_TEMPLATE, $registry );
	}

	public function buildTag(): string {
		$courseId = $this->urlHandler->getUrlQueryField($this->pluginData->getShortPrefix() . GeneralTermEnum::COURSE_ID_URL_QUERY);

		if ($courseId === null || ($courseId = filter_var($courseId, FILTER_VALIDATE_INT)) === false) {
			$this->sendToPage();
			return '';
		}

		try {
			$this->courseController->getCourse($courseId, true);
		} catch (InvalidResponseException|CourseNotFoundException ) {
			$this->sendToPage();
		}

		return '';
	}

	protected function sendToPage(): void {
		$pageId = $this->detailSettings->getCourseNotFoundPage();
		$currentPageId = $this->urlHandler->getCurrentPageId();
		$url = $pageId !== 0 && $pageId !== $currentPageId ?
			$this->urlHandler->getPageUrl($pageId) :
			$this->urlHandler->getBaseUrl();

		$this->urlHandler->redirect($url);
	}
}