<?php
namespace Modules\Admin\Config\Services\Basic;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract
{
	/**
	 * Store submit button name
	 * @var String
	 */
	protected $formSubmitButtonName  = 'save';

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = ['addTime'];

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

		$this->actionsCfg['addGroup'] 	= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['addService'] = ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['update'] 	= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveUp'] 	= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveDown'] 	= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['delete'] 	= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['save'] 		= ['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['reset'] 		= ['checkSection' => true, 	'checkOption' => false];
	}

	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		switch($option->getId()){
			case 'addGroup': case 'addService': case 'update': case 'delete':
			break;

			case 'save': case 'reset':
				if(!\App\Config\Services_Basic::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_Fields::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_OfferRowTypes::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_OfferDetails::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_OfferTypes::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_OfferConfirmations::getAdmin()->getChangedFlag()
					&& !\App\Config\Services_OfferFields::getAdmin()->getChangedFlag()) {
					$option->setDisabled();
				}
			break;

			case 'serviceOffer': case 'serviceFields': case 'serviceAttributes':
				foreach ($selection as $selectedItem) {
					$model = new \Modules\Admin\Config\Services\Basic\Model();
					$serviceCfg = \App\Config\Services_Basic::getAdmin();
					if (!$model->isGroup($selectedItem, $serviceCfg)) {
						$option->setDisabled(true);
					}
				}
			break;

			case 'moveUp':
				foreach ($selection as $selectedItem) {
					$model = new \Modules\Admin\Config\Services\Basic\Model();
					$serviceCfg = \App\Config\Services_Basic::getAdmin();
					if (!$model->canMoveUp($selectedItem, $serviceCfg)) {
						$option->setDisabled(true);
						$option->addMessage('info', $this->lang['index']['options']['reasons']['moveUp']['cannotMoveUp']);
					}
				}
			break;

			case 'moveDown':
				foreach ($selection as $selectedItem) {
					$model = new \Modules\Admin\Config\Services\Basic\Model();
					$serviceCfg = \App\Config\Services_Basic::getAdmin();
					if (!$model->canMoveDown($selectedItem, $serviceCfg)) {
						$option->setDisabled(true);
						$option->addMessage('info', $this->lang['index']['options']['reasons']['moveDown']['cannotMoveUp']);
					}
				}
			break;

			default:
				return false;
		}

		return true;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return NULL;
	}


	/**
	 * Action for adding new group in list
	 * @param Array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	public function actionAddGroup($R)
	{
		// instantiate message collector
		$msgs = \App\MessagesCollector::create();
		$closePopup = false;
		$formData = [];

		// if submit buttons has been pressed
		if ($R[$this->formSubmitButtonName]) {
			$formData = $R;
			// instantiate service config
			$serviceCfg = \App\Config\Services_Basic::getAdmin();

			try {
				$serviceCfg->itemInsert(
					$R['code'], [
						'name' => $R['name'],
						'type' => 'group',
					]
				);

				$msgs->addSuccess($this->lang['addGroup']['messages']['success']);
				$closePopup = true;
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}

		}

		// INSTANTIATE VIEW OBJECT
		$view = new View_AddGroup($this);

		// CLOSE POPUP
		$view->setClosePopup($closePopup);

		// ATTACH INFORMATION TO VIEW
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);
		$view->addInput('formData', $formData);
		$view->getMessagesCollector()->appendMessages($msgs);

		// RENDER VIEW
		return new \Engine\Mvc\Response\Html($view->render());
	}

	/**
	 * Action for adding new service
	 * @param Array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	public function actionAddService($R)
	{
		// instantiate message collector
		$msgs = \App\MessagesCollector::create();
		$_LANG = \App\Loader_Lang::getInstance()->getAll();
		$closePopup = false;
		$formData = [];

		// if submit buttons has been pressed
		if ($R[$this->formSubmitButtonName]) {
			$formData = $R;
			// instantiate service config
			$serviceCfg = \App\Config\Services_Basic::getAdmin();

			try {
				// insert new service
				$serviceCfg->itemInsert(
					$R['code'], [
						'type' => 		'service',
						'name' => 		$R['name'],
						'groupCode' => 	$R['group'],
						'category' 	=> 	$R['category'],
					]
				);

				// CLONED SERVICE //////////////////////////////////////////////////////////////////////////
				if ($R['clonedServiceType']) {

					// set general attributes
					$attrArr = \App\Config\Services_GeneralAttributes::getInstance()->get($R['clonedServiceType']);
					$attributes = \App\Config\Services_GeneralAttributes::getAdmin();
					$request = [];
					$request['category'] = [
						'type' 		=> $attrArr['category']['type'],
						'fieldName' => $attrArr['category']['fieldName']
					];
					if ($attrArr['category']['list']) {
						foreach ($attrArr['category']['list'] as $key=>$value) {
							$categoryList[$key] = $value;
						}
						$request['category']['list'] = $categoryList;
					}

					// product type
					$request['productType'] = [
						'type' 		=> $attrArr['productType']['type'],
						'fieldName' => $attrArr['productType']['fieldName']
					];
					if ($attrArr['productType']['list']) {
						foreach ($attrArr['productType']['list'] as $key=>$value) {
							$productTypeList[$key] = $value;
						}
						$request['productType']['list'] = $productTypeList;
					}

					// product multiplier
					$request['productMultiplier'] = [
						'type' 		=> $attrArr['productMultiplier']['type'],
						'fieldName' => $attrArr['productMultiplier']['fieldName']
					];
					if ($attrArr['productMultiplier']['list']) {
						foreach ($attrArr['productMultiplier']['list'] as $key=>$value) {
							$productMultiplierList[$key] = $value;
						}
						$request['productMultiplier']['list'] = $productMultiplierList;
					}

					// serviceSource
					$request['serviceSource'] = [
						'type' 		=> $attrArr['serviceSource']['type'],
						'fieldName' => $attrArr['serviceSource']['fieldName']
					];
					if ($attrArr['serviceSource']['list']) {
						foreach ($attrArr['serviceSource']['list'] as $key=>$value) {
							$serviceSourceList[$key] = $value;
						}
						$request['serviceSource']['list'] = $serviceSourceList;
					}

					// product name
					$request['productName'] = [
						'type' 		=> $attrArr['productName']['type'],
						'fieldName' => $attrArr['productName']['fieldName'],
					];

					// set the values
					$attributes->setCategory($R['code'], $request['category']);
					$attributes->setProductType($R['code'], $request['productType']);
					$attributes->setProductMultiplier($R['code'], $request['productMultiplier']);
					$attributes->setServiceSource($R['code'], $request['serviceSource']);
					$attributes->setProductName($R['code'], $request['productName']);

					$attributes->save();


					// set service attributes from the cloned service
					\App\Config\Services_Fields::getAdmin()->set($R['code'], \App\Config\Services_Fields::getAdmin()->get($R['clonedServiceType']));
					\App\Config\Services_OfferRowTypes::getAdmin()->set($R['code'], \App\Config\Services_OfferRowTypes::getAdmin()->get($R['clonedServiceType']));
					\App\Config\Services_OfferDetails::getAdmin()->set($R['code'], \App\Config\Services_OfferDetails::getAdmin()->get($R['clonedServiceType']));
					\App\Config\Services_OfferTypes::getAdmin()->set($R['code'], \App\Config\Services_OfferTypes::getAdmin()->get($R['clonedServiceType']));
					\App\Config\Services_OfferConfirmations::getAdmin()->set($R['code'], \App\Config\Services_OfferConfirmations::getAdmin()->get($R['clonedServiceType']));
					\App\Config\Services_OfferFields::getAdmin()->set($R['code'], \App\Config\Services_OfferFields::getAdmin()->get($R['clonedServiceType']));
				}
				else {
					// SET DEFAULT VALUES FOR SERVICE OFFER

					// offer row types
					$defaultRowTypesList=[];
					foreach ($this->cfg['defaultFields']['serviceOffer']['offerRowTypes'] as $rowTypeCode => $allowed) {
						if ($allowed) {
							$defaultRowTypesList[$rowTypeCode] = true;
						}
					}
					\App\Config\Services_OfferRowTypes::getAdmin()->set($R['code'], $defaultRowTypesList);

					// offer details
					\App\Config\Services_OfferDetails::getAdmin()->set($R['code'], $this->cfg['defaultFields']['serviceOffer']['offerDetails'] );

					// offer types
					$defaultOfferTypeList=[];
					foreach ($this->cfg['defaultFields']['serviceOffer']['offerTypes'] as $offerType) {
						$defaultOfferTypeList[$offerType]=$_LANG['offers']['offersTypes'][$offerType];
					}
					\App\Config\Services_OfferTypes::getAdmin()->set($R['code'], $defaultOfferTypeList);

					// offer confirmations
					\App\Config\Services_OfferConfirmations::getAdmin()->set($R['code'], $this->cfg['defaultFields']['serviceOffer']['offerConfirmations']);

					// offer fields
					\App\Config\Services_OfferFields::getAdmin()->set($R['code'], $this->cfg['defaultFields']['serviceOffer']['offerFields']);
				}

				$msgs->addSuccess($this->lang['addService']['messages']['success']);
				$closePopup = true;
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}

		}

		// INSTANTIATE VIEW OBJECT
		$view = new View_AddService($this);

		// CLOSE POPUP
		$view->setClosePopup($closePopup);

		// ATTACH INFORMATION TO VIEW
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);
		$view->addInput('formData', $formData);
		$view->getMessagesCollector()->appendMessages($msgs);

		// RENDER VIEW
		return new \Engine\Mvc\Response\Html($view->render());
	}


	public function actionUpdate($R)
	{
		// instantiate message collector
		$msgs = \App\MessagesCollector::create();
		$closePopup = false;
		// instantiate service config
		$serviceCfg = \App\Config\Services_Basic::getAdmin();

		// extract type of element
		$type = $R['type'];

		if (!$R[$this->formSubmitButtonName]) {
			$servicesList 		= $serviceCfg->getAll();
			$formData['action'] = 'update';

			if ($type == 'service') {
				$formData['code'] 		= $R['id'];
				$formData['group'] 		= $R['groupCode'];

				if ($servicesList[$formData['code']] and $servicesList[$formData['code']]['type'] == 'service') {
					$formData['name'] = $servicesList[$formData['code']]['name'];
					$formData['category'] 	= $servicesList[$formData['code']]['category'];
				}
				else {
					foreach ($servicesList as $groupCode => $groupDetails) {
						// service with a group
						if ($groupDetails['list'][$formData['code']]) {
							$formData['name'] 		= $groupDetails['list'][$formData['code']]['name'];
							$formData['group'] 		= $groupCode;
							$formData['category'] 	= $groupDetails['list'][$formData['code']]['category'];
						}
					}
				}
			}
			elseif ($type == 'group') {
				$formData['code'] = $R['id'];
				$formData['name'] = $servicesList[$formData['code']]['name'];
			}
		}
		else {
			$formData = $R;
			if ($type== 'group') {
				$formData['code'] = $R['id'];
			}
			else {
				$formData['code'] = $R['id'];
			}

			try {
				if ($type == 'group') {
					$serviceCfg->itemUpdate($formData['code'], [
						'type' => 'group',
						'name' => $formData['name'],
					]);
					$msgs->addSuccess($this->lang['update']['successMessage']['group']);
				}
				elseif ($type == 'service') {
					$serviceCfg->itemUpdate($formData['code'], [
						'type' => 		'service',
						'name' => 		$formData['name'],
						'groupCode' => 	$formData['group'],
						'category'	=>	$formData['category'],
					]);
					$msgs->addSuccess($this->lang['update']['successMessage']['service']);
				}

				$closePopup = true;
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}
		}

		// instantiate view
		if ($type == 'service') {
			$view = new View_AddService($this);
			$view->setPageTitle(sprintf($this->lang['update']['service']['pageTitle'], $R['name']));
		}
		elseif ($type == 'group') {
			$view = new View_AddGroup($this);
			$view->setPageTitle(sprintf($this->lang['update']['group']['pageTitle'], $R['name']));
		}
		else {
			throw new \Exception('Invalid type of element for action update');
		}

		$view->setClosePopup($closePopup);

		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);
		$view->addInput('formData', $formData);
		$view->getMessagesCollector()->appendMessages($msgs);

		// render view
		return new \Engine\Mvc\Response\Html($view->render());
	}

	/**
	 *  save the changes in services basic
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionSave(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$servicesCfg = \App\Config\Services_Basic::getAdmin();

		try {
			$servicesCfg->save();

			foreach ($recordsIds as $record) {
				$this->getListingSelection()->delete([$record]);
			}
			$msgs->addSuccess($this->lang['save']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError($e->getMessage());
		}
	}

	/**
	 * Move service or group up
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveUp(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$servicesCfg = \App\Config\Services_Basic::getAdmin();

		foreach ($recordsIds as $record) {
			try {
				$servicesCfg->itemMoveUp($record);

				// remove this record from the internal list
				$this->getListingSelection()->delete([$record]);
				$msgs->addSuccess($this->lang['moveUp']['messages']['success']);
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addError($e->getMessage());
			}
		}
	}

	/**
	 * Move service or group down
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveDown(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$servicesCfg = \App\Config\Services_Basic::getAdmin();

		foreach ($recordsIds as $record) {
			try {
				$servicesCfg->itemMoveDown($record);

				// remove this record from the internal list
				$this->getListingSelection()->delete([$record]);
				$msgs->addSuccess($this->lang['moveDown']['messages']['success']);
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addError($e->getMessage());
			}
		}
	}

	/**
	 *
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionDelete(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$servicesCfg = \App\Config\Services_Basic::getAdmin();

		foreach ($recordsIds as $record) {
			try {
				$servicesCfg->itemDelete($record);

				// remove this record from the internal list
				$this->getListingSelection()->delete([$record]);
				$msgs->addSuccess($this->lang['delete']['successMessage']);
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addError($e->getMessage());
			}
		}
	}

	/**
	 *
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionReset(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		// instantiate service config
		$servicesCfg = \App\Config\Services_Basic::getAdmin();
		$serviceFieldsCfg = \App\Config\Services_Fields::getAdmin();
		$servicesOfferRowTypes=\App\Config\Services_OfferRowTypes::getAdmin();
		$servicesOfferDetails=\App\Config\Services_OfferDetails::getAdmin();
		$servicesOfferTypes=\App\Config\Services_OfferTypes::getAdmin();
		$servicesOfferConfirmations=\App\Config\Services_OfferConfirmations::getAdmin();
		$servicesOfferFields=\App\Config\Services_OfferFields::getAdmin();

		try {
			$servicesCfg->reset();
			$serviceFieldsCfg->reset();
			$servicesOfferRowTypes->reset();
			$servicesOfferDetails->reset();
			$servicesOfferTypes->reset();
			$servicesOfferConfirmations->reset();
			$servicesOfferFields->reset();

			foreach ($recordsIds as $id ) {
				$this->getListingSelection()->delete([$id]);
			}
			$msgs->addSuccess($this->lang['reset']['successMessage']);
		}
		catch(\App\Config\MessageException $e) {
			$msgs->addError($e->getMessage());
		}
	}
}