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

$table = "partner_payouts";

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

$CheckObj=new TCheckForm;

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

/*getting row*/
if($id>0){
	$row = mysql_fetch_object(mysql_query("select * from $table where id=$id"));
	$stat = $row->status;
}
else{
	$_SESSION["ERROR_MSG"] = "Указанной комиссии не существует";
	header("Location: ./comissions.php");
	exit;
}

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

$fields = Array_Merge($fields,Array(
	"stat" => Array('<select><option value="2">В процессе<option value="1">Активный<option value="0">Не активный</select>','Статус:','Укажите статус, пожалуйста.',"^0|1|2$")
));

if(isset($_POST['subm'])){
	reset ($_POST);
	while (list($key, $value) = each ($_POST)) {
		$$key = $value;
	}
	
	$query = "SELECT status FROM `partner_payouts` WHERE `id` = '$id'";
	$row=mysql_fetch_object(mysql_query($query));
	if ($row->status != 2)
	{
		$error .= "Нельзя менять статус у выплаты которая была совершена или отменена<br>";
	}

	elseif(!($_POST['stat']==0||$_POST['stat']==1||$_POST['stat']==2)){
		$error .="Укажите статус, пожалуйста.<br>\n";
	}
		
	if($error==""){
		
		if ($status == 1)
		{
			//TODO: transfer real money here
			
			$query = "SELECT * FROM partner_payouts WHERE id = $id";

			$row = mysql_fetch_object(mysql_query($query));
			if ($row->payout_method_id == 1) // WMZ
			{
				$wmz_arr = array
				(
					"payer_purse" => $WM['z_purse'],
					"payer_wm" => $WM['id'],
					"payee_purse" => $row->payee_purse,
					"type" => 1,
					"status" => 1
				);
				$ret_id = AddRecord("wm_orders", $wmz_arr, true);
				$sys_trans_no = WMTransfer($row->amount, $WM['z_purse'], $row->payee_purse, $ret_id, 
							"Партнерская выплата № $row->id");
				if ($sys_trans_no != -1)
				{
					//money transfer complete
					$arr = array("id" => $ret_id,
											 "sys_trans_no" => $sys_trans_no,
											 "status" => 0);
					UpdateRecord("wm_transfer", $arr, 0);
				}
				else
				{
					$arr = array("id" => $ret_id,
											 "status" => 2);
					UpdateRecord("wm_transfer", $arr, 0);
					$status = 2;
				}
			}
			else // E_Gold
			{
					/*payee_account -- $EGOLD['id']="1206811";
					-payment_metal_id -- 1
					-payment_batch_num -- из массива
					- feeweight -- PAYMENT_FEE_OUNCES
					*/
					$egold_arr = array(
								"payer_account" => $EGOLD['id'],
								"payment_metal_id" => 1,
								"payee_account" => $row->payee_purse,
								"type" => 1,
								"status" => 1
								);
					$ret_id = AddRecord("egold_orders", $egold_arr, true);
					$res_arr = EGoldTransfer($ret_id, $row->amount, $row->payee_purse, "Gold", "Партнерская выплата № $row->id");
				
					if (($res_arr != false) && (is_array($res_arr)))
					{
						$arr = array("id" => $ret_id,
											 "sys_trans_no" => $sys_trans_no,
											 "payment_batch_num"=>$res_arr['PAYMENT_BATCH_NUM'],
											 "feeweight" => $res_arr['PAYMENT_FEE_OUNCES'],
											 "status" => 0);
						UpdateRecord("egold_transfer", $arr, 0);
					}
					else
					{
						$arr = array("id" => $ret_id,
											 "status" => 2);
						UpdateRecord("egold_transfer", $arr, 0);
						$status = 2;
					}
			}
		}
		elseif ($status == 0)
		{
			//return money to partner
			$query = "SELECT partner_payouts.*, partners.currency_id as curr_id
			 FROM `partner_payouts` join partners on partner_payouts.partner_id=partners.id
			  WHERE partner_payouts.id='$id'";
			$row = mysql_fetch_object(mysql_query($query));
			$arr = array(
			"partner_id" => $row -> partner_id,
			"amount" => $row -> amount,
			"currency_id" => $row -> curr_id,
			"comments" => "Откат выплаты # $id",
			"allow_recursion" => 0
			);
			//print_r($arr);exit;
			MakePartnerTransaction($arr);
		}
		
		$arr = array("status" => $stat);
		if(UpdateRecord($table,$arr,$id)) 
		{
			$_SESSION['STATUS_MSG'] = "Информация успешно сохранена!";
			header("Location: ./payouts.php");
			exit;
		}
		else{
			$_SESSION['ERROR_MSG'] = "Ошибка при работе с базой данных.";
			header("Location: ./payouts.php");
			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','./index.php?l_pager');
$smarty->assign('page_title',$page_title);
$smarty->assign('top_menu_tpl',"admin_partners_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');

?>