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

$table = "pincodes";

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

$CheckObj=new TCheckForm;

/*getting row*/
if($id>0){
	$row = mysql_fetch_object(mysql_query("select * from $table where id=$id"));
	$code=$row->code;
	$collection_id=$row->collection_id;
	$stat=$row->status;
}
else{
	$id=-1;
}

/* generating fields */
$fields=Array();
if ($id>0) {
	$fields[id]=Array($id,'ID:');
}

$collect_opts = "";
$res = mysql_query("select * from pincode_collections order by name");
while($row=mysql_fetch_object($res)){
	$collect_opts .= "<option value=\"$row->id\" ".($ex_id==$row->id?"selected":"").">$row->name</option>\n";
}

$fields = Array_Merge($fields,Array(
"code" => Array('<input type="text" size=60 class="text_input">','Код:'),
"collection_id" => Array("<select>
<option value=\"-1\">-выберите-</option>
$collect_opts
</select>",'Коллекция:'),
"stat"=>Array('<select><option value="valid">Действительный<option value="used">Использованный</select>','Статус:')
));


if(isset($_POST['subm'])){
	reset ($_POST);
	while (list($key, $value) = each ($_POST)) {
		$$key = $value;
	}
	$error = $CheckObj->LocalCheck();

	if($id<0&&is_string($_POST['code'])&&(integer)$_POST['collection_id']>0&&is_string($_POST['collection_id']))
	{
		$row = mysql_fetch_object(mysql_query("select * from $table where code='".$_POST['code']."' AND collection_id=".$_POST['collection_id'].";"));
		echo mysql_error();

		if($row->id!=""){
			$error .="ПИН-код с таким кодом в этой коллекции уже существует.<br>\n";
		}
		else{
			$row = mysql_fetch_object(mysql_query("select * from pincode_collections where id=".$_POST['collection_id']));
			if($row->id==""){
				$error .="Выберите правильно коллекцию.<br>\n";
			}

			if(!in_array($_POST['stat'], array("valid","used")))
			{
				$error .="Выберите правильно статус.<br>\n";
			}
		}
	}

	if(!(is_string($_POST['code']) && !empty($_POST['code']))){
		$error .= "Укажите код.<br>\n";
	}

	if(!((string)((integer)$_POST['collection_id']) == $_POST['collection_id'] && (integer)$_POST['collection_id'] > 0)){
		$error .= "Выберите правильно коллекцию.<br>\n";
	}

	if(!in_array($_POST['stat'], array("valid","used")))
	{
		$error .="Выберите правильно статус.<br>\n";
	}

	if($error==""){

		$arr = Array(
		"code" =>$code,
		"collection_id" =>$collection_id,
		"status" =>$stat
		);

		if(($id<0?AddRecord($table,$arr,TRUE):UpdateRecord($table,$arr,$id)) ){
			$_SESSION['STATUS_MSG'] = "Информация успешно сохранена!";
			
			$collection = @mysql_fetch_object(@mysql_query("select * from pincode_collections where id=$collection_id"));
			$res = @mysql_fetch_object(@mysql_query("select count(*) as pincount from pincodes where status='valid' and collection_id=$collection_id"));
			$pincount = (integer)$res->pincount;
			
			@mysql_query("update ex_currencies set amount='".$pincount*$collection->sell_price."' where pincode_collection_id=$collection_id");
		}
		else{
			$_SESSION['ERROR_MSG'] = "Ошибка при работе с базой данных.";
		}
		
		header("Location: ./listcodes.php".(isset($_GET["collection_id"])? "?collection_id=".$collection_id ."&" : "?").'l_pager');
		exit;
	}
}


$pass="";
$c_pass="";
foreach($fields as $key=>$value){
	$$key=htmlspecialchars(stripslashes($$key));
	$smarty->assign($key,$$key);
}

/* smarty */
$smarty->assign('id',$id);

$page_title = $id>0?"Редактирование ПИН-кода":"Добавление нового ПИН-кода";
$smarty->assign('index_page','./listcodes.php'.(isset($_GET["collection_id"])? "?collection_id=".$collection_id ."&" : "?").'l_pager');
$smarty->assign('page_title',$page_title);
$smarty->assign('top_menu_tpl',"admin_pincollections_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');