<?php
namespace Modules\Documents\ImportedDocuments\AddDocOnOrder;

class Controller extends \App\Mvc\ControllerAbstract
{

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\ControllerAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['index'] =     ['checkSection' => false, 'checkOption' => false,];
	}


	protected function actionIndex($R)
	{
		// collects messages
		$msgs = \App\MessagesCollector::create();

		// SAVE THE FORM DATA /////////////////////////////////////////////////////////////////////
		if ($R['save']) {
			if (!$R['servicesList']) {
				$msgs->addWarning($this->lang['index']['msgs']['noServiceSelected']);
			}

			if (!$R['currency']) {
				$msgs->addWarning($this->lang['index']['msgs']['noCurrencySelected']);
			}
			elseif (!\App\Config\Currencies::getInstance()->check($R['currency'])) {
				$msgs->addError($this->lang['index']['msgs']['invalidCurrency']);
			}

			if (!$msgs->hasErrorOrWarning()) {

				$postData = [];
				$postData['docCategory'] = 'cashing';
				$postData['entity'] = 'service';
				$postData['entityIds'] = $R['servicesList'];

				$postData['value']['currency'] = $R['currency'];
				$postData['value']['value'] = 0;
				foreach ($R['servicesList'] as $idService) {
					$serviceEnt = \Entity\Service::select($idService);
					$postData['value']['value'] += \App\CurrencyExchange\Rates::getInstance($serviceEnt->chosenOffer->currencyDate, $serviceEnt->chosenOffer->currencyType)->convert($serviceEnt->chosenOffer->offerWorkTotal, $serviceEnt->chosenOffer->totalCurrency, $R['currency']);
				}

				$response = new \Engine\Mvc\Response\HtmlRedirectWithPost(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl("Modules/Documents/ImportedDocuments", "insert"));
				$response->setPostData($postData);
				return $response;
			}
		}

		// instantiate the view
		$view = new View_Index($this);

		// send data to the view
		$view->addInput('formData', $R);
		$view->getMessagesCollector()->appendMessages($msgs);
		$view->addInput('formSubmitButtonName', 'save');

		// render the view
		return new \Engine\Mvc\Response\Html($view->render());

	}

}