<?php
namespace Modules\Admin\Config\CorporateGroupsManagement;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing
{
	/**
	 *************************************************************************************
	 *************************************************************************************
	 *************************************************************************************
	 *
	 * Please pay attention that any changes in the corporate groups management files
	 * might affect the supplier groups management files.
	 *
	 **************************************************************************************
	 **************************************************************************************
	 **************************************************************************************
	 */

	/**
	 * Store the ordering list columns
	 *
	 * @var array
	 */
	protected $listOrderingColumns = [];

	/**
	 *Store the groups ids list
	 *
	 * @var array
	 */
	protected  $groupsIdsList = [];

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

		$this->actionsCfg['addGroup'] = 			['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['addGroupElement'] = 		['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveUp'] 	= 			['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['moveDown'] 	= 			['checkSection' => true, 	'checkOption' => false];
		$this->actionsCfg['update'] = 				['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];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		switch($option->getId()){
			case 'addGroupElement':
				// disable the option for the `groupElement` row type
				if ($selection) {
					foreach ($selection as $id) {
						if (!in_array($id, $this->loadGroupsCfg()->getGroupsIdsList())) {
							$option->setDisabled()->addMessage('warning', $_LANG['noAccessToOption']);
						}
					}
				}
			break;

			case 'moveUp':
				foreach ($selection as $selectedItem) {
					$model = $this->getModel();
 					if (!$model->canMoveUp($selectedItem)) {
 						$option->setDisabled(true);
 						$option->addMessage('info', $this->lang['index']['options']['reasons']['moveUp']['cannotMoveUp']);
 					}
				}
			break;

			case 'moveDown':
				foreach ($selection as $selectedItem) {
					$model = $this->getModel();
					if (!$model->canMoveDown($selectedItem)) {
						$option->setDisabled(true);
						$option->addMessage('info', $this->lang['index']['options']['reasons']['moveUp']['cannotMoveDown']);
					}
				}
			break;

			case 'addGroup': case 'update': case 'delete':
			break;

			case 'save': case 'reset':
				if (!$this->loadGroupsCfg()->getChangedFlag()) {
					$option->setDisabled();
				}
			break;

			default:
				return false;
		}

		return true;
	}

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

		// if submit buttons has been pressed
		if ($R[$this->formSubmitButtonName]) {
			$idGroupElement = mb_substr(uniqid(), 4) . \Engine\RandomGenerator::randomString(4);

			try {
				$this->loadGroupsCfg()->addGroupElement($formData['idGroup'], $idGroupElement, $formData['groupElement']);
				$msgs->addSuccess($this->lang['addGroupElement']['successMessage']);
				$closePopup = true;
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}
		}

		// INSTANTIATE VIEW OBJECT
		$viewClassName = getClassNamespace(get_called_class()) . '\View_AddGroupElement'; // making sure that we are using the right namespace - (ex - \Modules\Admin\Config\SupplierGroupsManagement)
		$view = new $viewClassName($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 group in list
	 *
	 * @param Array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	protected 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;
			$groups = [];
			$idGroup = mb_substr(uniqid(), 4) . \Engine\RandomGenerator::randomString(4);
			$groups[$idGroup]['groupName'] = $formData['groupName'];
			foreach($formData['groupElements'] as $groupElement) {
				$idGroupElement = mb_substr(uniqid(), 4) . \Engine\RandomGenerator::randomString(4);
				$groups[$idGroup]['groupElements'][$idGroupElement] = $groupElement;
			}

			try {
				foreach ($groups as $idGroup=>$group) {
					$this->loadGroupsCfg()->itemInsert($idGroup, $group);
				}
				$msgs->addSuccess($this->lang['addGroup']['successMessage']);
				$closePopup = true;
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addWarning($e->getMessage());
			}

		}

		// INSTANTIATE VIEW OBJECT
		$viewClassName = getClassNamespace(get_called_class()) . '\View_AddGroup'; // making sure that we are using the right namespace - (ex - \Modules\Admin\Config\SupplierGroupsManagement)
		$view = new $viewClassName($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());
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::actionUpdate()
	 */
	protected function actionUpdate($R)
	{
		// instantiate message collector
		$msgs = \App\MessagesCollector::create();
		$closePopup = false;

		// instantiate groups config
		$groupsList = $this->loadGroupsCfg()->getAll();

		// IF SUBMIT BUTTON HAS BEEN PRESSED ------------------------------------------------------
		if ($R[$this->formSubmitButtonName]) {
			$formData = $R;
			if ($groupsList[$formData['id']]) {
				// GROUP
				$groupDetails = $groupsList[$formData['id']];

				if ($formData['groupName']) {
					$groupDetails['groupName'] = $formData['groupName'];
				}

				try {
					$this->loadGroupsCfg()->itemUpdate($formData['id'], $groupDetails);
					$msgs->addSuccess($this->lang['updateGroup']['successMessage']);
					$closePopup = true;
				}
				catch (\App\Config\MessageException $e) {
					$msgs->addWarning($e->getMessage());
				}
			}
			else {
				// GROUP ELEMENT
				try {
					$this->loadGroupsCfg()->updateGroupElement($formData['idGroup'], $formData['id'], $formData['groupElement']);
					$msgs->addSuccess($this->lang['updateGroupElement']['successMessage']);
					$closePopup = true;
				}
				catch (\App\Config\MessageException $e) {
					$msgs->addWarning($e->getMessage());
				}
			}
		}
		// LOAD DEFAULT FORM DATA -----------------------------------------------------------------
		else {
			// GET FORM DATA
			$formData['action'] = 'update';

			// check if the id is of a group...
			if ($groupsList[$R['id']]) {
				$formData['groupName'] = $groupsList[$R['id']]['groupName'];
			}
			// ... or an element
			else {
				foreach ($groupsList as $idGroup=>$group) {
					if (key_exists($R['id'], $group['groupElements'])) {
						$formData['idGroup'] = $idGroup;
						$formData['groupElement'] = $group['groupElements'][$R['id']];
						break;
					}
				}
			}
		}

		// INSTANTIATE VIEW OBJECT
		if ($groupsList[$R['id']]) {
			$viewClassName = getClassNamespace(get_called_class()) . '\View_AddGroup'; // making sure that we are using the right namespace - (ex - \Modules\Admin\Config\SupplierGroupsManagement)
			$view = new $viewClassName($this);
			$view->setPageTitle($this->lang['updateGroup']['pageTitle']);
		}
		else {
			$viewClassName = getClassNamespace(get_called_class()) . '\View_AddGroupElement'; // making sure that we are using the right namespace - (ex - \Modules\Admin\Config\SupplierGroupsManagement)
			$view = new $viewClassName($this);
			$view->setPageTitle($this->lang['updateGroupElement']['pageTitle']);
		}

		// 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());
	}

	/**
	 * Save the configuration file
	 *
	 * @param array $R
	 * @return \Engine\Mvc\Response\None
	 */
	protected function actionSave($R)
	{
		$msgs = \App\MessagesCollector::create();

		try {
			$this->loadGroupsCfg()->save();
			$msgs->addSuccess($this->lang['save']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError($e->getMessage());
		}

		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}


	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::delete_doDelete()
	 */
	protected function delete_doDelete($recordsIds, \App\MessagesCollector $msgs, $R)
	{
		foreach ($recordsIds as $recordId) {
			try {
				$this->loadGroupsCfg()->itemDelete($recordId);
				// remove this record from the internal list
				$this->getListingSelection()->delete([$recordId]);
				$msgs->addSuccess($this->lang['delete']['successMessage']);
			}
			catch (\App\Config\MessageException $e) {
				$msgs->addError($e->getMessage());
			}
		}
	}

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

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{
		return [];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_doInsert()
	 */
	protected function insert_doInsert($formData, \App\MessagesCollector $msgs)
	{}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_getDefaultFormData()
	 */
	protected function update_getDefaultFormData($idEntity)
	{
		return [];
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_doUpdate()
	 */
	protected function update_doUpdate($formData, \App\MessagesCollector $msgs)
	{}

	/**
	 * Load groups configs
	 */
	protected function loadGroupsCfg()
	{
		return \App\Config\CorporateGroups::getAdmin();
	}

	protected function getModel()
	{
		return new \Modules\Admin\Config\CorporateGroupsManagement\Model();
	}

	/**
	 * Move group or element up
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveUp(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$groupsCfg = $this->loadGroupsCfg();

		foreach ($recordsIds as $record) {
			try {
				$groupsCfg->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 group or element down
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionMoveDown(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$groupsCfg = $this->loadGroupsCfg();

		foreach ($recordsIds as $record) {
			try {
				$groupsCfg->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());
			}
		}
	}

	/**
	 * Reset the changes in groups
	 * @param array $R
	 */
	protected function actionReset($R)
	{
		$msgs = \App\MessagesCollector::create();

		$groupsCfg = $this->loadGroupsCfg();

		try {
			$groupsCfg->reset();
			$this->getListingSelection()->clear();
			$msgs->addSuccess($this->lang['reset']['successMessage']);
		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError($e->getMessage());
		}

		$R['listing']['options'] = [
				'render' => 'json',
				'section' => ['global', ],
		];
		$response = $this->actionListRecords($R);
		$response->headers->loadMessages($msgs);

		return $response;
	}
}
