<?php

namespace App\Utils\DigitsToLetters;

abstract class KwnAbstract extends GeneralAbstract
{

	/**
	 * The language code used by KWN lib.
	 * @var string
	 */
	protected $kwnLang = null;

	/**
	 * The minus word (can be the symbol '-' or any text based on language).
	 * @var string
	 */
	protected $minusWord = '-';

	/**
	 * The word glueing the integer value and the decimals of a price; usually the "and" word
	 * in the particular language.
	 * @var string
	 */
	protected $andWord = ',';

	/**
	 * {@inheritDoc}
	 * @see \App\Utils\DigitsToLetters\GeneralAbstract::getText()
	 */
	public function getText()
	{

		if (!$this->kwnLang) {
			throw new \Exception('You must set the kwnLang attribute.');
		}

		$numToWordsObj = new \NumberToWords\NumberToWords();
		$numTransformerObj = $numToWordsObj->getNumberTransformer($this->kwnLang);

		// get value components and their translation to words
		$valueComponents = $this->getNumberComponents();

		$integerText = $numTransformerObj->toWords($valueComponents['integer']);
		$decimalsText = $valueComponents['decimals'] ? $numTransformerObj->toWords($valueComponents['decimals']) : '';

		// determine signText (contains the separator)
		$signText = ($this->value<=0) ? $this->minusWord.$this->separator : '';

		// NO CURRENCY SET AT ALL .................................................................
		if (!$this->currencyName) {
			$text = $signText . $integerText;
			if ($valueComponents['decimals']) { // I don't care about subdivision in this case
				$text .= $this->separator . '.' . $this->separator . $decimalsText;
			}
		}
		// THE CURRENCY IS SET ....................................................................
		else {

			// if I have some decimals
			if ($valueComponents['decimals']) {
				// no subdivision
				if (!$this->currencySubdivision) {
					$text = $signText . $integerText .  $this->separator . '.' . $this->separator . $decimalsText . $this->separator . $this->currencyName;
				}
				// subdivision set as well
				else {
					$text = $signText . $integerText . $this->separator . $this->currencyName . $this->separator . $this->andWord . $this->separator . $decimalsText .  $this->separator . $this->currencySubdivision;
				}
			}
			// no decimals - only the integer part
			else {
				$text = $signText . $integerText . $this->separator . $this->currencyName;
			}

		}

		return $text;

	}

	/**
	 * Breaks the value into components.
	 * @return array
	 */
	protected function getNumberComponents()
	{

		$intVal = (Int)$this->value;

		// determine the number of decimals
		if ($this->currencyName) {
			$decimals = \App\Config\CurrencyDecimals::getCurrencyDecimals($this->currencyName);
		} else {
			$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
			$decimals = $CFG['localization']['maxDecimalsOnPrices'];
		}

		$floatVal = abs( round (($this->value - $intVal)*(10**$decimals)) );

		return [
			'integer'		=> abs($intVal),
			'decimals'		=> $floatVal,
		];

	}

}
