<?php

namespace Planaday\Html\NodeTags\Utility;

use DOMNode;
use Planaday\Config\General\Price\PriceSettings;
use Planaday\Entities\CostDataUtility;
use Planaday\Entities\CostsData;
use Planaday\Html\Nodes\ParserNode;
use Planaday\Html\NodeTags\Tag;
use Planaday\Html\NodeTags\TagCore;
use Planaday\Html\NodeTags\TagNotFullyInitializedException;
use Planaday\Utility\DependencyInjection\Attributes\Transient;

#[Transient]
class Price implements Tag {
	use TagCore;

	public function __construct(
		protected CostDataUtility $costUtility,
		protected PriceSettings $priceSettings,
	) {
		$this->config = [
			"withTax" => function () { return $this->priceSettings->isIncludingTax();},
		];
	}

	public function getNewNode(): DOMNode&ParserNode {
		if ( !isset( $this->originalNode ) ){
			throw new TagNotFullyInitializedException("The OriginalNode is not set");
		}

		$outputFragment = $this->originalNode->getUsableDocumentFragment();

		$priceData = $this->attributes["data"] ?? null;
		$bothPrices = ($this->attributes["both"] ?? null) == true;
		$perPerson = ($this->attributes["pp"] ?? false) == true;
		$withTax = isset($this->attributes["tax"]) ?
			$this->attributes["tax"] == true :
			$this->priceSettings->isIncludingTax();

		if ( !$priceData instanceof CostsData ) {
			throw new TagNotFullyInitializedException("The PriceData is not set");
		}

		$this->logDebug("tax is attribute: " . ( $this->attributes["tax"] ?? "null" ));
		$this->logDebug("so tax is " . $withTax );

		$outputText = $this->costUtility->getPriceString($priceData, $bothPrices, $perPerson, $withTax);

		$textNode = $outputFragment->ownerDocument->createTextNode($outputText);

		$outputFragment->prepend($textNode);
		return $outputFragment;
	}

	public function getTagDir(): string {
		return __DIR__;
	}
}