<?php
namespace Modules\Invoices\Cashings\Management\TransferToCredit;

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

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$invEnt = \Entity\Invoice::select($R['idInvoice']);
		$formData = $R;

		// document date
		$formData['docDate'] = TODAY_ISO;

		// document currency
		$formData['docValue']['currency'] = $invEnt->currency;

		// document value
		$formData['docValue']['value'] = (-1)*round($invEnt->printTotal-$invEnt->cashedTotal, 2);

		return $formData;
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(array $R, \App\MessagesCollector $msgs)
	{

		$cashingDocType = \Modules\Invoices\Cashings\Management\TransferToCredit\Config::getInstance()->get('cashingDocType');
		$impDocType = \Modules\Invoices\Cashings\Management\TransferToCredit\Config::getInstance()->get('impDocType');
		$idExternalSystem = \Modules\Invoices\Cashings\Management\TransferToCredit\Config::getInstance()->get('idExternalSystem');

		try {
			\DB::startTransaction();
			$model = new Model($R['idInvoice']);

			// set input data
			$model->setDocumentData($cashingDocType, $impDocType, $idExternalSystem, $R['docDate'], $R['docNumber'], $R['docValue']['value'], $R['docValue']['currency']);

			$model->process();
			\DB::commitTransaction();
			$msgs->addSuccess($this->lang['index']['form']['success']);
			return true;
		} catch (\App\MessagesException $e) {
			\DB::rollbackTransaction();
			$msgs->appendMessages($e->getMessagesCollector());
			return false;
		} catch (\App\Entity\Exception $e) {
			\DB::rollbackTransaction();
			$msgs->appendMessages($e->getMessagesCollector());
			return false;
		}
	}
}