<?php
namespace Modules\Admin\Config\ImportedOrders\Services\Attributes;

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

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();
		$this->actionsCfg['index'] 	= [ 'checkSection' => 'Modules/Admin/Config/ImportedOrders/Services', 'checkOption' => false ];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		if (!$R['idSystem'] || !$R['externalServiceCode']) {
			throw new \Exception('Not enough parameters.');
		}
		$formData = [];
		$formData['idSystem'] = $R['idSystem'];
		$formData['idExternalService'] = $R['externalServiceCode'];

		// GET SERVICE ATTRIBUTES /////////////////////////////////////////////////////////////////////////
		$ent = \App\Config\ImportedOrders_Matches::getAdmin();

		$serviceAttributes = array_merge(
			$ent->getServiceCategories($R['idSystem'], $R['externalServiceCode']),
			$ent->getServiceProductTypes($R['idSystem'], $R['externalServiceCode']),
			$ent->getServiceSources($R['idSystem'], $R['externalServiceCode']),
			$ent->getServiceMultipliers($R['idSystem'], $R['externalServiceCode'])
		);

		$values = [];
		foreach($serviceAttributes as $attribute) {
			$key = $attribute['entityType'].'|'.$attribute['idEntityTina'];
			$value = array_filter( [ $attribute['systemServiceCategoryCode'], $attribute['systemServiceProductTypeCode'], $attribute['systemServiceSourceCode'], $attribute['systemServiceMultiplierCode'] ], function($elem) {
				return (bool)strlen((String)$elem);
			});
			$values[] = ['key'=> $key,'value'=>reset($value)];
		}
		$formData['attributes'] = $values;

		return $formData;

	}


	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		if (!$R['idSystem']) {
			$msgs->addWarning($this->lang['process']['messages']['noIdSystem']);
			return false;
		}

		if(!$R['idExternalService']) {
			$msgs->addWarning($this->lang['process']['messages']['noIdExternalService']);
			return false;
		}

		foreach($R['attributes'] as $attributeData) {
			if (!$attributeData['key']) {
				$msgs->addWarning($this->lang['process']['messages']['noTinaCode']);
				return false;
			}
		}
		try {
			\DB::startTransaction();

			$ent = \App\Config\ImportedOrders_Matches::getAdmin();

			//first we remove the old data
			$ent->deleteServiceCategories($R['idSystem'], $R['idExternalService']);
			$ent->deleteServiceProductTypes($R['idSystem'], $R['idExternalService']);
			$ent->deleteServiceSources($R['idSystem'], $R['idExternalService']);
			$ent->deleteServiceMultipliers($R['idSystem'], $R['idExternalService']);

			foreach($R['attributes'] as $attributeData) {
				list($attributeType, $code) = explode('|',$attributeData['key']);
				if (strlen($attributeData['value']) && $attributeType && strlen($code)) {
					switch($attributeType) {
						case 'service_category':
							$ent->setServiceCategory($R['idSystem'], $R['idExternalService'], $attributeData['value'], $code);
							break;
						case 'service_productType':
							$ent->setServiceProductType($R['idSystem'], $R['idExternalService'], $attributeData['value'], $code);
							break;
						case 'service_source':
							$ent->setServiceSource($R['idSystem'], $R['idExternalService'], $attributeData['value'], $code);
							break;
						case 'service_multiplier':
							$ent->setServiceMultiplier($R['idSystem'], $R['idExternalService'], $attributeData['value'], $code);
							break;
						default:
							throw new \Exception("Invalid attribute type");
					}
				}

			}

			$ent->save();
			\DB::commitTransaction();

			$msgs->addSuccess($this->lang['process']['messages']['success']);
			return true;

		}
		catch(\App\Config\MessageException $ex) {
			\DB::rollbackTransaction();
			$msgs->addWarning(sprintf($this->lang['process']['messages']['error'], $ex->getMessage()));
		}
		return false;
	}

	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{

		$possibleValues = [];
		$notCategorizedPossibleAttributesList = [];

		// get the tina service type
		$tinaServiceType = \App\Config\ImportedOrders_Matches::getAdmin()->getServiceType($formData['idSystem'], $formData['idExternalService']);

		$tinaAttributesList['service_category'] = 		\App\Config\Services_GeneralAttributes::getInstance()->getServiceCategory($tinaServiceType);
		$tinaAttributesList['service_productType'] = 	\App\Config\Services_GeneralAttributes::getInstance()->getServiceProductType($tinaServiceType);
		$tinaAttributesList['service_source'] = 		\App\Config\Services_GeneralAttributes::getInstance()->getServiceSource($tinaServiceType);
		$tinaAttributesList['service_multiplier'] = 	\App\Config\Services_GeneralAttributes::getInstance()->getServiceMultiplier($tinaServiceType);

		if ($tinaAttributesList) {
			foreach ($tinaAttributesList as $key => $value) {
				if ($value['type'] == 'list') {
					$keyName = $value['fieldFinalName'] ? $value['fieldFinalName'] : $value['fieldName'];
					$possibleValues[$keyName] = [];
					foreach ($value['list'] as $subKey => $subValue) {
						$possibleValues[$keyName][$key.'|'.$subKey] = $subValue;
						$notCategorizedPossibleAttributesList[$key.'|'.$subKey] = $subValue;
					}
				}
			}
		}

		$view->addInput('possibleAttributesList', $possibleValues);
		$view->addInput('notCategorizedPossibleAttributesList', $notCategorizedPossibleAttributesList);
	}

}