<?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 guest_main extends ModuleTools
{
	public function __construct()
	{
		$this->module=Factory::create('guest.module');
	}

	public function show()
	{
		$page=(!empty($_GET['var1']))?intval($_GET['var1']):1;
		
		$data=$this->module->getPostsByPage(config::get('guestbook_posts_at_page'), $page);

		if ($data['count']) {
			self::_assign("posts", $data['collection']);
			self::_assign("pager", $this->module->getPager($data['count'], $page, config::get('guestbook_posts_at_page')));
		}
		self::_setTpl("guest");
	}
	
	public function edit()
	{
		if(!access('admin')) return LabCMS::i()->error403();
		if (!$post=$this->module->getPostById($_GET['var1'])) return self::_error(_m('Комментарий не найден'));
		
		$form=$this->module->getPostEditForm($post);

		if ($form->validate()) {
			$this->module->updatePost($post, $form->getValue());
			refresh('', $_REQUEST['redirect']?$_REQUEST['redirect']:_url());
		}
		
		self::_setTpl('form');
		self::_assign('post', $post);
		self::_assign('form', $this->_renderForm($form));
	}
	
	public function add()
	{
		if(!access('add')) return LabCMS::i()->error403();
		
		$form=$this->module->getPostEditForm();
		
		if (User::i()->isGuest()) $this->_botOborCheck($form);

		if ($form->validate()) {
			if ($post=$this->module->addPost($form->getValue())) {
				$this->_sendEmailNotify($post);
				refresh();
			}
		}
		self::_setTpl('form');
		self::_assign('form', $this->_renderForm($form));
	}
	
	public function delete()
	{
		if(!access('admin')) return LabCMS::i()->error403();
		User::checkToken();
		if (!$post=$this->module->getPostById($_GET['var1'])) return self::_error(_m('Комментарий не найден'));
		if ($this->module->deletePost($post)) {
			refresh('', $_REQUEST['redirect']?$_REQUEST['redirect']:_url());
		}
	}
	
	protected function _sendEmailNotify($post)
	{
		if (config::get('guestbook_email_notify') && config::get('core.admin_mail')) {
			$mail=Factory::create('Mailer', config::get('core.admin_mail'));
			$mail->From = 'guestbook@'.config::get('core.domain');
			$mail->FromName = "Робот гостевой";
			$mail->AddReplyTo('guestbook@'.config::get('core.domain'), "Робот гостевой");
			$mail->WordWrap = 80;
			$mail->Subject = 'Новое сообщение в гостевой книге '.config::get('core.domain');
			self::_assign('post', $post);
			$mail->Body    = Tpl::i()->fetch(LabCMS::i()->getModuleName()."/email_notify.tpl");
			$mail->Send();
		}
	}

	protected function _botOborCheck($form)
	{
		if ($form->isSubmitted()) {
			if (Botobor_Keeper::get()->isRobot()) {
				die('злобный бот!');
			}
			//после восстановления полей снова передаем данные в обработчик формы
			$form->setDatasources(array(Factory::create('HTML_QuickForm2_DataSource_SuperGlobal')));
		}
	}
}