<?php

namespace Modules\Invoices\Cashings\Management\Cancel;

/**
 * This section cancels one or more invoice cashing docs.
 */
class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

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

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

		$invoiceCashingEntCfg = \Entity\InvoiceCashing::loadCFG();

		// check that at least one cashing document id was sent
		if (!is_array($R['id']) or !$R['id']) {
			$msgs->addError($this->lang['index']['msgs']['noDocsIds']);
			return false;
		}

		// check that the void reason is filled in if the field is mandatory
		if ($invoiceCashingEntCfg['_special']['voidReasonMandatory'] and !$R['voidReason']) {
			$msgs->addWarning($this->lang['index']['msgs']['noVoidReason']);
			return false;
		}

		// VOIDS ALL SELECTED DOCUMENTS -----------------------------------------------------------
		$OK = true;
		foreach ($R['id'] as $idCashingDoc) {

			try {

				\DB::startTransaction();

				$cashingDocCancel = \Entity\InvoiceCashing::cancel($idCashingDoc);
				$cashingDocCancel->voidReason = $R['voidReason'];
				$cashingDocCancel->save();

				\DB::commitTransaction();
				$msgs->addSuccess(sprintf($this->lang['index']['msgs']['success'], $idCashingDoc));

			} catch (\App\Entity\Exception $e) {
				\DB::rollbackTransaction();
				$msgs->appendMessages($e->getMessagesCollector(), sprintf($this->lang['index']['msgs']['error'], $idCashingDoc).' %s');
				$OK = false;
				break ;
			}

		}

		return $OK;

	}

}