<?php
namespace Modules\Authenticate;

class View_Register extends \App\Mvc\ViewAbstract
{
	public function render()
	{
		$smarty = \Engine\Smarty\SmartyMultiton::getInstance();

		// temporary store all internal smarty vars. render_prepare() will overwrite some of the existing variables
		$tplVars = $smarty->getTemplateVars();

		$this->render_prepare($smarty);

		// run plugin trigger for
		\Engine\Plugins\Manager::getInstance()->executeEvent("MVC-BeforeViewRender-[{$this->controller->getModule()}-{$this->controller->getAction()}]", ['view'=>$this]);

		// define form
		$formValues = $this->input['formValues'];
		$form = \Engine\Form\General::create();
		$form->setFocus();
		$result = $this->renderRegisterPage($form, $formValues);
		$containers = $form->getChilds();
		if ($containers[0]) {
			$containers[0]->getMessagesObj()->addFromMessageCollector($this->getMessagesCollector());
		}
		$form->addButton(new \Engine\Form\Button\Submit('Register', null));

		$form->addElement(\Engine\Form\Input\Hidden::create(null, 'register', 1));

		$result = $smarty->fetch(__DIR__."/_tpl/register.tpl");

		// re-assigns all saved smarty vars
		$smarty->clearAllAssign();
		foreach ($tplVars as $k=>$v) {
			$smarty->assign($k, $v);
		}

		return $result;
	}

	/**
	 * Create formular for register
	 */
	protected function renderRegisterPage(\Engine\Form\General $form, array $formValues)
	{
		if (in_array('DB', $this->input['unregisteredSections'])) {
			$this->buildForm_database($form, $formValues);
		}
		else {
			if (in_array('user', $this->input['unregisteredSections'])) {
				$this->buildForm_user($form, $formValues);
			}

			if (in_array('office', $this->input['unregisteredSections'])) {
				$this->buildForm_office($form, $formValues);
			}

			if (in_array('department', $this->input['unregisteredSections'])) {
				$this->buildForm_department($form, $formValues);
			}

			if (!in_array('user', $this->input['unregisteredSections']) && in_array('adminUser', $this->input['unregisteredSections'])) {
				$this->buildForm_adminUser($form, $formValues);
			}
		}

		 // add warning messages if exists one
		if ($this->messagesCollector) {

			$inputMap = [
				'username' => 'user[username]',
				'password' => 'user[password2]',
				'password2' => 'user[password2]',
				'firstName' => 'user[firstName]',
				'lastName' => 'user[lastName]',
			];

			$newMessagesCollector = new \App\MessagesCollector();

			foreach ($this->messagesCollector->getMessages() as $message) {
				if ($message->getField() && $inputMap[$message->getField()]) {
					$form->findElementByName($inputMap[$message->getField()])->addMessage($message->getType(), $message->getText());
				}
				else {
					$newMessagesCollector->addMessage($message);
				}
			}

			$this->messagesCollector = $newMessagesCollector;
		}
	}

	protected function buildForm_database(\Engine\Form\General $form, array $formValues)
	{
		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('Database');

		$fieldset->addElement(\Engine\Form\Input\Text::create('Host', 'db[host]', $formValues['db']['host']));

		$fieldset->addElement(\Engine\Form\Input\Text::create('Name', 'db[name]', $formValues['db']['name']));

		$fieldset->addElement(\Engine\Form\Input\Text::create('Username', 'db[username]', $formValues['db']['username']));

		$fieldset->addElement(\Engine\Form\Input\Password::create('Password', 'db[password]', ''));

		$form->addContainer($fieldset);
	}

	protected function buildForm_office(\Engine\Form\General $form, array $formValues)
	{
		// get configs for user
		$cfg = \Entity\Office::loadCFG();

		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('First office');

		$fieldset->addElement(\Engine\Form\Input\Text::create('Name', 'office[name]', $formValues['office']['name'])
			->importFromConfig($cfg['name'])
		);

		$form->addContainer($fieldset);
	}

	protected function buildForm_department(\Engine\Form\General $form, array $formValues)
	{
		// get configs for user
		$cfg = \Entity\Department::loadCFG();

		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('First department');

		$fieldset->addElement(\Engine\Form\Input\Text::create('Name', 'department[name]', $formValues['department']['name'])
			->importFromConfig($cfg['name'])
		);

		$form->addContainer($fieldset);
	}

	protected function buildForm_adminUser(\Engine\Form\General $form, array $formValues)
	{
		// get configs for user
		$cfg = \Entity\Department::loadCFG();

		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('Setup user with admin rights');

		// get & format users list
		$users = new \App\EntityList\Users();
		$users->setColumn('firstName');
		$users->setColumn('lastName');
		$users->setOrderBy('firstName', 'ASC');

		$usersList = [];
		array_map(function($elm) use (&$usersList) {
			$usersList[$elm['id']] = sprintf("%s %s", $elm['lastName'], $elm['firstName']);
		}, $users->exportRecords());

		$fieldset->addElement(\Engine\Form\Input\Select::create('Admin user', 'adminUser[id]', $formValues['adminUser']['id'], $usersList)
			->importFromConfig($cfg['name'])
		);



		$form->addContainer($fieldset);
	}

	protected function buildForm_user($form, $formValues)
	{
		// get configs for user
		$cfg=\Entity\User::loadCFG();

		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('First user');

		// THE FIRST USER FIELDS //////////////////////////////////////////////////////////////////

		$fieldset->addElement(\Engine\Form\Input\Text::create('Username', 'user[username]', $formValues['user']['username'])
			->importFromConfig($cfg['username'])
		);

		$fieldset->addElement(\Engine\Form\Input\Password::create('Password', 'user[password]', $formValues['user']['password'])
			->importFromConfig($cfg['password'])
			->setStyle('autoEvaluate', true)
		);

		$fieldset->addElement(\Engine\Form\Input\Password::create('Password check', 'user[password2]', $formValues['user']['password2'])
			->importFromConfig($cfg['password'])
			->setStyle('autoEvaluate', true)
		);

		$fieldset->addElement(\Engine\Form\Input\Text::create('First name', 'user[firstName]', $formValues['user']['firstName'])
			->importFromConfig($cfg['firstName'])
		);

		$fieldset->addElement(\Engine\Form\Input\Text::create('Last name', 'user[lastName]', $formValues['user']['lastName'])
			->importFromConfig($cfg['lastName'])
		);

		$fieldset->addElement(\Engine\Form\Input\Text::create('Email', 'user[email]', $formValues['user']['email'])
			->importFromConfig($cfg['email'])
			->setMandatory(true)
		);


		if (!in_array('office', $this->input['unregisteredSections'])) {
			// get & format offices list
			$offices = new \App\EntityList\Offices();
			$offices->setColumn('name');
			$offices->setOrderBy('name', 'ASC');

			$officesList = [];
			array_map(function($elm) use (&$officesList) {
				$officesList[$elm['id']] = sprintf("%s", $elm['name']);
			}, $offices->exportRecords());

			$fieldset->addElement(\Engine\Form\Input\Select::create('Office', 'user[idOffice]', $formValues['user']['idOffice'], $officesList)
				->importFromConfig($cfg['idOffice'])
			);
		}

		if (!in_array('department', $this->input['unregisteredSections'])) {
			// get & format departments list
			$offices = new \App\EntityList\Departments();
			$offices->setColumn('name');
			$offices->setOrderBy('name', 'ASC');

			$deptList = [];
			array_map(function($elm) use (&$deptList) {
				$deptList[$elm['id']] = sprintf("%s", $elm['name']);
			}, $offices->exportRecords());

			$fieldset->addElement(\Engine\Form\Input\Select::create('Department', 'user[idDepartment]', $formValues['user']['idDepartment'], $deptList)
				->importFromConfig($cfg['idDepartment'])
			);
		}

		$form->addContainer($fieldset);
	}
}
