<?
require_once ("include/bittorrent.php");
dbconn ( false );
validcan ( false, 'can_playgames' );
global $pic_base_url, $CURGROUP;
function get_user_name($userid) {
	$userid = intval ( $userid );
	$r = mysql_query ( "select username from users where id=$userid" );
	$a = mysql_fetch_array ( $r );
	return "$a[username]";
}
/*function playerexists($userid){
$r = mysql_query("select count(*) from casino where userid=$userid");
$a = mysql_fetch_array($r);
if ($a[0] > 0) return true;
else return false;
}*/
$mb = 1024 * 1024 * 100; //bet size
if ($_POST ["game"]) {
	$cardcountres = mysql_query ( "select count(id) from cards" ) or sqlerr ( __FILE__, __LINE__ );
	$cardcountarr = mysql_fetch_array ( $cardcountres );
	$cardcount = $cardcountarr [0];
	if ($_POST ["game"] == 'start') {
		
		if ($CURUSER ["uploaded"] < $mb)
			stderr ( "Sorry " . $CURUSER ["username"], "You didn't uploaded " . mksize ( $mb ) );
		$required_ratio = 0.3;
		if ($CURUSER ["downloaded"] > 0)
			$ratio = number_format ( $CURUSER ["uploaded"] / $CURUSER ["downloaded"], 2 );
		else if ($CURUSER ["uploaded"] > 0)
			$ratio = 999;
		else
			$ratio = 0;
		if ($ratio < $required_ratio)
			stderr ( "Извините " . $CURUSER ["username"], "Ваш рейтинг меньше минимальной ставки " . $required_ratio );
		$res = mysql_query ( "select count(*) from blackjack where userid=$CURUSER[id] and status='waiting'" );
		$arr = mysql_fetch_array ( $res );
		if ($arr [0] > 0) {
			stderr ( "Вы должны дождаться, пока кто-нибудь не сыграет с Вами..", "Для начала новой игры, Вам необходимо закончить предыдущую. Подождите немного, с Вами обязательно сыграют..." );
		} else {
			$res = mysql_query ( "select count(*) from blackjack where userid=$CURUSER[id] and status='playing'" );
			$arr = mysql_fetch_array ( $res );
			if ($arr [0] > 0)
				stderr ( "Ошибка..", "<p>Вы еще не завершили предыдущую игру&nbsp;<form method=post name=form action=$phpself><input type=hidden name=game value=cont><input type=submit value='Вернуться к ней?'></p></form>" );
		}
		$cardid = rand ( 1, $cardcount );
		$cardres = mysql_query ( "select * from cards where id=$cardid" ) or sqlerr ( __FILE__, __LINE__ );
		$cardarr = mysql_fetch_array ( $cardres );
		mysql_query ( "insert into blackjack (userid, points, cards, started) values($CURUSER[id], $cardarr[points], $cardid, 1)" ) or sqlerr ( __FILE__, __LINE__ );
		stdhead ();
		begin_frame ( "21 очко" );
		print ( "<center><h1>Привет, <b><a href=userdetails.php?id=$CURUSER[id]>$CURUSER[username]</a></b>. Готов просадить свои mb?!</h1>\n" );
		print ( "<table cellspacing=0 cellpadding=3 width=600><tr><td style='border: none;'  align=center><img src=" . $pic_base_url . "blackjack.jpg></td></tr>\n" );
		print ( "<tr><td style='border: none;'  colspan=2 cellspacing=0 cellpadding=3>" );
		print ( "<form name=blackjack method=post action=$phpself>" );
		print ( "<table class=message width=100% cellspacing=0 cellpadding=5 bgcolor=white>\n" );
		print ( "<tr><td style='border: none;'  align=center><img src=" . $pic_base_url . "cards/" . $cardarr ["pic"] . " border=0></td></tr>" );
		print ( "<tr><td style='border: none;'  align=center><b>Очки = $cardarr[points]</b></td></tr>" );
		print ( "<tr><td style='border: none;'  align=center><input type=hidden name=game value=cont><input type=submit class=button value='Еще давай'></td></tr>" );
		print ( "</table><br>" );
		print ( "</form>" );
		print ( "</td></tr></table><br></center>" );
		end_frame ();
		stdfoot ();
	} elseif ($_POST ["game"] == 'cont') {
		
		$playeres = mysql_query ( "select * from blackjack where userid=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
		$playerarr = mysql_fetch_array ( $playeres );
		$showcards = "";
		$cards = $playerarr ["cards"];
		$usedcards = explode ( " ", $cards );
		$arr = array ();
		foreach ( $usedcards as $array_list )
			$arr [] = $array_list;
		foreach ( $arr as $card_id ) {
			$used_card = mysql_query ( "SELECT * FROM cards WHERE id='$card_id'" ) or sqlerr ( __FILE__, __LINE__ );
			$used_cards = mysql_fetch_array ( $used_card );
			$showcards .= "<img src=" . $pic_base_url . "cards/" . $used_cards ["pic"] . " border=0> ";
			$i ++;
		}
		$cardid = rand ( 1, $cardcount );
		while ( in_array ( $cardid, $arr ) ) {
			$cardid = rand ( 1, $cardcount );
		}
		$cardres = mysql_query ( "select * from cards where id=$cardid" ) or sqlerr ( __FILE__, __LINE__ );
		$cardarr = mysql_fetch_array ( $cardres );
		$showcards .= "<img src=" . $pic_base_url . "cards/" . $cardarr ["pic"] . " border=0> ";
		$points = $playerarr ["points"] + $cardarr ["points"];
		$mysqlcards = "$playerarr[cards] $cardid";
		mysql_query ( "update blackjack set points=points+$cardarr[points], cards='$mysqlcards' where userid=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
		if ($points == 21) {
			$waitres = mysql_query ( "select count(*) from blackjack where status='waiting'" );
			$waitarr = mysql_fetch_array ( $waitres );
			if ($waitarr [0] > 0) {
				$r = mysql_query ( "select * from blackjack where status='waiting' order by date asc LIMIT 1" );
				$a = mysql_fetch_assoc ( $r );
				if ($a ["points"] != 21) {
					$winorlose = "вы Выйграли " . mksize ( $mb );
					mysql_query ( "update users set uploaded = uploaded + $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
					mysql_query ( "update users set uploaded = uploaded - $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
					//mysql_query("update casino set win = win + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
					//mysql_query("update casino set lost = lost + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
					mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
					mysql_query ( "delete from blackjack where userid=$a[userid]" );
					$dt = sqlesc ( get_date_time () );
					$subject = sqlesc ( "21 очко\n" );
					$msg = sqlesc ( "Вы проиграли " . mksize ( $mb ) . " $CURUSER[username] (у Вас $a[points], у $CURUSER[username] 21 очко). [url=blackjack.php]Играть еще?[/url]" );
					mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
				} else {
					$winorlose = "ничья";
				}
				stderr ( "Игра окончена", "у Вас 21 очко, Вашим опонентом был " . get_user_name ( $a ["userid"] ) . ", с $a[points] очками на борту, $winorlose. <a href=blackjack.php>Играть еще?</a>" );
			} else {
				mysql_query ( "update blackjack set status = 'waiting', date=" . sqlesc ( get_date_time () ) . " where userid = $CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				stderr ( "Игра окончена", "у Вас 21 очко, пока что нет других игроков. Вам придется подождать соперника. Вы получите ЛС о результатах игры" );
			}
		} elseif ($points > 21) {
			$waitres = mysql_query ( "select count(*) from blackjack where status='waiting'" );
			$waitarr = mysql_fetch_array ( $waitres );
			if ($waitarr [0] > 0) {
				$r = mysql_query ( "select * from blackjack where status='waiting' order by date asc LIMIT 1" );
				$a = mysql_fetch_assoc ( $r );
				if ($a ["points"] == $points) {
					$winorlose = "Ничья!";
					mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
					mysql_query ( "delete from blackjack where userid=$a[userid]" );
					$dt = sqlesc ( get_date_time () );
					$subject = sqlesc ( "21 очко\n" );
					$msg = sqlesc ( "Вашим соперником был $CURUSER[username], победила дружба! [url=blackjack.php]Играть еще?[/url]" );
					mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
				} elseif ($a ["points"] > $points) {
					$winorlose = "Вы выйграли " . mksize ( $mb );
					mysql_query ( "update users set uploaded = uploaded + $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
					mysql_query ( "update users set uploaded = uploaded - $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
					//mysql_query("update casino set win = win + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
					//mysql_query("update casino set lost = lost + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
					mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
					mysql_query ( "delete from blackjack where userid=$a[userid]" );
					$dt = sqlesc ( get_date_time () );
					$subject = sqlesc ( "21 очко\n" );
					$msg = sqlesc ( "Вы проиграли " . mksize ( $mb ) . " $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $points). [url=blackjack.php]Играть еще?[/url]" );
					mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
				} elseif ($a ["points"] < $points) {
					$winorlose = "Вы проиграли " . mksize ( $mb );
					mysql_query ( "update users set uploaded = uploaded - $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
					mysql_query ( "update users set uploaded = uploaded + $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
					//mysql_query("update casino set win = win + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
					//mysql_query("update casino set lost = lost + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
					mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
					mysql_query ( "delete from blackjack where userid=$a[userid]" );
					$dt = sqlesc ( get_date_time () );
					$subject = sqlesc ( "21 очко\n" );
					$msg = sqlesc ( "Вы выйграли " . mksize ( $mb ) . " у $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $points). [url=blackjack.php]Играть еще?[/url] " );
					mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
				}
				stderr ( "Игра окончена", "у Вас $points, Вашим соперником был " . get_user_name ( $a ["userid"] ) . ", с $a[points] очками на борту, $winorlose. <a href=blackjack.php>Играть еще?</a>" );
			} else {
				mysql_query ( "update blackjack set status = 'waiting', date=" . sqlesc ( get_date_time () ) . " where userid = $CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				stderr ( "Игра окончена", "у Вас $points, пока что нет других игроков. Вам придется подождать соперника. Вы получите ЛС о результатах игры" );
			}
		} 

		else {
			stdhead ();
			begin_frame ( "21 очко" );
			print ( "<center><h1>Привет, <b><a href=userdetails.php?id=$CURUSER[id]>$CURUSER[username]</a></b>. Готов просадить свои mb?!</h1>\n" );
			print ( "<table cellspacing=0 cellpadding=3 width=600><tr><td style='border: none;'  align=center><img src=" . $pic_base_url . "blackjack.jpg></td></tr>\n" );
			print ( "<tr><td style='border: none;'  colspan=2 cellspacing=0 cellpadding=5 >" );
			print ( "<table class=message width=100% cellspacing=0 cellpadding=5 bgcolor=white>\n" );
			print ( "<tr><td style='border: none;'  align=center>$showcards</td></tr>" );
			print ( "<tr><td style='border: none;'  align=center><b>Очки = $points</b></td></tr>" );
			print ( "<form name=blackjack method=post action=$phpself>" );
			print ( "<tr><td style='border: none;'  align=center><input type=hidden name=game value=cont><input type=submit class=button value='Еще давай'></td></tr>" );
			print ( "</form>" );
			print ( "<form name=blackjack method=post action=$phpself>" );
			print ( "<tr><td style='border: none;'  align=center><input type=hidden name=game value=stop><input type=submit class=button value='Хватит'></td></tr>" );
			print ( "</form>" );
			print ( "</table><br>" );
			print ( "</td></tr></table><br></center>" );
			end_frame ();
			stdfoot ();
		}
	} elseif ($_POST ["game"] == 'stop') {
		
		$playeres = mysql_query ( "select * from blackjack where userid=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
		$playerarr = mysql_fetch_array ( $playeres );
		if ($playerarr ["started"] == 0)
			stderr ( "Ошибка", "Халява кончилась :)" );
		$waitres = mysql_query ( "select count(*) from blackjack where status='waiting'" );
		$waitarr = mysql_fetch_array ( $waitres );
		if ($waitarr [0] > 0) {
			$r = mysql_query ( "select * from blackjack where status='waiting' order by date asc LIMIT 1" );
			$a = mysql_fetch_assoc ( $r );
			if ($a ['userid'] == $CURUSER ['id'])
				stderr ( "Ошибка", "Вы не можете играть сами с собой" );
			if ($a ["points"] == $playerarr [points]) {
				$winorlose = "ничья";
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вашим соперником был $CURUSER[username], победила дружба! [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			} elseif ($a ["points"] < $playerarr [points] && $a [points] < 21) {
				$winorlose = "Вы выйграли " . mksize ( $mb );
				mysql_query ( "update users set uploaded = uploaded + $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				mysql_query ( "update users set uploaded = uploaded - $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
				//mysql_query("update casino set win = win + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
				//mysql_query("update casino set lost = lost + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вы проиграли " . mksize ( $mb ) . " $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $playerarr[points]). [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			} elseif ($a ["points"] > $playerarr [points] && $a [points] < 21) {
				$winorlose = "Вы проиграли " . mksize ( $mb );
				mysql_query ( "update users set uploaded = uploaded - $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				mysql_query ( "update users set uploaded = uploaded + $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
				//mysql_query("update casino set win = win + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
				//mysql_query("update casino set lost = lost + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вы выйграли " . mksize ( $mb ) . " у $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $playerarr[points]). [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			} elseif ($a ["points"] == 21) {
				$winorlose = "Вы проиграли " . mksize ( $mb );
				mysql_query ( "update users set uploaded = uploaded - $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				mysql_query ( "update users set uploaded = uploaded + $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
				//mysql_query("update casino set win = win + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
				//mysql_query("update casino set lost = lost + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вы выйграли " . mksize ( $mb ) . " у $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $playerarr[points]). [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			} elseif ($a ["points"] < $playerarr [points] && $a [points] > 21) {
				$winorlose = "Вы проиграли " . mksize ( $mb );
				mysql_query ( "update users set uploaded = uploaded - $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				mysql_query ( "update users set uploaded = uploaded + $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
				//mysql_query("update casino set win = win + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
				//mysql_query("update casino set lost = lost + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вы выйграли " . mksize ( $mb ) . " у $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $playerarr[points]). [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			} elseif ($a ["points"] > $playerarr [points] && $a [points] > 21) {
				$winorlose = "Вы выйграли " . mksize ( $mb );
				mysql_query ( "update users set uploaded = uploaded + $mb where id=$CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
				mysql_query ( "update users set uploaded = uploaded - $mb where id=$a[userid]" ) or sqlerr ( __FILE__, __LINE__ );
				//mysql_query("update casino set win = win + $mb where userid=$CURUSER[id]") or sqlerr(__FILE__, __LINE__);
				//mysql_query("update casino set lost = lost + $mb where userid=$a[userid]") or sqlerr(__FILE__, __LINE__);
				mysql_query ( "delete from blackjack where userid=$CURUSER[id]" );
				mysql_query ( "delete from blackjack where userid=$a[userid]" );
				$dt = sqlesc ( get_date_time () );
				$subject = sqlesc ( "21 очко\n" );
				$msg = sqlesc ( "Вы проиграли " . mksize ( $mb ) . " $CURUSER[username] (у Вас $a[points], у $CURUSER[username] $playerarr[points]). [url=blackjack.php]Играть еще?[/url]" );
				mysql_query ( "INSERT INTO messages (sender, receiver, added, msg, subject, poster) VALUES(0, $a[userid], $dt, $msg, $subject, 0)" ) or sqlerr ( __FILE__, __LINE__ );
			}
			stderr ( "Игра окончена", "у Вас $playerarr[points], Вашим соперником был " . get_user_name ( $a ["userid"] ) . ", у него $a[points], $winorlose <a href=blackjack.php>Играть еще?</a>" );
		} else {
			mysql_query ( "update blackjack set status = 'waiting', date=" . sqlesc ( get_date_time () ) . " where userid = $CURUSER[id]" ) or sqlerr ( __FILE__, __LINE__ );
			stderr ( "Игра окончена", "у Вас $points, пока что нет других игроков. Вам придется подождать соперника. Вы получите ЛС о результатах игры" );
		}
	}
} else {
	//if (playerexists($CURUSER[id]) == false)
	//mysql_query("insert into casino (userid, win, lost) values($CURUSER[id], 0, 0)") or sqlerr(__FILE__, __LINE__);
	stdhead ();
	begin_frame ( "21 очко" );
	print ( "<center><table cellspacing=0 cellpadding=3 width=400>\n" );
	print ( "<tr><td style='border: none;'  colspan=2 cellspacing=0 cellpadding=5 align=center>" );
	//print("<h3><a href=players.php>Stats</a></h3>");
	print ( "<table class=message width=100% cellspacing=0 cellpadding=10 bgcolor=white>\n" );
	print ( "<tr><td style='border: none;'  align=center><img src=" . $pic_base_url . "blackjack.jpg><h3>Правила</h3>Вы должны набрать большее количество очков, чем у оппонента, но не более 21</td></tr>" );
	print ( "</table><br>" );
	print ( "<form name=form method=post action=$phpself><input type=hidden name=game value=start><input type=submit class=button value='Сдать!'>" );
	print ( "</td></tr></table><br><br></center>" );
	end_frame ();
	
	stdfoot ();
}
?>