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

$CheckObj=new TCheckForm;

/* generating fields */
$fields = Array(
	"amount"=>Array('<input type="text" maxlength="100" size=5> '.$PARTNER_DATA["currency_symbol"],'Сумма:','Укажите сумму, пожалуйста.','^[+]?[0-9]+\.?[0-9]+$'),
	"props" =>Array('<textarea cols=60 rows=5>','Детали перевода:','Введите пожалуйста детали перевода'),
	"wm" => Array('
	<input '.(($_POST['n1']==1)?"checked=\"checked\"":"").'name="n1" id="wm" value="1" type="radio">
	<label for="wm" value=""><b>WebMoney USD</b></label>'),
	"wm_purse"=>Array('<input type="text" maxlength="100" size=25> ','# WMZ Кошелька:'),
	"egold" => Array('
	<input '.(($_POST['n1']==2)?"checked=\"checked\"":"").'name="n1" id="egold" value="2" type="radio">
	<label for="egold" value=""><b>E-gold</b></label>'),
	"egold_purse"=>Array('<input type="text" maxlength="100" size=25> ','# E-gold счета:'),
	);

if(isset($_POST['subm'])){
	reset ($_POST);
	while (list($key, $value) = each ($_POST)) {
		if($key!="id"){
			$$key = $value;
		}	
	}
	
	function LocalCheck()
	{
		global $SETTINGS;
		global $PARTNER_ID;
		$error = "";
		
		$query = "SELECT `amount` FROM `partners` WHERE id = $PARTNER_ID";
		$row =  mysql_fetch_object(mysql_query($query));
		$partner_amount = $row->amount;
		
		if ($_POST['amount'] < 0)
		{
			$error .= "Сумма вывода не может быть отрицательной<br>";
		}
		elseif (($_POST['amount']) < ($SETTINGS['min_partner_payout']))
		{	
			$error .= "Минимальный размер выплаты составляет ".$SETTINGS['min_partner_payout']."$ <br>";
		}
		elseif ($_POST['amount'] > $partner_amount)
		{
			$error .= "На вашем счету не достаточно денег<br>";
		}
		
		if ($_POST['n1'] == 1)
		{
			if (!eregi('^(z|Z)[0-9]{12}$', $_POST['wm_purse']))
			{
				$error .= "Введите, пожалуйста корректный # WMZ кошелька<br>";
			}
		}
		elseif ($_POST['n1'] == 2)
		{
			if (!eregi('^[0-9]+$', $_POST['egold_purse']))
			{
				$error .= "Введите, пожалуйста корректный # cчета E-gold<br>";
			}
		}
		else
		{
			$error .= "Выберите, пожалуйста способ оплаты<br>";
		}

		return $error;
	}


	$error = LocalCheck();
	if($error==""){
		$arr = Array(
			"partner_id" =>$PARTNER_ID,
			"amount"=>floatval($amount),
			"regdate"=>time(),
			"currency_id"=>$PARTNER_DATA["currency_id"],
			"properties"=>addslashes($props),
			"payout_method_id"=>$n1,
			"status"=>2,
			"payee_purse"=>($n1==1)?$wm_purse:$egold_purse
		);
		
		if(($p_id=AddRecord("partner_payouts",$arr,true))){
			
			$p_params = Array(
				"partner_id" => $PARTNER_ID,
				"amount" => 0-$amount,
				"currency_id" => $PARTNER_DATA["currency_id"],
				"comments" => "Выплата # $p_id"
			);
			
			MakePartnerTransaction($p_params);
			
			$query = "select sum(partner_amount) as partn_sum from orders where
								partner_id=$PARTNER_ID and status=0";			
						
			$result = mysql_query($query);
			$row = mysql_fetch_object($result);
			$partn_sum = $row -> partn_sum;
			
			$query = "select * from partners where id = $PARTNER_ID";
			$result = mysql_query($query);
			$row = mysql_fetch_object($result);
			$ref_partner_id = $row -> ref_partner_id;
			
			if (($ref_partner_id > 0) && (is_numeric($ref_partner_id)))
			{
						
				$arr = array(
				"partner_id" => $ref_partner_id,
				"amount" => $partn_sum * $SETTINGS['subpartner_payout_perc'],
				"currency_id" => $PARTNER_DATA["currency_id"],
				"comments" => "Выплата c субпарнтера # $PARTNER_ID",
				"ref_partner_id" => $PARTNER_ID,
				"allow_recursion" => 1
				);
				//echo $row -> partn_sum ."<br>";
				//print_r($arr);
				//exit;
				MakePartnerTransaction($arr);
			}
					
			$_SESSION['STATUS_MSG'] = "Информация успешно сохранена!";
			header("Location: ./index.php?l_pager");
			exit;
		}
		else{
			$_SESSION['ERROR_MSG'] = "Системная ошибка.";
			header("Location: ./index.php?l_pager");
			exit;
		}
	}
}
else{
	$amount = $PARTNER_DATA["amount"];
}
$amount = $PARTNER_DATA["amount"];


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

if (!$is_default) {
    unset($is_default);
}

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

$page_title = "Запрос вывода денег";

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

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

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

?>