<?php
namespace Modules\Partners\Corporates\AutoCompensate;

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

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

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


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($formData)
	{

		if (!$formData['typeChanged']) {
			$formData['compensateType'] = \App\EntityPreference\Corporate::getInstance((Int)$formData['idCorporate'])->autoCompensateType;
			$formData['cashingDocType'] = \App\Config\ClientInvoicesCompensate::getInstance()->get('cashingDocType');
		}

		return $formData;
	}


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

		// CHECK INPUT ----------------------------------------------------------------------------
		if (!$formData['compensateType']) {
			$msgs->addWarning($this->lang['index']['messages']['noCompType']);
		}
		if (!$formData['cashingDocType']) {
			$msgs->addWarning($this->lang['index']['messages']['noCashDocType']);
		}
		if (!$formData['invoicesList']) {
			$msgs->addWarning($this->lang['index']['messages']['noInv']);
		}

		// ACTUAL COMPENSATION --------------------------------------------------------------------
		if (!$msgs->hasErrorOrWarning()) {

			try {
				\DB::startTransaction();

				foreach ($formData['invoicesList'] as $suggestionInvoicesList) {

					// stop if we have a wrong invoice ids list
					if (!$suggestionInvoicesList or !is_array($suggestionInvoicesList)) {
						$msgs->addWarning($this->lang['index']['messages']['invalidInvSelect']);
						\DB::rollbackTransaction();
						return false;
					}

					// actual cashing docs added
					$compensationObj = new \App\Utils\Invoices\Compensate\Client\Compensate($suggestionInvoicesList);
					$compensationObj->setDocumentData($formData['cashingDocType'], TODAY_ISO, CURRENT_ID_USER, CURRENT_ID_OFFICE);
					$compensationObj->process();

				}

				\DB::commitTransaction();

				$msgs->addSuccess( sprintf($this->lang['index']['messages']['successMsg'], count($formData['invoicesList'])) );

				return true;

			} catch (\App\MessagesException | \App\Entity\Exception $e) {

				\DB::rollbackTransaction();

				// output/log the errors
				$msgs->addError( sprintf($this->lang['index']['messages']['errorMsg'], $e->getMessagesCollector()->getMessageBulk()) );
				return false;
			}

		}

		return false;

	}

	/**
	 * Exports the list of suggestions to the view; also auto-checks invoices when needed (on first form load or typeChange)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::preRenderOperations()
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{

		// if we have a compensation type set - get the invoices selection
		if ($formData['compensateType'] and !$view->getClosePopup()) {

			// get suggested compensations
			$invSelection = new \App\Utils\Invoices\Compensate\Client\SelectInvoices($formData['compensateType']);
			$invSelection->setIdCorporate($formData['idCorporate']);
			$invSelection->process();

			$compensations = $invSelection->getCompensations();

			// display message
			if (!$compensations) {
				$view->getMessagesCollector()->addWarning($this->lang['index']['messages']['noCompSuggFound']);
			}

			// associate the suggestions - this is just for display
			$formData['compensationsSuggestions'] = $compensations;

			// on first load of suggestions, auto-check all invoices
			if (!key_exists('invoicesList', $formData) or $formData['typeChanged']) {
				$formData['invoicesList'] = [];
				foreach($compensations as $suggestionKey=>$invoicesList) {
					$formData['invoicesList'][$suggestionKey] = [];

					// for bulk - we need to check which invoices should be compensated, maybe too many are included
					if ($formData['compensateType']=='bulk') {
						$model = new \App\Utils\Invoices\Compensate\Client\Compensate($invoicesList);
						$compensatedValues = $model->calculateCompensatedValues(false);
						$formData['invoicesList'][$suggestionKey] = array_keys($compensatedValues);
					}
					// for exact credit notes - everything is selected
					elseif ($formData['compensateType']=='onlyExactCreditNotes') {
	 					$formData['invoicesList'][$suggestionKey] = $invoicesList;
					}
				}
			}

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

		}

	}

}
