<?php

session_start();
header("Content-type: text/html; charset=windows-1251");
define("PATH", $_SERVER['DOCUMENT_ROOT']);
include(PATH."/core/func.php");
include(PATH."/core/db.php");
include(PATH."/core/set.php");
include(PATH."/core/define.php");
include(PATH."/core/defineset.php");
db_connect();

if(isset($_POST['game_id']))
{
	$res = db_query("SELECT `login`, `login2`, `summa`, `item`, `item2`, `dat`, `dat2`, `md5` FROM `sapper_games_active` WHERE `id` = '".$_POST["game_id"]."'");
	$row = db_assoc($res);
	if($row["dat2"] < time()-298)
	{
		$bank = round($row["summa"],2) * 1.9;
			echo json_encode(array("result"=>1));
			db_query("INSERT INTO `sapper_games_end` (`id`, `summa`, `item`, `item2`, `login`, `login2`, `winner`, `dat`, `dat2`, `md5`) VALUES ('".db_string($_POST["game_id"])."', '".$row["summa"]."', '".db_string($row["item"])."', '".db_string($row["item2"])."', '".db_string($row["login"])."', '".db_string($_SESSION["login"])."', '".db_string($row["login"])."', '".db_string($row["dat"])."', '".date("Y-m-d H:i:s")."', '".db_string($row["md5"])."')");
			db_query("DELETE FROM `sapper_games_active` WHERE `id` = ".$_POST["game_id"]);
			db_query("UPDATE `knb_users` SET `balance` = `balance` + ".round($bank,2)." WHERE `login` = '".db_string($row["login"])."'");	
			$REFrow = db_assoc(db_query("SELECT `ref`, `refback` FROM `".DBpref."users` WHERE `login`  = '".db_string($row["login"])."'"));
			if($REFrow['ref'] != NULL){
				$p_rate = db_assoc(db_query("SELECT `partner_rating` FROM `".DBpref."users` WHERE `login`  = '".$REFrow['ref']."'"));

				//сумма которую получит партнер с сыгравшего рефа
				$partner_sum = getPartnerPay($row["summa"], getPartnerProc($p_rate['partner_rating']), $REFrow['refback']); 

				//сумма которую получит реф с рефбека
				$ref_sum = getRefPay($row["summa"], getPartnerProc($p_rate['partner_rating']), $REFrow['refback']); 

				db_query("UPDATE `".DBpref."users` SET `balance` = `balance` + ".round($ref_sum,2)."  WHERE `login`  = '".db_string($row["login"])."'");
				db_query("UPDATE `".DBpref."users` SET `balance` = `balance` + ".round($partner_sum,2)."  WHERE `login`  = '".db_string($REFrow['ref'])."'");
				db_query("UPDATE `".DBpref."users` SET `partner_rating` = `partner_rating` + ".round($partner_sum,2)."  WHERE `login`  = '".db_string($REFrow['ref'])."'");
				$partner_bonus = $partner_sum*10001;
				db_query("UPDATE `".DBpref."users` SET `partner_bonus` = `partner_bonus` + ".($partner_bonus)."  WHERE `login`  = '".db_string($REFrow["ref"])."'");
			}
	}
	
}
	//echo json_encode(array("type_gamer"=>'bbbbb',"type_creator"=>'dddd'));
db_close();
?>