<?php

namespace Modules\Admin\UserProfile\Notification;

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

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\PopupAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['index'] = [ 'checkSection' => 'Modules/Admin/UserProfile', 'checkOption' => false ];
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{

		$formData = [];

		$notifStr = \App\EntityPreference\User::getInstance()->extSysResNotif;
		if ($notifStr) {
			$sys = unserialize($notifStr);
			if ($sys) {
				foreach ($sys as $key=>$value) {
					foreach ($value as $k=>$v) {
						$formData['sys'][$key][$k] = $k;
					}
				}
			}
		}

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		try {
			\DB::startTransaction();
			if ($R['sys']) {
				$notifications=serialize($R['sys']);
			}
			else {
				$notifications='';
			}

			\App\EntityPreference\User::getInstance()->extSysResNotif = $notifications;
			\DB::commitTransaction();
			$msgs->addSuccess($this->lang['index']['success']);
			return true;
		}
		catch (\App\Entity\Exception $ex) {
			\DB::rollbackTransaction();
			$msgs->addError($ex->getMessage());
			return false;
		}
	}

	/**
	 * Do some more stuff on the current controller/view right before the render is called.
	 * @param \App\Mvc\View_Window_FormAbstract $view
	 * @param array $formData
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$systemsListObj = new \App\EntityList\ImportedOrdersSystems();
		$systemsListObj->setColumns(['extResSys.name', 'extResSys.active']);
		$systemsListObj->setOrderBy('extResSys.name', 'ASC');
		$systemsListBulk = $systemsListObj->getExecution();
		$systemsList = [];
		foreach($systemsListBulk as $sys) {
			$systemsList[$sys['id']] = [ 'name' => $sys['name'], 'active' => $sys['active'] ];
		}

		$formData['systemsList'] = $systemsList;

		$view->addInput('formData', $formData);
	}
}