<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class admin_groups_group extends DefaultObject
{
	protected $allowed_keys=array(
		'group_id', 'parent_id', 'group_name'
	);
	
	public function __construct($id=null)
	{
		$this->data['id']=&$this->data['group_id'];
		if (is_numeric($id)) $this->loadDataById($id);
	}
	
	public function loadDataById($id)
	{
		$data=Db::i()->selectRow("SELECT * FROM ?_groups WHERE group_id=?", $id);
		if ($data) {
			$this->set($data);
		}
	}
	
	public function delete()
	{
		if ($_GET['var1']>2) {
			$groups_tmp=$this->getChildGroups($this->id);
			$groups=array($this->id);
			if (count($groups_tmp))
			foreach ($groups_tmp as $group) {
				$groups[]=$group['group_id'];
			}
			//удаляем группу и подчиненные группы
			Db::i()->query("DELETE FROM ?_groups WHERE group_id IN (?a)", $groups);
			$users=Db::i()->selectCol("SELECT user_id FROM ?_users WHERE group_id IN (?a)", $groups);
			if ($users) {
				//всех пользователей из удаленных групп перекидываем в дефолтную группу
				Db::i()->query("UPDATE ?_users SET group_id=2 WHERE group_id IN (?a)", $groups);
				User::i()->resetCache($users);
			}
			unset($users);
		}
	}
	
	public function add($data)
	{
		$this-> _filterKeys($data);
		$this->id=Db::i()->query("INSERT INTO ?_groups SET ?a", $data);
		return true;
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query("UPDATE ?_groups SET ?a WHERE group_id=?", $data, $this->id);
	}
	
	protected function _resetItemCache()
	{
	}
	
	public function getChildGroups($id, $finish=false, $noSAGroup=true, $groups=array(), $indent=0)
	{
		$result=Db::i()->select(
			"SELECT group_id, group_name FROM ?_groups
			WHERE parent_id=? {AND group_id!=?} ORDER BY group_name",
			$id, ($noSAGroup?1:DBSIMPLE_SKIP)
		);
		if (count($result)) {
			foreach ($result as $val) {
				if ($val['group_id']==$finish) continue;
				$groups[]=array('group_id'=>$val['group_id'], 'group_name'=>$val['group_name'], 'indent'=>$indent);
				$groups=$this->getChildGroups($val['group_id'], $finish, $noSAGroup, $groups, $indent+1);
			}
		}
		return $groups;
	}
	
	public function getEditForm()
	{
		$form = Factory::create('HTML_QuickForm2', '', 'post', array('action'=>''));

		$name=$form->addElement('text', 'group_name', array('tabindex'=>1), array('label' => 'Название группы'));
		$name->addRule('required', 'Название группы не может быть пустым');
		if (!$this->id || $this->id>2) {
			$form->addElement(
				'select', 'parent_id', array('tabindex'=>2),
				array('label' => 'Родитель', 'options'=>$this->_prepareFormSelect())
			);
		}
		$form->addElement('hidden', 'token', array('value'=>User::i()->token));
		$form->addElement('submit', '', array('value'=>'Сохранить', 'tabindex'=>3));

		if ($this->id) $form->addDataSource(Factory::create('HTML_QuickForm2_DataSource_Array', $this->data));

		return $form;
	}
	
	protected function _prepareFormSelect()
	{
		$groups=$this->getChildGroups(0, $this->id);
		$options=array();
		foreach ($groups as $group) {
			$options[$group['group_id']]=str_repeat('&nbsp;', $group['indent']*10).$group['group_name'];
		}
		return $options;
	}
	
	public function toArray()
	{
		return $this->data;
	}
}