<?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
*/

if ($mode=="delete")
{
	User::checkToken();
	Db::i()->query("DELETE FROM ?_guest WHERE msg_id=?", $_GET['var1']);
	LabCMS::i()->reset_cache();
	refresh();
}

//вывод смайликов
Tpl::i()->assign("js_smiles", bbcode_smiles_js(4,4));
$mod_template="edit_post.tpl";

$form = new HTML_QuickForm2('guest_form', 'post', array('action'=>''));
$form->addElement('hidden', 'token', array('value' => User::i()->token));

if ($mode=="edit")
{
	$post_info=Db::i()->selectRow("SELECT msg_id, g.email, login, name, msg, answer
								FROM ?_guest g
								LEFT JOIN ?_users u ON g.user_id=u.user_id
								WHERE msg_id=?", $_GET['var1']);
	
	// data source with default values:
	$form->addDataSource(new HTML_QuickForm2_DataSource_Array(array(
		LabConfig::$cfg['catcher']=>$post_info['name'],
		'email'=>$post_info['email'],
		'msg'=>$post_info['msg'],
		'answer'=>$post_info['answer']
	)));
}

//если сообщение редактируется или вводится незарегистрированный пользователем
if (User::i()->id<0)
{
	$login=$form->addElement('text', LabConfig::$cfg['catcher'], null, array('label' => 'Имя:'));
	$catcher=$form->addElement('text', 'name', array('class' => 'catch'));
	$email=$form->addElement('text', 'email', null, array('label' => 'Email:'));
	$login	->addRule('required', 'Вы не ввели имя')
			->and_($login->createRule('callback', 'Такой пользователь уже зарегистрирован', 'isLoginNotExists'));
	$catcher->addRule('callback', '', 'isNotBot');
}
elseif($post_info)
{
	if (!empty($post_info['name']))
	{
		$login=$form->addElement('text', LabConfig::$cfg['catcher'], null, array('label' => 'Имя:'));
		$login	->addRule('required', 'Вы не ввели имя')
			->and_($login->createRule('callback', 'Такой пользователь уже зарегистрирован', 'isLoginNotExists'));
		$email=$form->addElement('text', 'email', null, array('label' => 'Email:'));	
	}
}

$msg = $form->addElement(
    'textarea', 'msg', array('cols' => 50, 'rows' => 7, 'id'=>'msg', 'class'=>'bbcode'),
    array('label' => 'Сообщение:')
);
$msg->addRule('required', 'Вы не ввели сообщение');


if ($post_info)
{
	//если сообщение редактируется - выводми форму ответа
	$answer = $form->addElement(
    'textarea', 'answer', array('cols' => 50, 'rows' => 7, 'id'=>'answer', 'class'=>'bbcode'),
    array('label' => 'Ответ:'));
}
$form->addElement('submit', null, array('value' => 'Отправить'));



if($form->validate())
{
	User::checkToken();
	$post=$form->getValue();
	$post['name']=$post[LabConfig::$cfg['catcher']];
	unset($post[LabConfig::$cfg['catcher']]);
	
	if ($mode=="edit")
	{
		Db::i()->query("UPDATE ?_guest SET ?a WHERE msg_id=?", array('msg'=>$post['msg'], 'answer'=>$post['answer'], 'name'=>$post['name'], 'email'=>$post['email']), $_GET['var1']);
	}
	elseif ($mode=="add")
	{
		if (User::i()->id>0)
		{
			Db::i()->query("INSERT INTO ?_guest (user_id, msg, `date`, ip) VALUES (?, ?, NOW(), INET_ATON('".$_SERVER['REMOTE_ADDR']."'))", User::i()->id, trim($post['msg']));
		}
		else
		{
			Db::i()->query("INSERT INTO ?_guest (name, email, msg, `date`, ip) VALUES (?, ?, ?, NOW(), INET_ATON('".$_SERVER['REMOTE_ADDR']."'))", trim($post['name']), trim($post['email']), trim($post['msg']));
		}
		if (LabConfig::$mcfg['guestbook_email_notify'] && LabConfig::$cfg['admin_mail'])
		{
			$mail=new Mailer(LabConfig::$cfg['admin_mail']);
			$mail->From = 'guestbook@'.preg_replace('/^www\./i', '', $_SERVER["SERVER_NAME"]);
			$mail->FromName = "Робот гостевой";
			$mail->AddReplyTo('guestbook@'.preg_replace('/^www\./i', '', $_SERVER["SERVER_NAME"]), "Робот гостевой");
			$mail->WordWrap = 80;                                 // set word wrap to 50 characters
			$mail->Subject = 'Новое сообщение в гостевой книге '.$_SERVER["SERVER_NAME"];
			if (!Tpl::i()->templateExists(LabCMS::i()->getModuleName()."/email_notify.tpl")) $default='../default/';
			$mail->Body    = Tpl::i()->fetch($default.LabCMS::i()->getModuleName()."/email_notify.tpl");
			$mail->Send();
		}
	}
	LabCMS::i()->reset_cache();
	refresh();

}

$renderer = HTML_QuickForm2_Renderer::factory('labsmarty');
Tpl::i()->assign('form', $form->render($renderer)->toArray());

function isLoginNotExists($login)
{
	return !User::i()->isLoginExists($login);
}

