<?php

class lc_seo_editor_main extends ModuleTools
{
	public $validation=1;
	
	public function lc_list()
	{
		if (!access('read')) return LabCMS::i()->error403();
		$list=Factory::create('lc_seo_editor.list');
		$items=$list->get();
		self::_assign('list', $items);
		self::_setTpl('list');
	}
	
	public function lc_add()
	{
		if (!access('edit')) return LabCMS::i()->error403();
		$form=$this->_buildForm();
		if ($form->validate()) {
			$item=Factory::create('lc_seo_editor.tags');
			$item->add($form->getValue());
			refresh();
		}
		
		self::_assign('form', $this->_renderForm($form));
		self::_setTpl('form');
	}
	
	public function lc_edit()
	{
		if (!access('edit')) return LabCMS::i()->error403();
		if (!$item=Factory::create('lc_seo_editor.tags', $_GET['var1'])) return self::_error('Запись не найдена');
		$form=$this->_buildForm($item);
		if ($form->validate()) {
			$item->update($form->getValue());
			refresh();
		}
		
		self::_assign('form', $this->_renderForm($form));
		self::_setTpl('form');
	}
	
	public function lc_delete()
	{
		if (!access('edit')) return LabCMS::i()->error403();
		User::checkToken();
		if (!$item=Factory::create('lc_seo_editor.tags', $_GET['var1'])) return self::_error('Запись не найдена');
		$item->delete();
		refresh();
	}
	
	public function lc_sort()
	{
		if (!access('edit')) exit;
		User::checkToken();
		$list=Factory::create('lc_seo_editor.list');
		$list->setSort($_POST['item']);
		exit;
	}
	
	protected function _buildForm($item=null)
	{
		$form = Factory::create('HTML_QuickForm2', null, 'post', array('action'=>''));
		$token=$form->addElement('hidden', 'token', array('value'=>User::i()->token));

		$pattern=$form->addElement('text', 'pattern', null, array('label' => _m('Адрес:')));
		$title=$form->addElement('text', 'title', null, array('label' => _m('Title:')));
		$description=$form->addElement('textarea', 'description', null, array('label' => _m('Description:')));
		$keywords=$form->addElement('textarea', 'keywords', null, array('label' => _m('Keywords:')));
		$form->addElement('checkbox', 'walkthrough', null, array('label' => _m('Обрабатывать следующие правила')));
		
		$submit=$form->addElement('submit', 'save', array('value'=>_m('Сохранить')));
		
		$pattern->addRule('required', _m('Необходимо указать адрес'), null,	$this->validation);
		
		if ($item) {
			$form->addDataSource(Factory::create('HTML_QuickForm2_DataSource_Array', $item->getArray()));
		}
		return $form;
	}
}