<?php
namespace Modules\Authenticate;

class View_ChangePassword 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();

		$this->buildForm_user($form, $formValues);

		$containers = $form->getChilds();
		if ($containers[0]) {
			$containers[0]->getMessagesObj()->addFromMessageCollector($this->getMessagesCollector());
		}
		$form->addButton(new \Engine\Form\Button\Submit('Set new password', null));

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

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

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

		return $result;
	}


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

		// create container
		$fieldset = \Engine\Form\Container\Fieldset::create();
		$fieldset->setLabel('Password expired, enter new password');

		$fieldset->addElement(\Engine\Form\Input\Text::create('Username', null, $this->input['oldCredentials']['username'])
			->setDisabled()
		);

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

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

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