<?php
namespace ModulesAbstract\PluginReports\ConfigUDEFListing;

abstract class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing
{
	protected $listOrderingColumns = [];	// ordering is done by the UDEF data processor

	protected $absLang = [];

	protected $model = null;

	protected function initialize()
	{
		parent::initialize();

		$this->absLang = \App\Loader_Lang::getInstance()->loadAppFile('_customLoad/modulesAbstract/pluginReports/configUdefListing/ConfigUDEFListing.lang.php')->getSection("ModulesAbstract/PluginReports/ConfigUDEFListing");

		// having access to this section will grant access to all options
		$this->actionsCfg['insert'] = [ 'checkOption' => false, ];
		$this->actionsCfg['update'] = [ 'checkOption' => false, ];
		$this->actionsCfg['delete'] = [ 'checkOption' => false, ];
	}

	/**
	 * Builds the model
	 * @return mixed
	 */
	public function buildModel()
	{
		if ($this->model) {
			return $this->model;
		}
		$class = getClassNamespace(get_class($this)).'\Model';
		$model = new $class();
		$this->model = $model;
		return $model;
	}

	protected function actionIndex($R)
	{
		// NOTE: adding &config[ignoreConfigs]=1 to the URL will basically reset ALL configs. It should be used if the conig form somehow gets broken and no toher recovery is possible. !!! USE WITH CAUTION !!!
		if (SHOW_DEBUGS && isset($R['config']['ignoreConfigs'])) {
			$this->buildModel()->saveUDEFConfigs([]);
		}

		return parent::actionIndex($R);
	}


	/**
	 * Returns an array of default values for insert form.
	 * @return Array
	 */
	protected function insert_getDefaultFormData($R)
	{
		return [];
	}

	/**
	 * Does the actual "insert" operation upon form submit.
	 * @param array $formData
	 * @param \App\MessagesCollector $msgs
	 * @return boolean
	 */
	protected function insert_doInsert($formData, \App\MessagesCollector $msgs)
	{
		$UDEFConfigs = $this->buildModel()->getUDEFConfigs();
		$UDEFConfigs[] = [	// append to the array
			'corporateFilter' => 	$formData['corporateFilter'],
			'corporate' => 			$formData['corporate'],
			'corporateSegmentId' => $formData['corporateSegmentId'],
			'corporateGroupIds' => 	$formData['corporateGroupIds'],
			'UDEF' => 				$formData['UDEF'],
		];

		$this->buildModel()->saveUDEFConfigs($UDEFConfigs);

		$msgs->addSuccess($this->absLang['index']['action']['save']['success']);

		// store the "id" of the new record. This needs to be a non-falsey value, it's not used anywhere
		$this->insertIdRecord = count($UDEFConfigs);
		return true;
	}

	/**
	 * Returns an array of default values for update form.
	 * @param int $idEntity
	 * @return Array
	 */
	protected function update_getDefaultFormData($idEntity)
	{
		$UDEFConfigs = $this->buildModel()->getUDEFConfigs();
		return (array)$UDEFConfigs[$idEntity];
	}

	/**
	 * Does the actual "update" operation upon form submit.
	 * @param array $formData
	 * @param \App\MessagesCollector $msgs
	 * @return boolean
	 */
	protected function update_doUpdate($formData, \App\MessagesCollector $msgs)
	{
		$idEntity = (int)$formData['id'];
		$UDEFConfigs = $this->buildModel()->getUDEFConfigs();
		$UDEFConfigs[$idEntity] = [
			'corporateFilter' => 	$formData['corporateFilter'],
			'corporate' => 			$formData['corporate'],
			'corporateSegmentId' => $formData['corporateSegmentId'],
			'corporateGroupIds' => 	$formData['corporateGroupIds'],
			'UDEF' => 				$formData['UDEF'],
		];

		$this->buildModel()->saveUDEFConfigs($UDEFConfigs);

		$msgs->addSuccess($this->absLang['index']['saveOk']);
		return true;
	}

	/**
	 * Returns an array of default values for list view.
	 * @return Array
	 */
	protected function list_getDefaultParams()
	{
		$cfg = (array)$this->cfg['listingParams'];
		return $cfg;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{
		$selectionSize = count($selection);
		switch ($option->getId()) {
			case 'insert':
			break;

			case 'update':
			break;

			case 'delete':
			break;

			default:
				return false;
		}

		return true;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::delete_doDelete()
	 */
	protected function delete_doDelete(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		// this needs to exists because the abstract parent requires it
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		$UDEFConfigs = $this->buildModel()->getUDEFConfigs();
		$UDEFConfig = $UDEFConfigs[$id];
		switch ($UDEFConfig['corporateFilter']) {
			case 'corporate':
				$corporate = \Entity\Corporate::select($UDEFConfig['corporate']['id']);
				return ($corporate->recordExists()?$corporate->company:'');

			case 'segment':
				$corporateSegment = \Entity\CorporateSegment::select($UDEFConfig['corporateSegmentId']);
				return ($corporateSegment->recordExists()?$corporateSegment->name:'');

			case 'group':
				$groups = [];
				foreach ($UDEFConfig['corporateGroupIds'] as $groupId) {
					$groupElemDetails = \App\Config\CorporateGroups::getInstance()->getGroupElementDetailsById($groupId);
					$groups[$groupElemDetails['groupName']][] = $groupElemDetails['groupElementName'];
				}

				// return the "pretty" groups details
				return implode(', ', array_map(function($groupName, $groupElements) {
					return "$groupName: " . implode(', ', $groupElements);
				}, array_keys($groups), $groups));

			case 'any':
				return 'any';
		}

		return $id;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::bulkActionDelete()
	 * @throws \Exception
	 */
	protected function bulkActionDelete(array $recordsIds, \App\MessagesCollector $msgs, $R)
	{
		$UDEFConfigs = $this->buildModel()->getUDEFConfigs();

		foreach ($recordsIds as $id) {
			unset($UDEFConfigs[$id]);
		}
		$this->getListingSelection()->delete($recordsIds);

		// re-index the array, I'm not sure this is necessary
		// $UDEFConfigs = array_values($UDEFConfigs);

		$this->buildModel()->saveUDEFConfigs($UDEFConfigs);

		$msgs->addSuccess($this->absLang['index']['deleteOk']);
	}

}