<?php

namespace Planaday\Html\Tags\Course\Price;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Config\General\Price\PriceSettings;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\Course\Exception\CourseNotFoundException;
use Planaday\Html\Tags\InvalidAttributesException;
use Planaday\Html\Tags\Tag;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class CoursePrice extends Tag {
	const TAG = 'legacy-course-price';

	const DEFAULT_TEMPLATE = 'price';
	const ID_ATTRIBUTE = 'data-id';

	protected CourseController $courseController;
	protected PriceSettings $priceOptions;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct( Container $registry ) {
		$this->courseController = $registry->getInstance( CourseController::class );
		$this->priceOptions     = $registry->getInstance( PriceSettings::class );
		parent::__construct( __DIR__, self::DEFAULT_TEMPLATE, $registry );
	}

	public function buildTag(): string {
		$parser = $this->getNewParser();

		try {
			$courseIdString = $this->attributes[self::ID_ATTRIBUTE] ?? null;
			if ($courseIdString === null) throw new InvalidAttributesException();

			$courseId = filter_var($courseIdString, FILTER_VALIDATE_INT);
			if ($courseId === false) throw new InvalidAttributesException();

			$priceData = $this->courseController->getCourse( $courseId )->getCostsData();

			$parser->setData('price', number_format($this->priceOptions->isIncludingTax() ? $priceData->getPriceWithTax() : $priceData->getCost(), 2));

			return $parser->parse( $this->getTemplate() );
		} catch ( CourseNotFoundException ){
			$parser->setData('errorType', 'notFoundError');
		} catch ( InvalidResponseException ){
			$parser->setData('errorType', 'serverError');
		} catch ( InvalidAttributesException ){
			$parser->setData('errorType', 'attributeError');
		}

		return $parser->parse($this->getErrorTemplate());
	}
}