<?php

namespace Planaday\Html\Tags\Form\Booking\ApiAttributesInput;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Entities\Booking\PostRequest\BookingFormFieldEnum;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\Course\DTO\ApiAttribute;
use Planaday\Entities\Course\Exception\CourseNotFoundException;
use Planaday\Html\Tags\Form\DataInputFieldTag;
use Planaday\Html\Tags\Form\GenericInput\CheckboxInput\CheckboxInput;
use Planaday\Html\Tags\Form\GenericInput\RadioInput\RadioInput;
use Planaday\Html\Tags\Form\SelectableDataInputFieldTag;
use Planaday\Platform\PlatformAbstraction\DataHandler;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\GeneralTermEnum;

class ApiAttributesInput extends DataInputFieldTag {
	const TAG = 'api-attributes-input';
	const DEFAULT_TEMPLATE = 'apiAttributesInput';
	const COURSE_ID_ATTRIBUTE = self::ATTRIBUTE_PREFIX . 'course-id';
	protected string $fieldName = BookingFormFieldEnum::ATTRIBUTES;

	protected CourseController $courseController;
	protected DataHandler $dataHandler;
	protected UrlHandler $urlHandler;

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

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

		$courseIdString = $this->attributes[self::COURSE_ID_ATTRIBUTE] ?? null;
		if ($courseIdString === null && $dataHandler->isPostDataSet())
			$courseIdString = $dataHandler->getPostField( GeneralTermEnum::COURSE_ID );
		if ($courseIdString === null)
			$courseIdString = $this->urlHandler->getUrlQueryField($this->pluginData->getShortPrefix() . GeneralTermEnum::COURSE_ID_URL_QUERY);
		$courseId = filter_var($courseIdString, FILTER_VALIDATE_INT);

		if (!is_int($courseId))
			return $parser->parse($this->getErrorTemplate('', 'attributeError'));

		try {
			$course = $this->courseController->getCourse($courseId, true);
		} catch ( InvalidResponseException ) {
			return $parser->parse($this->getErrorTemplate());
		} catch ( CourseNotFoundException ) {
			return $parser->parse($this->getErrorTemplate('', 'courseNotFound'));
		}

		if (count($course->getAttributes()) == 0)
			return $parser->parse($this->getErrorTemplate('', 'noAttributes'));

		$attributes = '';
		foreach ($course->getAttributes() as $attribute){
			$attributes .= $this->buildAttributeHtml($attribute);
		}

		$parser->setUnsafeData('attributes', $attributes);
		return $parser->parse($this->getTemplate());
	}

	protected function buildAttributeHtml(ApiAttribute $attribute): string{
		if (!$attribute->isForBooking()) return '';

		$parser = $this->getNewParser();
		$parser->injectAttribute(
			SelectableDataInputFieldTag::FIELD_CLASS_ATTRIBUTE,
			BookingFormFieldEnum::class
		);

		$parser->setData('name', $attribute->getName());
		$parser->setCondition('required', $attribute->isRequired());

		$valueHtml = '';
		foreach ($attribute->getValues() as $value){
			if ($attribute->isMultipleValuesAllowed()) {
				$valueHtml .= CheckboxInput::getTagHtml(
					$attribute->getCode(),
					' ' . $value->getName(),
					$value->getDescription(),
					$value->getName(),
					false,
					true,
					'simpleCheckbox'
				);
			}
			else {
				$valueHtml .= RadioInput::getTagHtml(
					$attribute->getCode(),
					$value->getName(),
					$value->getDescription(),
					htmlspecialchars($value->getName())
				);
			}
		}
		$parser->setUnsafeData('values', $valueHtml);

		return $parser->parse($this->getTemplate('Attribute'));
	}
}