<?php
namespace Modules\Admin\Config\ClientInvoices\TotalRounding;

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


	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$invoiceRoundingDetails = \App\Config\InvoiceRounding::getInstance()->getAll();

		$formData = [];
		$formData['active'] =				!$invoiceRoundingDetails['disabled'];
		$formData['roundType'] =			$invoiceRoundingDetails['roundType'];
		$formData['defaultByCurrency'] =	array_keys($invoiceRoundingDetails['defaultByCurrency']);
		$formData['blockedServices'] =		array_keys($invoiceRoundingDetails['blockedServices']);

		return $formData;

	}


	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		// processing request to be saved
		$saveInvoiceRounding = [];

		$defaultByCurrencyList = [];
		foreach ((array)$R['defaultByCurrency'] as $currencyCode => $code ) {
			$defaultByCurrencyList[$currencyCode] = true;
		}

		$blockedServicesList=[];
		foreach ((array)$R['blockedServices'] as $serviceCode => $code ) {
			$blockedServicesList[$serviceCode] = true;
		}

		$saveInvoiceRounding = [
			'disabled' =>			!$R['active'],
			'defaultByCurrency' =>	$defaultByCurrencyList,
			'blockedServices' =>	$blockedServicesList,
			'roundType' =>			$R['roundType']
		];

		// save
		try {
			\App\Config\InvoiceRounding::getAdmin()->setAll($saveInvoiceRounding);
			\App\Config\InvoiceRounding::getAdmin()->save();
			$msgs->addSuccess($this->lang['process']['messages']['success']);
		}

		// errors
		catch (\App\Config\MessageException $e) {
			$msgs->addError(sprintf($this->lang['process']['messages']['error'],$e->getMessage()));
		}
	}

}