<?
define("ADMIN_AUTHORIZATION",1);
include("../../../includes/common.php");


$table = "email_tpl";


$id = trim($_GET['id']=="")?trim($_POST['id']):trim($_GET['id']);
$format = trim($_GET['format']=="")?trim($_POST['format']):trim($_GET['format']);

if(!is_numeric($id)){
	$id = -1;
}
if($id>0){
	$row = mysql_fetch_object(mysql_query("select * from $table where id=$id"));
	$name = $row->name;
	$from = $row->from_who;
	$subject = $row->subject;
	$body = $row->body;
	$code = $row->code;
	$format = $row->format;
}	


/* generating fields */
$fields = Array(
	"ch_format" => Array('<input type="hidden">'),
	"name" => Array('<input type="text" size=60>','Название:','Введите название шаблона.'),
	"from" => Array('<input type="text" size=60>','Отправитель:','Введите адрес отправителя.'),
	"subject" => Array('<input type="text" size=60>','Тема:','Введите тему письма.'),
	"body" => Array($format=="html"?'<htmleditor width="100%" height="300">':"<textarea cols=80 rows=15>",'Message:'),
	"code" => Array('<input type="text" size=60>','Код:',"Введите корректный код шаблона (в верхнем регистре).","^[A-Za-z_]+$"),
	"format" => Array('<select  onChange="alert(\'Страница будет перезагружена.\');this.form.ch_format.value=1;this.form.submit();"><option value="text">Текст<option value="html">HTML</select>','Формат:',"Выберите формат письма.","[(text)|(html)]")
	); 	

function LocalCheck(){
	global $_POST;
	global $DB_LINK;
	global $fields;
	global $id;
	global $table;
	$error = "";

	foreach($fields as $key=>$value){
		if($value[3]!=""&&is_array($value)){
			if(!eregi($value[3],$_POST[$key])){
				$error .= $value[2]."<br>\n";
			}
		}
		elseif($value[2]!=""&&trim($_POST[$key])==""&&is_array($value)){
			$error .= $value[2]."<br>\n";
		}
	}		
	
	/* checking code */
	$row = mysql_fetch_object(mysql_query("select * from $table where code='".strtoupper($_POST['code'])."'".($id > 0?" and id<>$id":"")));
	
	if($row->id!=""){
		$error .="Код, который вы ввели уже существует.<br>\n";
	}
		
	return $error;
}

if(isset($_POST['subm'])){
	reset ($_POST);
	while (list($key, $value) = each ($_POST)) {
		if($key!="id"){
			$$key = $value;
		}	
	}

	$error = LocalCheck();

	if($error==""){
		
		$arr = Array(
			"name" => addslashes($name),
			"from_who" => addslashes($from),
			"subject" => addslashes($subject),
			"body" => addslashes($body),
			"code" => strtoupper($code),
			"format" => $format
		);
//		print_r($arr);
//		exit;
		if(($id<=0?AddRecord($table,$arr):UpdateRecord($table,$arr,$id)) ){
			$_SESSION['STATUS_MSG'] = "Шаблон успешно сохранен!"; 
			header("Location: ./mail.php?l_pager");
			exit;
		}
		else{
			$_SESSION['ERROR_MSG'] = "Ошибка работы с базой данных."; 
			header("Location: ./mail.php?l_pager");
			exit;
		}
	}
}	
elseif($_POST['ch_format']==1){
	reset ($_POST);
	while (list($key, $value) = each ($_POST)) {
		$$key = $value;
	}
}

$name = htmlspecialchars(stripslashes($name));
$from = htmlspecialchars(stripslashes($from));
$subject = htmlspecialchars(stripslashes($subject));
$body = stripslashes($body);
$code = htmlspecialchars(stripslashes($code));

/* smarty */
foreach($fields as $key=>$value){
	$smarty->assign($key,$$key);
}
$smarty->assign('id',$id);
/* smarty */

$page_title = $id<0?"Add email template":"Edit email template";

$smarty->assign('index_page','./mail.php?l_pager');
$smarty->assign('page_title',$page_title);
$smarty->assign('top_menu_tpl',"admin_settings_menu.tpl");

$smarty->assign('error',$error);
$smarty->assign('status',$status);

/* table template */
$smarty->assign('fields',$fields);
$smarty->assign('table_width',"95%");
$smarty->assign('main_tpl',"admin_add_form.tpl");
/* display content */
$smarty->display('admin_index.tpl');

?>