<?php

namespace Planaday\Html\Tags\Form\GenericInput\PageSelect;

use Planaday\Html\Tags\Form\SelectableDataInputFieldTag;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class PageSelect extends SelectableDataInputFieldTag {
	const TAG = 'page-select';
	const DEFAULT_TEMPLATE = 'pageSelect';
	const NEED_TAG_ATTRIBUTE = 'data-need-tag';

	protected UrlHandler $urlHandler;

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

	public function buildTag(): string {
		$parser = $this->getNewParser();
		$currentFieldValue = $this->getCurrentFieldValue() ?? $this->attributes[self::FIELD_SET_VALUE_ATTRIBUTE] ?? null;

		if (empty($currentFieldValue)){
			$options = "<option value='0' selected>Selecteer een pagina</option>";
		} else {
			$options = "<option value='0'>Selecteer een pagina</option>";
		}

		$pages = !empty($this->attributes[self::NEED_TAG_ATTRIBUTE] ?? null) ? $this->urlHandler->getPagesWithShortCode($this->attributes[self::NEED_TAG_ATTRIBUTE]): $this->urlHandler->getAllPages();

		$parser->setData('needs', $this->attributes[self::NEED_TAG_ATTRIBUTE] ?? null);

		foreach ( $pages as $page) {
			$selected = $currentFieldValue == $page['id'] ? 'selected' : '';
			$pageId = $page['id'];
			$pageTitle = empty($page['title']) ? 'Pagina zonder titel, id:' . $pageId : $page['title'];
			$options  .= "<option value='$pageId' $selected>$pageTitle</option>";
		}

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