<?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 blocks_static_edit_block extends DefaultObject
{
	protected $allowed_keys=array('name', 'data', 'visible');
	
	public $validation=HTML_QuickForm2_Rule::ONBLUR_CLIENT_SERVER;
	
	public function __construct($id=null)
	{
		$this->data['id']=&$this->data['block_id'];
		if ($id) $this->loadDataById($id);
	}
	
	public function loadDataById($id)
	{
		$data=Db::i()->selectRow(
			"SELECT * FROM ?_blocks_static WHERE block_id=?", $id
		);
		
		if ($data) {
			$this->set($data);
		}
	}
	
	public function add($data)
	{
		$this->_filterKeys($data);
		$data['id']=Db::i()->query(
			"INSERT INTO ?_blocks_static (?#) VALUES(?a)", array_keys($data), array_values($data)
		);
		$block=Factory::create('blocks_static_edit.block');
		$block->set($data);
		return $block;
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query("UPDATE ?_blocks_static SET ?a WHERE block_id=?", $data, $this->id);
	}
	
	protected function _resetItemCache()
	{
	}

	public function delete()
	{
		Db::i()->query("DELETE FROM ?_blocks_static WHERE block_id=?", $this->id);
	}
	
	public function toggle()
	{
		$this->update(array('visible'=>$this->visible?0:1));
	}
	
	protected function _filterKeys(&$data)
	{
		foreach ($data as $key=>$v) {
			if (!in_array($key, $this->allowed_keys)) unset($data[$key]);
		}
	}
	
	public function __set($key, $value)
	{
		parent::__set($key, $value);
		if ($key=='text') {
			$this->_setAnonce();
		}
	}
	
	public function buildEditForm()
	{
		$form = Factory::create('HTML_QuickForm2', null, 'post', array('action'=>'#'));
		$token=$form->addElement('hidden', 'token', array('value' => User::i()->token));
		
		$name=$form->addElement('text', 'name', null, array('label' => _m('Название блока:')));
		
		//передаем название поля к которому надо прикрепить визуальный редактор
		Tpl::i()->assign('field', 'data');
		$form->addElement('static', '', null, array('label' => '&nbsp;', 'content'=>Tpl::i()->fetch('WYSIWYG/editor.tpl')));
		
		$data=$form->addElement('textarea', 'data', array('id'=>'data'), array('label' => _m('Данные:')));
		
		$name->addRule('required', _m('Введите название блока'), null, $this->validation);
		
		$form->addElement('submit', null, array('value'=>_m('Сохранить')));
		
		if ($this->id) {
			$form->addDataSource(Factory::create('HTML_QuickForm2_DataSource_Array', $this->data));
		}
		
		return $form;
	}
}