<?php
require ("../config.php");


// ме юбрнпхгнбюм


if(empty($u_id)){
echo 'window.location="/login";';
exit;
}


// гюыхрю нр вюяршу ярюбнй


if(!empty($_SESSION['gtime']) && $_SESSION['gtime']>$time-2){ exit; }
$_SESSION['gtime']=$time;


if(empty($_GET['num'])){ exit; }
$num=preg_replace("#[^0-9]+#i",'',$_GET['num']);
$num+=0;
if(empty($num) || strlen($num)>2 || empty($fix[$num])){
exit;
}


$sum_bet=$fix[$num]['bet'];


if(empty($sum_bet) || !is_numeric($sum_bet) || strlen($sum_bet)>10){ exit; }
if($mydm['balance']<$sum_bet){ echo 'fix_no_money_show();'; exit; }


// __________________ яоепбю бшахпюел бяе дюммше йнлмюрш _______________


$absent=0;


$s_q=mysqli_query($db,"SELECT * FROM room_fix WHERE id=$num LIMIT 1") or die('cant room_fix');
$s_m=mysqli_fetch_assoc($s_q);
// гюыхрю, мю яксвюи, еякх опнькюъ хцпю ме яр╗прю
if($s_m['closed']==1){ echo 'its closed'; exit; }
if(!isset($s_m['hash'])){ echo 'no hash'; exit; }
$hash=$s_m['hash'];
for($n=1;$n<$fix[$num]['players']+1;$n++){
// сфе декюк ярюбйс
if($u_id==$s_m['uid_'.$n]){ echo 'bet already done'; exit; }
// мюундхл ябнандмне леярн
if($s_m['uid_'.$n]==0 && empty($place)){ $place=$n; }
// гюыхрю, мю яксвюи, еякх опнькюъ хцпю ме дн йнмжю яр╗прю
if($s_m['uid_'.$n]==0){ $absent=1; }
if($s_m['uid_'.$n]!=0 && $absent==1){ echo 'break found'; exit; }
}


if(empty($place)){ echo 'no places'; exit; }


// __________________ ярюбхл _______________


mysqli_query($db,"UPDATE room_fix SET uid_$place='$u_id',login_$place='".$mydm['login']."',avatar_$place='".$mydm['avatar']."' WHERE id='$num' AND hash='$hash' AND uid_$place=0 LIMIT 1") or die('cant update room_fix');


$users_q=mysqli_query($db,"SELECT * FROM room_fix WHERE id='$num' AND hash='$hash' AND uid_$place='$u_id' LIMIT 1") or die('cant select room_fix');
$users_m=mysqli_fetch_assoc($users_q);


if(empty($users_m['id'])){ echo 'not mine bet'; exit; }


// __________________ еякх онярюбхкняэ - опнднкфюел _______________


// дкъ йнмйспяю ярюбнй


$cbdq=mysqli_query($db,"SELECT contest_bet_d_1,contest_bet_d_2 FROM data LIMIT 1") or die('cant select data');
$cbdm=mysqli_fetch_assoc($cbdq);


$contest_bet_d_1=strtotime($cbdm['contest_bet_d_1']);
$contest_bet_d_2=strtotime($cbdm['contest_bet_d_2']);
$contest_bet=0;


if($time>$contest_bet_d_1 && $time<$contest_bet_d_2){ $contest_bet=$sum_bet; }


// __________________ яохяшбюел аюкюмя _______________


mysqli_query($db,"UPDATE users SET balance=balance-$sum_bet,bets_time=$time,bets_fsum=bets_fsum+$sum_bet,bets_count=bets_count+1,contest_bet=contest_bet+$contest_bet WHERE uid=$u_id LIMIT 1") or die('cant user update balance');


$mydm['balance']-=$sum_bet;
$mydm['balance']=number_format($mydm['balance'],4,'.','');


// __________________ еякх щрн ашк онякедмхи хцпнй _______________


if($place==$fix[$num]['players']){


// яохл 2 яейсмдш, врнаш дпсцхе сяоекх гюйнмвхрэ ябнх опнбепйх


sleep(2);


// бшахпюел бяеу хцпнйнб


$users_uid=array();


for($n=1;$n<$fix[$num]['players']+1;$n++){
if($users_m['uid_'.$n]!=0){ $users_uid[]=$users_m['uid_'.$n]; }
}


if(empty($users_uid) || sizeof($users_uid)!=$fix[$num]['players']){ exit; }


shuffle($users_uid);
$winners_id=array_slice($users_uid,0,$fix[$num]['winners']);
$lost_id=array_slice($users_uid,$fix[$num]['winners'],$fix[$num]['players']);


if(empty($winners_id) || sizeof($winners_id)!=$fix[$num]['winners']){ exit; }
if(empty($lost_id) || sizeof($lost_id)!=($fix[$num]['players']-$fix[$num]['winners'])){ exit; }


$winners_text='';
$lost_text='';


for($n=1;$n<$fix[$num]['players']+1;$n++){
for($i=0;$i<sizeof($winners_id);$i++){
$p_url=md5($users_m['uid_'.$n].$p_hash);
$p_url=$users_m['uid_'.$n].'_'.substr($p_url,0,4);
$users_m['login_'.$n]=str_replace(' ','<br>',$users_m['login_'.$n]);
if($users_m['uid_'.$n]==$winners_id[$i]){ $winners_text.='<a target="_blank" href="/profile/'.$p_url.'"><div>'.$users_m['login_'.$n].'</div><img src="'.$users_m['avatar_'.$n].'" /></a>'; }
}
}


for($n=1;$n<$fix[$num]['players']+1;$n++){
for($i=0;$i<sizeof($lost_id);$i++){
$p_url=md5($users_m['uid_'.$n].$p_hash);
$p_url=$users_m['uid_'.$n].'_'.substr($p_url,0,4);
$users_m['login_'.$n]=str_replace(' ','<br>',$users_m['login_'.$n]);
if($users_m['uid_'.$n]==$lost_id[$i]){ $lost_text.='<a target="_blank" href="/profile/'.$p_url.'"><div>'.$users_m['login_'.$n].'</div><img src="'.$users_m['avatar_'.$n].'" /></a>'; }
}
}


mysqli_query($db,"INSERT INTO room_fix_winners SET num='$num',date='$time',date_word='".date("d.m.y H:i:s",$time)."',winners='$winners_text',lost='$lost_text'") or die('cant set room_fix_winners');
$last_id=0+mysqli_insert_id($db);


// пюгдюел бшхцпшьх онаедхрекъл


$com=$fix_r_1+$fix_r_2+$fix_r_3+$fix[$num]['to_admin'];
$priz=((($fix[$num]['players']-$fix[$num]['winners'])*$fix[$num]['bet'])/100*(100-$com))/$fix[$num]['winners'];
$priz=number_format($priz,2,'.','');
$priz=$fix[$num]['bet']+$priz+0;


for($n=0;$n<sizeof($winners_id);$n++){
mysqli_query($db,"UPDATE users SET balance=balance+'$priz',bets_wfsum=bets_wfsum+'$priz',bets_win=bets_win+1 WHERE uid='".$winners_id[$n]."' LIMIT 1") or die('cant update winner balance');
}


// намскъел йнлмюрс


mysqli_query($db,"UPDATE room_fix SET closed=1,hash='".microtime(true)."',uid_1=0,uid_2=0,uid_3=0,uid_4=0,uid_5=0,uid_6=0,uid_7=0,uid_8=0,uid_9=0,uid_10=0,login_1='',login_2='',login_3='',login_4='',login_5='',login_6='',login_7='',login_8='',login_9='',login_10='',avatar_1='',avatar_2='',avatar_3='',avatar_4='',avatar_5='',avatar_6='',avatar_7='',avatar_8='',avatar_9='',avatar_10='' WHERE id='$num' LIMIT 1") or die('cant empty room_fix 1');




$p_url=md5($u_id.$p_hash);
$p_url=$u_id.'_'.substr($p_url,0,4);
$winners_text='winners_uids=['.implode(',',$winners_id).'];last_id_new='.$last_id.';set_last("'.$mydm['uid'].'","'.$p_url.'","'.$mydm['avatar'].'","'.$mydm['login'].'");toins=`<tr><td class="fix_w_num">'.$last_id.'</td><td class="fix_w_winners">'.$winners_text.'</td><td class="fix_w_lost">'.$lost_text.'</td></tr>`;document.getElementById("winners_text").innerHTML=`'.$winners_text.'`;';


mysqli_query($db,"UPDATE room_fix SET closed=0,winners='$winners_text' WHERE id='$num' LIMIT 1") or die('cant empty room_fix 2');
mysqli_query($db,"OPTIMIZE TABLE room_fix") or die('cant optimize room_fix');


// бшахпюел яонмянпнб опнхцпюбьху


$lost=array();
$uids=implode(',',$lost_id);


$lost_q=mysqli_query($db,"SELECT uid,login,avatar,ref_id_1,ref_id_2,ref_id_3,ref_ban_1,ref_ban_2,ref_ban_3 FROM users WHERE uid IN ($uids) LIMIT ".sizeof($lost_id)) or die ('cant select sponsors');
while($lost_m=mysqli_fetch_assoc($lost_q)){
if($lost_m['ref_id_1']>0 && $lost_m['ref_ban_1']==0){ $lost[$lost_m['uid']]['ref_1']=$lost_m['ref_id_1']; $lost[$lost_m['uid']]['login']=$lost_m['login']; $lost[$lost_m['uid']]['avatar']=$lost_m['avatar']; }
if($lost_m['ref_id_2']>0 && $lost_m['ref_ban_2']==0){ $lost[$lost_m['uid']]['ref_2']=$lost_m['ref_id_2']; $lost[$lost_m['uid']]['login']=$lost_m['login']; $lost[$lost_m['uid']]['avatar']=$lost_m['avatar']; }
if($lost_m['ref_id_3']>0 && $lost_m['ref_ban_3']==0){ $lost[$lost_m['uid']]['ref_3']=$lost_m['ref_id_3']; $lost[$lost_m['uid']]['login']=$lost_m['login']; $lost[$lost_m['uid']]['avatar']=$lost_m['avatar']; }
}


// рнкэйн реоепэ пюгдю╗л петяйхе


$ref_send=array();
$sended_sum=0;
$unused_sum=0;


foreach($lost as $u=>$v){
if(!empty($lost[$u]['ref_1'])){
$to_send_sum=$fix[$num]['bet']/100*$fix_r_1;
$to_send_sum=number_format($to_send_sum,4,'.','');
$to_send_sum+=0;
if($to_send_sum>0){
$ref_send[]=array($u,$lost[$u]['avatar'],$lost[$u]['login'],1,$to_send_sum,$lost[$u]['ref_1']);
$sended_sum+=$to_send_sum;
}
}
if(!empty($lost[$u]['ref_2'])){
$to_send_sum=$fix[$num]['bet']/100*$fix_r_2;
$to_send_sum=number_format($to_send_sum,4,'.','');
$to_send_sum+=0;
if($to_send_sum>0){
$ref_send[]=array($u,$lost[$u]['avatar'],$lost[$u]['login'],2,$to_send_sum,$lost[$u]['ref_2']);
$sended_sum+=$to_send_sum;
}
}
if(!empty($lost[$u]['ref_3'])){
$to_send_sum=$fix[$num]['bet']/100*$fix_r_3;
$to_send_sum=number_format($to_send_sum,4,'.','');
$to_send_sum+=0;
if($to_send_sum>0){
$ref_send[]=array($u,$lost[$u]['avatar'],$lost[$u]['login'],3,$to_send_sum,$lost[$u]['ref_3']);
$sended_sum+=$to_send_sum;
}
}
}


$to_refs=($fix[$num]['bet']*($fix[$num]['players']-$fix[$num]['winners']))/100*($fix_r_1+$fix_r_2+$fix_r_3);
$to_refs=number_format($to_refs,4,'.','');
$sended_sum=number_format($sended_sum,4,'.','');
$unused_sum=$to_refs-$sended_sum;
$unused_sum=number_format($unused_sum,4,'.','');
$unused_sum+=0;


// нропюбкъел юдлхмс петяйхе нашвмше х мепнгдюммше
// мепнгдюммюъ ясллю лнфер ашрэ х лемэье мскъ, мн щрн йюй йнппейрхпнбйю


$to_admin=$fix[$num]['bet']*($fix[$num]['players']-$fix[$num]['winners'])/100*$fix[$num]['to_admin'];
$to_admin=number_format($to_admin,4,'.','');


mysqli_query($db,"UPDATE data SET admin_fix_s_1=admin_fix_s_1+$to_admin,admin_fix_s_2=admin_fix_s_2+$unused_sum,ref_sum=ref_sum+$sended_sum,games_fix=$last_id LIMIT 1") or die('cant update admin profit');


// нропюбкъел петяйхе петнбндюл
// х с петепюкю гюохяшбюел яйнкэйн петяйхл опхм╗я ябнхл петнбндюл


foreach($ref_send as $rsend){
mysqli_query($db,"INSERT INTO refs_profit SET date='$time',date_word='".date("d.m.y H:i:s",$time)."',ref_id='".$rsend[0]."',ref_avatar='".$rsend[1]."',ref_login='".$rsend[2]."',ref_level='".$rsend[3]."',rsum='".$rsend[4]."',sp_id='".$rsend[5]."'") or die('cant insert refs_profit');
mysqli_query($db,"UPDATE users SET balance=balance+".$rsend[4].",nrs=nrs+".$rsend[4].",refs_s_".$rsend[3]."=refs_s_".$rsend[3]."+".$rsend[4]." WHERE uid='".$rsend[5]."' LIMIT 1") or die('cant update referer balance');
mysqli_query($db,"UPDATE users SET toref_s_".$rsend[3]."=toref_s_".$rsend[3]."+".$rsend[4]." WHERE uid='".$rsend[0]."' LIMIT 1") or die('cant update refereral toref_s');
}


}


echo 'document.getElementById("bet").style.display="none";if(document.getElementById("winners").style.display=="none"){ document.getElementById("done").style.display="block"; }';
echo 'document.getElementById("my_balance").innerHTML="'.preg_replace('#(\..{2}).*#','$1',$mydm['balance']).'";';


// __________________ ондявер хцпнйнб х аюмйю бн бяеу йнлмюрюу _______________


$players=0;
$bank=0;


$pb_q=mysqli_query($db,"SELECT * FROM room_fix") or die('cant room_fix');
while($pb_m=mysqli_fetch_assoc($pb_q)){
for($n=1;$n<$fix[$pb_m['id']]['players']+1;$n++){
if($pb_m['uid_'.$n]!=0){ $players++; $bank+=$fix[$pb_m['id']]['bet']; }
}
}


$fix_status='<div class="head_room_players">хЦПНЙНБ: <span>'.$players.'</span></div> <div class="head_room_bank">аЮМЙ: <span>'.$bank.' П.</span></div>';


mysqli_query($db,"UPDATE room_status SET room_fix='$fix_status' LIMIT 1") or die('cant update room_status');


?>
