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

$table = "ex_currencies";

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


//$res=pg_query($DB_LINK, );

/*getting row*/
if($id>0){
	$row = mysql_fetch_object(mysql_query("select $table.*, currencies.symbol as currency_symbol from $table inner join currencies on currencies.id = $table.currency_id where $table.id=$id"));
	$name = $row->name;
	$code = $row->code;
	$country = $row->country_id;
	$url = $row->url;
	$pos = $row->position;
	$amount = $row->amount + 0;
	$comission_fix = $row->comission_fix + 0;
	$comission_perc = $row->comission_perc*100 + 0;
	$comission_min = $row->comission_min + 0;
	$who_pay_comission = $row->who_pay_comission;
	$precision = $row->precision;
	$curr = $row->currency_id;
	$metal = $row->metal_id;
	$type = $row->type;
	$pincode_collection_id = $row->pincode_collection_id;
	$transfare_type = $row->transfare_type;
	$manual_properties = $row->manual_properties;
	$stat = $row->status;
	$currency_symbol = $row->currency_symbol;
	$ps_comission = $row->payment_system_comission_perc*100+0;
}
else{
	$id=-1;
}

	if(isset($_POST['subm'])){
		reset ($_POST);
		while (list($key, $value) = each ($_POST)) {
			$$key = $value;
		}
		$error = "";
		if(!eregi("^[А-Яа-яA-Za-z0-9() -]+$",$_POST['name'])){
			$error .= "Название валюты указано неверно.<br>\n";
		}
		if(!eregi("^[A-Za-z]+$",$_POST['code'])){
			$error .= "Код валюты указан неверно.<br>\n";
		}

		if(is_numeric($_POST['country'])&&$_POST['country'] > 0){
			$row = mysql_fetch_object(mysql_query("select * from countries where id=".$_POST['country']));
			if($row->id==""){
				$error .="Укажите страну валюты, пожалуйста.<br>\n";
			}
		}
		elseif($_POST['country']!=0){
			$error .="Укажите страну валюты, пожалуйста.<br>\n";
		}
		if(!eregi("^http://[^']+$",$_POST['url'])){
			$error .= "Сайт валюты указан неверно.<br>\n";
		}
		if($_FILES["logo"]['name']!=""&&$_FILES["logo"]['type']!="image/gif"){
			$error .= "Логотип должен быть GIF картинкой.<br>\n";
		}
		elseif(!isset($_POST['id'])&&$_FILES["logo"]['name']==""){
			$error .= "Загрузите логотип, пожалуйста.<br>\n";
		}

		if(is_numeric($_POST['curr'])&&$_POST['curr'] > 0 ){
			$row = mysql_fetch_object(mysql_query("select * from currencies where id=".$_POST['curr']));
			if($row->id==""){
				$error .="Укажите валюту, пожалуйста.<br>\n";
			}
		}
		else{
			if($_POST["type"] != "pincode")
			{
				$error .="Укажите валюту, пожалуйста.<br>\n";
			}
		}

		if(is_numeric($_POST['metal'])&&$_POST['metal'] > 0 ){
			$row = mysql_fetch_object(mysql_query("select * from metals where id=".$_POST['metal']));
			if($row->id==""){
				$error .="Укажите металл, пожалуйста.<br>\n";
			}
		}
		if(!is_numeric($_POST['pos'])&&$_POST['action'] =="edit" ){
			$error .="Укажите место(позицию), пожалуйста.<br>\n";
		}

		if(!(is_numeric($_POST['amount'])&&(double)$_POST['amount'] >= 0) && $_POST["type"]!="pincode"){
			$error .="Укажите остаток на счете, пожалуйста.<br>\n";
		}
		if(!(is_numeric($_POST['ps_comission'])&&$_POST['ps_comission'] >= 0)){
			$error .="Укажите комиссию платежной системы, пожалуйста.<br>\n";
		}

		if(!($_POST['who_pay_comission']==0||$_POST['who_pay_comission']==1)){
			$error .="Укажите, кто платит за перевод, пожалуйста.<br>\n";
		}

		if(!(is_numeric($_POST['precision'])&&$_POST['precision']>=0&&$_POST['precision']<=6)){
			$error .="Укажите количество знаков за запятой, пожалуйста.<br>\n";
		}

		if(!($_POST['type']=="ordinary"||$_POST['type']=="pincode")){
			$error .="Укажите тип валюты, пожалуйста.<br>\n";
		}

		if(($_POST['type']=="pincode"&&!is_numeric($_POST['pincode_collection_id']))){
			$error .="Укажите колекцию ПИН-кодов, пожалуйста.<br>\n";
		}

		if(!($_POST['transfare_type']=="auto"||$_POST['transfare_type']=="manual"||$_POST['transfare_type']=="pincode")){
			$error .="Укажите способ передачи, пожалуйста.<br>\n";
		}

		if(($_POST['transfare_type']=="manual"&&$_POST['manual_properties']=="")){
			$error .="Укажите реквизиты для ручного перевода, пожалуйста.<br>\n";
		}

		if(!($_POST['status']==0||$_POST['status']==1)){
			$error .="Укажите статус, пожалуйста.<br>\n";
		}

		if($type == "pincode")
		{
			$row = mysql_fetch_assoc(mysql_query("select * from pincode_collections where id=$pincode_collection_id"));
			$sell_price = $row["sell_price"];
			$pincurr = $row["currency_id"];
			
			$row = mysql_fetch_assoc(mysql_query("select count(*) as pincount from pincodes where collection_id=$pincode_collection_id and status='valid'"));
			$pincount = $row["pincount"];
		}
		
		if($error=="")
		{
		
			$arr = Array(
			"name" => addslashes($name),
			"code" => addslashes(strtoupper($code)),
			"country_id" => $country,
			"currency_id" => $type == "pincode" ? $pincurr :$curr,
			"metal_id" => $metal,
			"url" => addslashes($url),
			"position" => $pos,
			"amount" => $type == "pincode" ? $sell_price * $pincount : $amount,
			"payment_system_comission_perc" => $ps_comission/100+0,
			"who_pay_comission" => $who_pay_comission,
			"precision" => $precision,
			"type" => $type,
			"pincode_collection_id" => intval($type == "pincode" ? $pincode_collection_id : ""),
			"transfare_type" => $transfare_type,
			"manual_properties" => $transfare_type == "manual" ? $manual_properties : "",
			"status" => $stat
			);
			
			if (0 >= $id)
			{
				$pos = mysql_fetch_object(mysql_query("select 1 + max(position) as pos from ex_currencies"));
				$arr["position"] = $pos->pos;
			}
			else
			{
				$tmp_row = mysql_fetch_object(mysql_query("select * from ex_currencies where id=$id"));
				$cur_pos = $tmp_row->position;
			}

			if ($id > 0)
			{
				$arr ["regdate"] = time();
			}
			$id_d = $id;
			if(($id<0?AddRecord($table,$arr):UpdateRecord($table,$arr,$id)) ){
				$row = mysql_fetch_row(mysql_query("select max(id) from ex_currencies"));
				$id = $row[0];
				/* EXCHANGES */
				$tmp_res = mysql_query("select * from ex_currencies where id<>".$row[0]);

				while($tmp_row = mysql_fetch_object($tmp_res))
				{
					if (0 >= mysql_num_rows(mysql_query("select * from ex_exchanges where
									ex_currency1_id = $id and ex_currency2_id=$tmp_row->id")))
					{
						$query = "INSERT INTO `ex_exchanges` (`ex_currency1_id` , `ex_currency2_id` , `sys_comission_perc` , `sys_comission_fix` , `sys_comission_min` , `min_amount` , `max_amount` , `status` ) VALUES ('$id', '$tmp_row->id', '$SYS_COMISSION_PERC_DEF', '$SYS_COMISSION_FIX_DEF', '$SYS_COMISSION_MIN_DEF', '$MIN_AMOUNT_DEF', '$MAX_AMOUNT_DEF','1');";
						mysql_query($query);
					}
					if (0 >= mysql_num_rows(mysql_query("select * from ex_exchanges where
									ex_currency2_id = $id and ex_currency1_id=$tmp_row->id")))
					{
						$query = "INSERT INTO `ex_exchanges` (`ex_currency1_id` , `ex_currency2_id` , `sys_comission_perc` , `sys_comission_fix` , `sys_comission_min` , `min_amount` , `max_amount` , `status` ) VALUES ('$tmp_row->id','$id','$SYS_COMISSION_PERC_DEF', '$SYS_COMISSION_FIX_DEF', '$SYS_COMISSION_MIN_DEF', '$MIN_AMOUNT_DEF', '$MAX_AMOUNT_DEF','1');";
						@mysql_query($query);
					}
				}

				if($_FILES["logo"]['name']!=""){
					@unlink($_SERVER["DOCUMENT_ROOT"].$CURR_IMG_PATH."/".$id_d.".gif");
					@move_uploaded_file($_FILES["logo"]['tmp_name'], $_SERVER["DOCUMENT_ROOT"].$CURR_IMG_PATH."/".$id_d.".gif");
					@chmod($_SERVER["DOCUMENT_ROOT"].$CURR_IMG_PATH."/".$id_d.".gif", 777);
				}

				if (0 < $id_d)
				{
					/* position */
					$new_pos = $pos;
					
					
					if ($new_pos<>$cur_pos)
					{
						if ($cur_pos>0) 
						{
							$q = "update ex_currencies set 
							position=position-1 where position>".($cur_pos+0)." and id<>$id_d";
							//echo $q;
							mysql_query($q);
							
							
						}
						$q = "update ex_currencies set 
						position=position+1 where position>=".($new_pos+0)." and id<>$id_d";
						//echo $q;
						mysql_query($q);
					} 
					
					//exit;
				}

				$_SESSION['STATUS_MSG'] = "Информация успешно сохранена!";
				header("Location: ./index.php");
				exit;
			}
			else{
				$_SESSION['ERROR_MSG'] = "Ошибка при работе с базой данных.".mysql_error();
				header("Location: ./index.php");
				exit;
			}
		}
	}

/* smarty */

/*
logo
*/
$logo_img_src = "";
if(file_exists($_SERVER["DOCUMENT_ROOT"].$CURR_IMG_PATH."/".$id.".gif")){
	$logo_img_src = $SITE_URL.$CURR_IMG_PATH."/".$id.".gif";
}
$smarty->assign('logo_img_src',$logo_img_src);


/*
html options section
*/
$res = mysql_query("select * from countries order by name_rus");

$country_ids[0]=0;
$country_names[0]="International";
$country_ids[1]=-1;
$country_names[1]="-------------------";
$i=2;
while($row=mysql_fetch_object($res)){
	$country_ids[$i]=$row->id;
	$country_names[$i]=stripslashes($row->name_rus);	
	$i++;
}
$smarty->assign('country_ids',$country_ids);
$smarty->assign('country_names',$country_names);

$curr_ids[0]=0;
$curr_names[0]="Выберите";
$i=1;
$res = mysql_query("select * from currencies");
while($row=mysql_fetch_object($res)){
	$curr_ids[$i]=$row->id;
	$curr_names[$i]=stripslashes($row->name);	
	$i++;
}
$smarty->assign('curr_ids',$curr_ids);
$smarty->assign('curr_names',$curr_names);

$metal_ids[0]=0;
$metal_names[0]="Нет привязки";
$i=1;
$res = mysql_query("select * from metals");
while($row=mysql_fetch_object($res)){
	$metal_ids[$i]=$row->id;
	$metal_names[$i]=stripslashes($row->name);	
	$i++;
}
$smarty->assign('metal_ids',$metal_ids);
$smarty->assign('metal_names',$metal_names);

for($i=0;$i<=6;$i++){
	$precision_ids[$i]=$i;
	$precision_names[$i]=$i;	
}
$smarty->assign('precision_ids',$precision_ids);
$smarty->assign('precision_names',$precision_names);

$row = mysql_fetch_row(mysql_query("select count(*) from ex_currencies"));
for($i=1;$i<=$row[0];$i++){
	$pos_ids[$i-1]=$i;
	$pos_names[$i-1]=$i;	
}
$smarty->assign('pos_ids',$pos_ids);
$smarty->assign('pos_names',$pos_names);

$collect_ids[0]=0;
$collect_names[0]="Нет привязки к коллекции";
$i=1;
$res = mysql_query("select * from pincode_collections");
while($row=mysql_fetch_object($res)){
	$collect_ids[$i]=$row->id;
	$collect_names[$i]=stripslashes($row->name);	
	$i++;
}
$smarty->assign('collect_ids',$collect_ids);
$smarty->assign('collect_names',$collect_names);

/*
html options section
*/


$smarty->assign('id',$id);
$smarty->assign('currency_symbol',$currency_symbol);
$smarty->assign('ps_comission',$ps_comission);
$smarty->assign('name',$name);
$smarty->assign('code',$code);
$smarty->assign('country',$country);
$smarty->assign('url',$url);
$smarty->assign('logo',$logo);
$smarty->assign('curr',$curr);
$smarty->assign('metal',$metal);
$smarty->assign('amount',$amount);
$smarty->assign('comission_min',$comission_min);
$smarty->assign('precision',$precision);
$smarty->assign('who_pay_comission',$who_pay_comission);
$smarty->assign('type',$type);
$smarty->assign('pincode_collection_id',$pincode_collection_id);
$smarty->assign('transfare_type',$transfare_type);
$smarty->assign('manual_properties',$manual_properties);
$smarty->assign('stat',$stat);
$smarty->assign('pos',$pos);

$page_title = $id>0?"Редактирование электронной валюты":"Добавление электронной валюты";
$smarty->assign('index_page','./index.php?l_pager');
$smarty->assign('page_title',$page_title);
$smarty->assign('top_menu_tpl',"admin_excurr_menu.tpl");

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

/* table template */
$smarty->assign('main_tpl',"admin_excurr_add.tpl");
/* display content */
$smarty->display('admin_index.tpl');

?>