<?php
session_start();
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["id"]))
{

	$res = db_query("SELECT `login`, `summa`, `item`, `dat`, `md5` FROM `sapper_games` WHERE `id` = '".db_string($_POST["id"])."'");
	if(db_rows($res) != 0)
	{
		$row = db_assoc($res);
		$balrow = db_query("SELECT `balance` FROM `knb_users` WHERE `login` = '".db_string($_SESSION["login"])."'");
		$bal = db_assoc($balrow);
		if($bal['balance'] < $row['summa'])
		{
			$hide = "<script type='text/javascript'>
			$('#sapper-".intval($_POST["id"])."').hide();
			</script>";

			echo "<script type='text/javascript'>$('.sapper-".intval($_POST["id"])."').html('Недостаточно средств!')</script>";
		}
		else
		{
			$bank = round($row["summa"],2) * 1.9;
			db_query("UPDATE `knb_users` SET `balance` = `balance` - ".round($row["summa"],2)." WHERE `login` = '".db_string($_SESSION["login"])."'");
			db_query("DELETE FROM `sapper_games` WHERE `id` = ".$_POST["id"]);
			db_query("INSERT INTO `sapper_games_active` (`id`, `summa`, `item`, `login`, `login2`, `dat`, `dat2`, `md5`) VALUES ('".db_string($_POST["id"])."', '".$row["summa"]."', '".db_string($row["item"])."', '".db_string($row["login"])."', '".db_string($_SESSION["login"])."', '".db_string($row["dat"])."', '".time()."', '".db_string($row["md5"])."')");
			echo "<script type='text/javascript'>game_open_dialog_g(".$_POST["id"].", ".round($row["summa"],2).", ".$bank.", '".$row["login"]."'); $('#game_last_do').show();
                        $('.smr_bot_alert').show(); smr_set_timeout_sec(300, ".$_POST["id"].");</script>";
		}
	} else {
		$res = db_query("SELECT * FROM `sapper_games_active` WHERE `id` = '".db_string($_POST["id"])."'");
		if(db_rows($res) != 0)
		{
			echo "<script type='text/javascript'>$('.sapper-".intval($_POST["id"])."').html('Игра уже начата!')</script>";
		} else {
			$res = db_query("SELECT * FROM `sapper_games_end` WHERE `id` = '".db_string($_POST["id"])."'");
			if(db_rows($res) != 0)
			{
				$l = db_assoc($res);
				echo "<script type='text/javascript'>$('.sapper-".intval($_POST["id"])."').html('Игра уже завершена!<br>Победитель: ".$l['winner']."')</script>";
			}
			else echo "<script type='text/javascript'>$('.sapper-".intval($_POST["id"])."').html('Игра отменена!')</script>";

		}
	}
}

db_close();