<?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 adv_rotator_editor_place extends DefaultObject
{
	protected $allowed_keys=array('name', 'describe', 'active');
	
	public $validation=HTML_QuickForm2_Rule::ONBLUR_CLIENT_SERVER;
	
	public function __construct($id=null)
	{
		$this->data['id']=&$this->data['place_id'];
		if ($id) $this->loadDataById($id);
	}

	public function loadDataById($id)
	{
		if ($data=Db::i()->selectRow("SELECT * FROM ?_ad_rotator_places WHERE place_id=?", $id)) {
			$this->set($data);
		}
	}
	
	public function getAll()
	{
		$data=Db::i()->select(
			"SELECT *
			FROM ?_ad_rotator_places
			ORDER BY name, active DESC"
		);
		$result=array();
		if ($data) {
			foreach ($data as $item) {
				$obj=Factory::create('adv_rotator_editor.place');
				$obj->set($item);
				$result[$obj->id]=$obj;
			}
		}
		return $result;
	}
	
	public function getChildren()
	{
		$data=Db::i()->select("SELECT * FROM ?_ad_rotator_values WHERE place_id=?", $this->id);
		$result=array();
		if ($data) {
			foreach ($data as $item) {
				$obj=Factory::create('adv_rotator_editor.value');
				$obj->set($item);
				$result[$obj->id]=$obj;
			}
		}
		return $result;
	}
	
	public function add($data)
	{
		$this->_filterKeys($data);
		$data['id']=Db::i()->query("INSERT INTO ?_ad_rotator_places (?#) VALUES(?a)", array_keys($data), array_values($data));
		$place=Factory::create('adv_rotator_editor.place');
		$place->set($data);
		return $place;
	}
	
	public function toggle()
	{
		$this->update(array('active'=>$this->active?0:1));
	}
	
	public function delete()
	{
		Db::i()->query(
			"DELETE p, v
			FROM ?_ad_rotator_places p
			LEFT JOIN ?_ad_rotator_values v ON p.place_id=v.place_id
			WHERE p.place_id=?", $this->id
		);
	}
	
	protected function _updateDB(&$data)
	{
		return Db::i()->query("UPDATE ?_ad_rotator_places SET ?a WHERE place_id=?", $data, $this->id);
	}
	
	protected function _resetItemCache()
	{
	}
	
	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('Название:')));
		$describe=$form->addElement('textarea', 'describe', null, array('label' => _m('Описание:')));
		
		$name->addRule('required', _m('Название не может быть пустым'), null, $this->validation);
		$describe->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;
	}
}