<h1 style="text-align: left;">
<img  src="style/img/refbir.png" align="center">Биржа рефералов</h1>
<?php
if($_GET["t"] == "by"){
	db_connect();

		
	$res = db_query("SELECT `price`, `seller`, `login` FROM `".DBpref."refmarket` WHERE `login` = '".db_string($_POST["login"])."' AND `seller` != '".db_string($_SESSION["login"])."' AND `login` != '".db_string($_SESSION["login"])."'");
	$row = db_assoc($res);
	$res2 = db_query("SELECT `login`, `balance`, `ref`, `ref2`, `referals`, `referals2` FROM `".DBpref."users` WHERE `login` = '".db_string($_SESSION["login"])."'");
	$row2 = db_assoc($res2);
	$res3 = db_query("SELECT `login`, `balance`, `ref`, `ref2`, `referals`, `referals2` FROM `".DBpref."users` WHERE `login` = '".db_string($row["seller"])."'");
	$row3 = db_assoc($res3);
	$res4 = db_query("SELECT `login`, `balance`, `ref`, `ref2`, `referals`, `referals2` FROM `".DBpref."users` WHERE `login` = '".db_string($row["login"])."'");
	$row4 = db_assoc($res4);
	
	$err = NULL;
	if(db_rows($res) == 0)
		$err .= "<li>Пользователь не найден</li>";
	if(round($row["price"],2) > round($row2["balance"],2))
		$err .= "<li>На балансе недостаточно средств</li>";
		
	if($err == NULL){
	    
		
	
	    $row2['balance'] = $row2['balance'] - round($row["price"],2);
		$row3['balance'] = $row3['balance'] + round($row["price"]*(1 - refmarketCom),2);
		db_query("UPDATE `".DBpref."users` SET `balance` = '".$row2['balance']."' WHERE `login` = '".db_string($_SESSION["login"])."'") or die(mysql_error());
		//история
			db_query("INSERT INTO `knb_history` (`user`, `date`, `amount`, `method`, `status`, `tipo`) VALUES('".db_string($_SESSION["login"])."', '".$row["dat"]."', '".(round($row["price"],2))."', 'Покупка реферала ".db_string($_POST["login"])."', 'Списано', 'rashod')") or die(db_error());
		
		db_query("UPDATE `".DBpref."users` SET `balance` = '".$row3['balance']."' WHERE `login` = '".db_string($row["seller"])."'") or die(mysql_error());
		//история
			db_query("INSERT INTO `knb_history` (`user`, `date`, `amount`, `method`, `status`, `tipo`) VALUES('".db_string($row["seller"])."', '".$row["dat"]."', '".(round($row["price"]*(1 - refmarketCom),2))."', 'Продажа реферала ".db_string($_POST["login"])."', 'Зачислено', 'popoln')") or die(db_error());
		
		$row2['referals2'] = $row2['referals2'] + $row4['referals'];
		$row2['referals'] = $row2['referals'] + 1;
		db_query("UPDATE `".DBpref."users` SET `referals2`='".$row2['referals2']."', `referals`='".$row2['referals']."' WHERE `login`='".db_string($row2["login"])."'") or die(mysql_error());

		$row3['referals2'] = $row3['referals2'] - $row4['referals'];
		$row3['referals'] = $row3['referals'] - 1;
		
		db_query("UPDATE `".DBpref."users` SET `referals2`='".$row3['referals2']."', `referals`='".$row3['referals']."' WHERE `login`='".db_string($row3["login"])."'") or die(mysql_error());
		

		if($row3["ref2"] == $row2["ref2"]){

		} else {
		   if(!empty($row3["ref2"])){

		   $res5 = db_query("SELECT `referals2` FROM `".DBpref."users` WHERE `login` = '".db_string($row3["ref"])."'") or die(mysql_error());
	       $row5 = db_assoc($res5);
		   $row5['referals2'] = $row5['referals2'] - 1;
		   db_query("UPDATE `".DBpref."users` SET `referals2`='".$row5['referals2']."' WHERE `login`='".db_string($row3["ref"])."'") or die(mysql_error());
		
		   }
		   if(!empty($row2["ref2"])){

		   $res6 = db_query("SELECT `referals2` FROM `".DBpref."users` WHERE `login` = '".db_string($row2["ref"])."'") or die(mysql_error());
	       $row6 = db_assoc($res6);
		   $row6['referals2'] = $row6['referals2'] + 1;
		   db_query("UPDATE `".DBpref."users` SET `referals2`='".$row6['referals2']."' WHERE `login`='".db_string($row2["ref"])."'") or die(mysql_error());
		   }

		   
		}
		db_query("UPDATE `".DBpref."users` SET `refmarket` = 0, `ref`='".db_string($row2['login'])."', `ref2` = '".db_string($row2['ref'])."' WHERE `login`='".db_string($_POST["login"])."'");
		db_query("UPDATE `".DBpref."users` SET `ref2`='".db_string($row2['login'])."' WHERE `ref2`='".db_string($row3["login"])."' AND `ref`='".db_string($_POST["login"])."'"); 
		
		db_query("DELETE FROM `".DBpref."refmarket` WHERE `login` = '".db_string($_POST["login"])."'");
		
		echo "<ul><li>Реферал куплен</li></ul>";
	}else{
		echo "<ul>".$err."</ul>";
	}
	
	
	
	
	db_close();
}

db_connect();
$res = db_query("SELECT `t1`.`login`, `t1`.`price`, `t2`.`game_win`, `t2`.`game_loss`, `t2`.`game_draw`, `t2`.`regdat`, `t2`.`logdat` FROM `".DBpref."refmarket` `t1` INNER JOIN `".DBpref."users` `t2` ON `t1`.`login` = `t2`.`login` WHERE `t1`.`login` != '".db_string($_SESSION["login"])."' AND `t1`.`seller` != '".db_string($_SESSION["login"])."'");
db_close();

echo '
<table class="table1">
  <tr class="title">
    <td>Логин</td>
    <td>Зарегистрирован</td>
	<td>Последняя активность</td>
    <td>Побед</td>
    <td>Поражений</td>
    <td>Ничьих</td>
	<td>Цена</td>
	<td>Купить</td>
  </tr>
';
if(db_rows($res) == 0)
	echo "<ul><li>На бирже нет рефералов</li></ul>";

while($row = db_assoc($res)){
echo '
 <tr>
    <td><a target="_blank" href="/?p=wprofile&login='.htmlspecialchars($row["login"]).'">'.htmlspecialchars($row["login"]).'</a></td>
    <td>'.substr($row["regdat"],0,10).'</td>
	<td>'.substr($row["logdat"],0,10).'</td>
    <td>'.$row["game_win"].'</td>
    <td>'.$row["game_loss"].'</td>
    <td>'.$row["game_draw"].'</td>
	<td>'.round($row["price"],2).' р.</td>
    <td><form action="/?p=refmarket&t=by" method="post"><input name="login" type="hidden" value="'.htmlspecialchars($row["login"]).'" /> <input name="submitt" type="submit" value="Купить" /></form></td>
  </tr>
';
}
echo '</table>';
?>
