<?php

namespace Planaday\Html\Tags\Admin\Pages\CSS;

use Planaday\Config\Internal\InternalOptionsEnum;
use Planaday\Config\Internal\InternalSettings;
use Planaday\Entities\PostEntities;
use Planaday\Html\Tags\Tag;
use Planaday\Platform\PlatformAbstraction\DataHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class CSS extends Tag {
	const TAG = 'admin-page-css';
	const DEFAULT_TEMPLATE = 'css';
	const NONCE_NAME = '-css-nonce';

	protected InternalSettings $internalSettings;
	protected DataHandler $dataHandler;

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

	public function buildTag(): string {
		$postData = $this->dataHandler->getPostField(PostEntities::GENERIC_POST);
		$parser = $this->getNewParser();
		$parser->setData('nonce-name', self::NONCE_NAME);

		if (is_array($postData) &&
		    (is_string($postData[InternalOptionsEnum::GLOBAL_CSS->value] ?? null) ||
		    is_null($postData[InternalOptionsEnum::GLOBAL_CSS->value] ?? null))) {
			$this->dataHandler->verifyAdminNonce(self::NONCE_NAME);
			$this->logInfo('Global Css set to: ' . $postData[InternalOptionsEnum::GLOBAL_CSS->value]);
			$this->internalSettings->setGlobalCss($postData[InternalOptionsEnum::GLOBAL_CSS->value]);

			$parser->setCondition('success-block', true);
			$parser->setData('successMessage', 'CSS opgeslagen.');
		}

		$parser->setData('globalCss', $this->internalSettings->getGlobalCss());

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