<?php
namespace Modules\Admin\ExportData\ExportFields;


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

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();
		$this->actionsCfg['generateInputMatrixRow'] = ['checkOption' => false, 'checkSection' => false];
	}

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

		$recordsList = [];

		$fieldsList = \App\Config\ExportData_Fields::getInstance()->getFieldsAll($R['exportType']);

		foreach ($fieldsList as $fieldCode => $fieldDetails) {
			$recordsList[] = [
				"code"=>$fieldCode,
				"name"=>$fieldDetails['name'],
				"active"=>$fieldDetails['active'],
			];
		}

		return [
			"exportFieldsMatrix"	=>	$recordsList,
			'exportType'			=>	$R['exportType'], //used to define pageTitle/sectionTitle in the formAdmin
		];

	}



	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		$nullExports = array_filter($R['exportFieldsMatrix'], function($item){
			if (!strlen($item['code']) and !strlen($item['name'])) return true;
		});

		if (count($nullExports)) {
			$msgs->addError($this->lang['index']['noneError']);
			return false;
		}

		$exportFields = [];

		foreach ($R['exportFieldsMatrix'] as $fieldDetails) {
			if (strlen($fieldDetails['code']) or strlen($fieldDetails['name'])) {
				$exportFields[$fieldDetails['code']] = $fieldDetails;
			}
		}

		try {

			\App\Config\ExportData_Fields::getAdmin()->setFields($R['exportType'], $exportFields);
			\App\Config\ExportData_Fields::getAdmin()->save();
			$msgs->addSuccess($this->lang['index']['saveOk']);

		}
		catch (\App\Config\MessageException $e) {
			$msgs->addError(sprintf($this->lang['index']['saveError'], $e->getMessage()));
			return false;
		}

		return true;
	}



	/**
	 * Render a new matrix row
	 * @param array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	protected function actionGenerateInputMatrixRow($R)
	{
		$matrix = \Engine\Cache\General::getInstance('disk')->get($R['inputMatrixStorageId']);
		if (!$matrix) {
			throw new \Engine\Mvc\ControllerException("Matrix not found");
		}

		$view = $this->buildViewObjectFromCurrentModuleForAction('index');

		return new \Engine\Mvc\Response\Json(['responseRow'=>$view->generateInputMatrixRow($matrix, $R['index'], $R['counter'])]);
	}
}
