<?php
namespace Modules\Admin\CurrencyExchange;

class Controller extends \App\Mvc\Controller\Form\WindowAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();
	}

	/**
	 * Render popup options
	 */
	public function getAllDefinedOptions()
	{
		$options = new \App\Mvc\View\Utils\RowOptions\Container\Simple();

		$options
		->append(\App\Mvc\View\Utils\RowOptions\Option\Option::create("history")
			->setSection('global')
			->setDescription($this->lang['index']['options']['history'])
			->setIcon('quickNav')
			->setJsCallback("Popup2.create().setId('historyRates').setUrl(MVC.appUrl('Admin/CurrencyExchange/HistoryRates', 'index')).setDimensions(1000, 700).show();")
		)
		->append(\App\Mvc\View\Utils\RowOptions\Option\Option::create("parities")
			->setSection('global')
			->setDescription($this->lang['index']['options']['parities'])
			->setIcon('mandatory')
			->setJsCallback("Popup2.create().setId('parities').setUrl(MVC.appUrl('Admin/CurrencyExchange/Parities', '')).setDimensions(600, 500).show();")
		)
		->append(\App\Mvc\View\Utils\RowOptions\Option\Option::create("checkOnlineSystem")
			->setDescription($this->lang['index']['options']['checkOnlineSystem'])
			->setSection('global')
			->setIcon('export')
			->setJsCallback("Popup2.create().setId('checkOnlineSystem').setUrl(MVC.appUrl('Admin/CurrencyExchange/CheckOnlineSystem', '')).setDimensions(750, 500).show();")
		);

		return $options;
	}

	protected function getDefaultFormData($R)
	{
		if (!$R['operation']) {
			$allRates = \App\CurrencyExchange\Date::getInstance($R['currencyExchDate'])->getRates(false);
			foreach ($allRates as $currencyTypeCode => $currencyDetails) {
				foreach ($currencyDetails as $currency => $currencyRate) {
					$R['currencyRates'][$currency][$currencyTypeCode] = $currencyRate;
				}
			}
		}

		if ($R['operation'] == "importPrevExchRate") {
			$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

			$currenciesMngObj = new \App\CurrencyExchange\Admin($R['currencyExchDate']);

			// load rates from the previous date
			$currenciesMngObj->addRates_previousDate();

			$initialRates = $currenciesMngObj->getRates();
			foreach(\App\Config\CurrencyTypes::getInstance()->getAll() as $currencyTypeCode=>$currencyTypeDetails) {

				if (!$currencyTypeDetails['disabled']) {

					// loop currencies
					foreach(\App\Config\Currencies::getInstance()->getSimple() as $currencyCode) {

						// skip default currency
						if ($currencyCode!=$CFG['currencies']['defaultCurrency']) {

							// by default set this to the value from the rates array
							$thisRate = $initialRates[$currencyTypeCode][$currencyCode];

							// apply global formula
							if ($currencyTypeDetails['parent']) {
								if ($currencyTypeDetails['operation']=='multiply') {
									$thisRate = $initialRates[$currencyTypeDetails['parent']][$currencyCode] * $currencyTypeDetails['argument'];
								} elseif ($currencyTypeDetails['operation']=='add') {
									$thisRate = $initialRates[$currencyTypeDetails['parent']][$currencyCode] + $currencyTypeDetails['argument'];
								}
							}
							// apply independent currency formula
							elseif ($currencyTypeDetails['currencies'][$currencyCode]['parent']) {
								$currTypeParent = $currencyTypeDetails['currencies'][$currencyCode]['parent'];
								$currTypeOperation = $currencyTypeDetails['currencies'][$currencyCode]['operation'];
								$currTypeArg = $currencyTypeDetails['currencies'][$currencyCode]['argument'];

								if ($currTypeOperation=='multiply') {
									$thisRate = $initialRates[$currTypeParent][$currencyCode] * $currTypeArg;
								} elseif ($currTypeOperation=='add') {
									$thisRate = $initialRates[$currTypeParent][$currencyCode] + $currTypeArg;
								}
							}

							// set the new row fields for this rate
							$R['currencyRates'][$currencyCode][$currencyTypeCode] = $thisRate;
						}
					}
				}
			}
		}

		if ($R['operation'] == "importExtSystExchRate") {
			$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

			$currenciesMngObj = new \App\CurrencyExchange\Admin($R['currencyExchDate']);

			// load rates from the previous date
			$currenciesMngObj->addRates_previousDate();
			$currenciesMngObj->addRates_externalSystems($R['currencyExchDate']);

			$initialRates = $currenciesMngObj->getRates();
			foreach(\App\Config\CurrencyTypes::getInstance()->getAll() as $currencyTypeCode=>$currencyTypeDetails) {

				if (!$currencyTypeDetails['disabled']) {

					// loop currencies
					foreach(\App\Config\Currencies::getInstance()->getSimple() as $currencyCode) {

						// skip default currency
						if ($currencyCode!=$CFG['currencies']['defaultCurrency']) {

							// by default set this to the value from the rates array
							$thisRate = $initialRates[$currencyTypeCode][$currencyCode];

							// apply global formula
							if ($currencyTypeDetails['parent']) {
								if ($currencyTypeDetails['operation']=='multiply') {
									$thisRate = $initialRates[$currencyTypeDetails['parent']][$currencyCode] * $currencyTypeDetails['argument'];
								} elseif ($currencyTypeDetails['operation']=='add') {
									$thisRate = $initialRates[$currencyTypeDetails['parent']][$currencyCode] + $currencyTypeDetails['argument'];
								}
							}
							// apply independent currency formula
							elseif ($currencyTypeDetails['currencies'][$currencyCode]['parent']) {
								$currTypeParent = $currencyTypeDetails['currencies'][$currencyCode]['parent'];
								$currTypeOperation = $currencyTypeDetails['currencies'][$currencyCode]['operation'];
								$currTypeArg = $currencyTypeDetails['currencies'][$currencyCode]['argument'];

								if ($currTypeOperation=='multiply') {
									$thisRate = $initialRates[$currTypeParent][$currencyCode] * $currTypeArg;
								} elseif ($currTypeOperation=='add') {
									$thisRate = $initialRates[$currTypeParent][$currencyCode] + $currTypeArg;
								}
							}

							// set the new row fields for this rate
							$R['currencyRates'][$currencyCode][$currencyTypeCode] = $thisRate;
						}
					}
				}
			}
		}

		return $R;
	}

	protected function processFormData(array $R, \App\MessagesCollector $msgs)
	{
		if (!$R['currencyExchDate']) {
			$msgs->addError($this->lang['index']['messages']['currencyExchDateNotSet']);
		}
		elseif ($R['currencyExchDate'] < TODAY_ISO or $R['currencyExchDate'] > \Engine\DateTime::create("+ 7 days")->formatDateIso()) {
			$msgs->addError(sprintf($this->lang['index']['messages']['invalidCurrencyExchDate'], \Engine\DateTime::create()->formatDateStd(), \Engine\DateTime::create("+ 7 days")->formatDateStd()));
		}

		if (!$msgs->hasErrorOrWarning()) {
			try {
					\DB::startTransaction();
					$currenciesMngObj = new \App\CurrencyExchange\Admin($R['currencyExchDate']);

					// set the rates
					if ($R['currencyRates']) {
						foreach($R['currencyRates'] as $currency=>$ratesList) {
							foreach($ratesList as $currencyType=>$rate) {
								if ($rate) {
									$currenciesMngObj->addRate($currencyType, $currency, $rate);
								}
							}
						}
					}
					$currenciesMngObj->save();
					\DB::commitTransaction();

					$trailItem = \App\UserTrailItem::create($this->getModule(), 'save');
					\App\UserTrail::getInstance()->addItem($trailItem);

					$msgs->addSuccess($this->lang['index']['messages']['success']);
					return true;
			} catch (\App\MessagesException $e) {
				\DB::rollbackTransaction();
				$msgs->addError(sprintf($this->lang['index']['messages']['error'], $e->getMessagesCollector()->getMessageBulk()));
				return false;
			}
		}
	}

	/**
	 * Add the possibility to set or change the formData value for submitted content.
	 * @param Array $R
	 */
	protected function getSubmitFormData($R, \App\MessagesCollector $msgs)
	{
		$allRates = \App\CurrencyExchange\Date::getInstance($R['currencyExchDate'])->getRates(false);

		foreach ($allRates as $currencyTypeCode => $currencyDetails) {
			foreach ($currencyDetails as $currency => $currencyRate) {
				$R['currencyRates'][$currency][$currencyTypeCode] = $currencyRate;
			}
		}
		return $R;
	}

	/**
	 * Do some more stuff on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{
		if (!$formData['currencyExchDate']) {
			$formData['currencyExchDate'] = TODAY_ISO;
		}

		if ($formData['currencyExchDateChanged']  and  !\App\CurrencyExchange\Date::getInstance($formData['currencyExchDate'])->getRates(false)) {
			$formData['currencyRates'] = [];
		}

		$view->addInput('formData', $formData);

		if ($formData['operation'] and !$formData['save']) {
			$msgs = $view->getMessagesCollector();
			$msgs->addWarning($this->lang['index']['messages']['warningSave']);
		}
	}

}