<?php

namespace Planaday\Entities\Course;

use Planaday\Config\Course\Detail\DetailSettings;
use Planaday\Entities\Course\DTO\Course;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\DependencyInjection\Attributes\Scoped;
use Planaday\Utility\GeneralTermEnum;
use Planaday\Utility\PluginData;

#[Scoped]
class CourseUtility {
	use Logging;

	public function __construct(
		protected UrlHandler $urlHandler,
		protected DetailSettings $detailSettings,
		protected PluginData $pluginData,
	) {}

	public function getDetailLink(Course $course):string {
		$pageId = $this->detailSettings->getSelectedDetailPage();
		$overriddenPageId = $this->detailSettings->getOverriddenDetailPage();

		if ($pageId === 0 && $overriddenPageId !== 0) {
			$page = $this->urlHandler->getPageUrl($overriddenPageId);

			if ($page === false) {
				$this->logError("Could not find page for detail page");
				return '';
			}

			return $this->getDetailLinkFromBase($course, $page, true);
		} else {
			$page = $this->urlHandler->getPageUrl($pageId);

			if ($page === false || $pageId === 0) {
				$this->logError("Could not find page for detail page");
				return '';
			}

			return $this->getDetailLinkFromBase($course, $page);
		}
	}

	protected function getDetailLinkFromBase(Course $course, string $base, bool $forceQuery = false):string {
		if ( str_contains( $base, '?' ) ) {
			return $base . '&' . $this->pluginData->getShortPrefix() . GeneralTermEnum::COURSE_ID_URL_QUERY . "=" . $course->getId();
		}

		if ( $forceQuery ) {
			return $base . '?' . $this->pluginData->getShortPrefix() . GeneralTermEnum::COURSE_ID_URL_QUERY . "=" . $course->getId();
		}

		$var = strtolower($course->getName());
		$var = '' . preg_replace("/[^a-zA-Z\d]/", '-', $var);
		$var = '' . preg_replace("/-+/", '-', $var);
		$var = trim($var, '-');

		return $base . $course->getId() . '/' . $var;
	}

	/**
	 * gives the DayPartCount for in use of display
	 */
	public function getDayPartCount(Course $course, bool $includeELearning):int {
		if ($includeELearning){
			return $course->getDayPartAmount();
		}

		$dayParts = $course->getDayParts();

		$teller = 0;

		foreach ($dayParts as $dayPart) {
			if (!$dayPart->isELearning()) {
				$teller++;
			}
		}

		return $teller;
	}
}