<?php
namespace Modules\Invoices\SupplierInvoices\Compensate;

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

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$formData = $R;

		$model = new Model($R['ids']);
		$compensatedValues = $model->calculateCompensatedValues(false);
		$formData['invoicesList'] = array_keys($compensatedValues);

		return $formData;
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::preRenderOperations()
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$model = new Model($formData['invoicesList']);
		$formData['compensatedValues'] = $model->calculateCompensatedValues(false);

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

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(array $R, \App\MessagesCollector $msgs)
	{
		try {
			\DB::startTransaction();
			$model = new Model($R['invoicesList']);

			// set input data
			$model->setDocumentData($R['paymentDocType'], TODAY_ISO, CURRENT_ID_USER, CURRENT_ID_OFFICE);
			$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;
		}
	}
}