<?php
namespace Modules\Admin\Config\SupplierInvoices\Vats;

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

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

		$formData = [];

		foreach(\App\Config\SupplierInvoice_Vats::getInstance()->getAll() as $serviceCode => $serviceDetails) {
			foreach($serviceDetails['list'] as $quota => $percent) {

				if (!$serviceCode) {
					$serviceCode = '_';
				}

				$formData['invoicesVat'][$serviceCode][] = [
					'code' => $quota,
					'value' => $percent,
					'default'=>($serviceDetails['default'] == $quota)
				];
			}
		}
		return $formData;

	}


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

			$servicesList = \App\Config\Services_Basic::getInstance()->getListLinear();

			$formData = [];
			foreach ($R['invoicesVat'] as $serviceCode => $quotasList) {

				if($serviceCode == '_') {
					$serviceCode = '';
				}

				foreach ($quotasList as $quota) {
					if( !strlen($quota['code']) and !strlen($quota['value']) ) {
						continue;
					}

					if($formData[$serviceCode]['list'][$quota['code']]) {
						$msgs->addWarning(sprintf($this->lang['process']['messages']['duplicate'], $servicesList[$serviceCode]['name']));
					}

					$formData[$serviceCode]['list'][$quota['code']] = $quota['value'];

					if (count($quotasList) == 1) {
						$formData[$serviceCode]['default'] = $quota['code'];
					}
					elseif ($quota['default']) $formData[$serviceCode]['default'] = $quota['code'];

				}
			}

			if(!$msgs->hasErrorOrWarning()) {
				\App\Config\SupplierInvoice_Vats::getAdmin()->setAll($formData);
				\App\Config\SupplierInvoice_Vats::getAdmin()->save();
				$msgs->addSuccess($this->lang['process']['messages']['success']);
			}
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError(sprintf($this->lang['process']['messages']['error'],$e->getMessage()));
		}
	}

}