<?php

namespace Modules\Admin\Config\SupplierInvoices\Vats\BulkOperations;

/**
 * This module is used for processing multiple services at once.
 */
class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\PopupAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['index'] = [ 'checkSection' => 'Modules/Admin/Config/SupplierInvoices/Vats', 'checkOption' => false ];
	}


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

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(array $R, \App\MessagesCollector $msgs)
	{
		// vatQuota is mandatory
		if (!strlen($R['vatQuota'])) {
			$msgs->addWarning($this->lang['index']['messages']['vatQuotaMandatory']);
		}

		// vatPercent is mandatory
		if (!is_numeric($R['vatPercent'])) {
			$msgs->addWarning($this->lang['index']['messages']['vatPercentMandatory']);
		}

		if (!$msgs->hasErrorOrWarning()) {

			$configClass = \App\Config\SupplierInvoice_Vats::getAdmin();

			if ($R['services']) {
				$servicesList = $R['services'];
			}
			else {
				$allServices = \App\Config\Services_Basic::getInstance()->getListLinear();
				$servicesList = array_keys($allServices);
			}

			try {
				foreach ($servicesList as $service) {
					$srvConfigList = $configClass->get($service);
					$srvConfigList['list'][$R['vatQuota']] = $R['vatPercent'];
					$configClass->set($service, $srvConfigList);
				}
				$configClass->save();
				$msgs->addSuccess($this->lang['index']['messages']['insertOk']);
				return true;
			}
			catch (\App\Config\MessageException $e) {
				$configClass->reset();
				$msgs->addWarning($e->getMessage());
			}
		}
	}

}