<?php

class Users_Form_Admin_User extends Main_Users_Form_Admin_User {

	public function populateWithBean($bean) {
		$roles = array();
		foreach ($bean->sharedRole as $role) {
			$roles[$role->id] = true;
		}

		return $this->populate($roles + $bean->export());
	}

	public function init() {

		$exclude_id = $this->bean ? $this->bean->id : NULL;

		/**
		 * Dane do logowania
		 */
		$creditnails = array();

		$creditnails[] = new Zend_Form_Element_Text('name', array(
			'label' => 'Nazwa',
			'required' => true,
			'validators' => array(
				new Eppe_Validate_StringLength(array('min' => 4, 'max' => 20)),
				new Eppe_Validate_Db_NoRecordExists(array('bean' => 'user', 'column' => 'name', 'exclude_id' => $exclude_id))
			),
			'filters' => array(
				new Zend_Filter_StringTrim(),
				new Zend_Filter_StripTags()
			)
				)
		);

		$creditnails['pass'] = new Zend_Form_Element_Password('pass', array(
			'label' => 'Hasło',
			'validators' => array(
				new Zend_Validate_Identical('rep_pass'),
				new Eppe_Validate_StringLength(array('min' => 4, 'max' => 20))
			),
			'filters' => array(
				new Zend_Filter_StringTrim(),
				new Zend_Filter_StripTags()
			)
				)
		);

		if (NULL === $this->bean) {
			$creditnails['pass']->setRequired(true);
		}

		$creditnails[] = new Zend_Form_Element_Password('rep_pass', array(
			'label' => 'Powtórz hasło',
		        'required' => true,
				)
		);

		$this->addDisplayGroup($creditnails, 'creditnails', array('legend' => 'Dane do logowania'));

		/**
		 * Uprawnienia
		 */
		$roles = R::$f->begin()
				->select('*')
				->from('role')
				->where('id != 1')
				->and('name != "anonymous"')
				->and('name != "user"')
				->and('name != "loggedin"')
				->order('BY id ASC')
				->get();


		foreach ($roles as $role) {
			$privileges[$role['id']] = new Zend_Form_Element_Checkbox($role['id'], array('label' => $role['name'], 'class' => $role['name'], 'checked' => 'checked'));
		}

		$this->addDisplayGroup($privileges, 'privileges', array('legend' => 'Uprawnienia'));

		$this->addToolbar();
	}


	public function isValid($data) {
		$isValid = parent::isValid($data);

		foreach ($elements = $this->getDisplayGroup('privileges')->getElements() as $element) {
			if ($element->getValue())
				return $isValid;
		}
		reset($elements)->addError('Użtkownik musi być przypisany przynajmniej do jednej roli');
		return false;
	}

}

?>
