<?php 

include("include/connection.php");


$game_sql = "select * from periodid order by id desc limit 1";
$game_query = mysqli_query($con,$game_sql);
$game_data = mysqli_fetch_array($game_query);
$game_rows = $game_data['period'];

///////

$sql_manual = mysqli_query($con,"select * from andarmanual_result where period_id = '$game_rows'");
$manual = mysqli_num_rows($sql_manual);

if($manual == 1)
{
    $manual_rows = mysqli_fetch_array($sql_manual);
    $result_rand = $manual_rows['result'] ;  
}else{


$result1 = mysqli_query($con, "SELECT SUM(amount) AS amount FROM andar_bet where period_id='$game_rows' and name='1'"); 
$row1 = mysqli_fetch_assoc($result1); 
$sum1 = $row1['amount'];

$result2 = mysqli_query($con, "SELECT SUM(amount) AS amount FROM andar_bet where period_id='$game_rows' and name='2'"); 
$row2 = mysqli_fetch_assoc($result2); 
$sum2 = $row2['amount'];
 
   
   if($sum1 > $sum2)
   {
    $result_rand = 2;   
   }elseif($sum1 < $sum2)
   {
    $result_rand = 1;    
   }else{
       
     $result = rand(1,7);
     
    if($result == 1 || $result == 4 || $result == 5 || $result == 7)
    {
     $result_rand = 1;
     }
     if($result == 2 || $result == 3 || $result == 6)
     {
      $result_rand = 2; 
     }

    }
}
$cardnumber_sql1 = mysqli_query($con,"select * from card_number order by id desc");
 $cardnumber_rows1 = mysqli_fetch_array($cardnumber_sql1);
 $number1 = $cardnumber_rows1['number'];
 
$result_sql = mysqli_query($con,"insert into andar_result(period_id,number,result)values('$game_rows','$number1','$result_rand')");

$bet_sql = mysqli_query($con,"select * from andar_bet where period_id='$game_rows'");

while($bet_rows = mysqli_fetch_array($bet_sql))
{

    
	$name = $bet_rows['name'];
	$userid = $bet_rows['userid'];
	$bet_amount = $bet_rows['pay_amount'];
	
	
	if($name == $result_rand)
	{
	    
        $wallet_sql = mysqli_query($con,"select * from tbl_wallet where userid = '$userid'");
		$wallet_rows = mysqli_fetch_array($wallet_sql);
		$wallet_balance = $wallet_rows['amount'] + $bet_amount;
		$wallet_insert = mysqli_query($con,"update tbl_wallet set amount='$wallet_balance' where userid='$userid'");
	
		$bet_updatess ="update andar_bet set result='$result_rand',status=1 where userid='$userid' and period_id='$game_rows'";
		$bet_success =  mysqli_query($con,$bet_updatess);
	
	 }else	{
	   
        $bet_updateff ="update andar_bet set result='$result_rand',status=2 where userid='$userid' and period_id='$game_rows'";
		$bet_fail =  mysqli_query($con,$bet_updateff);
		
    }
}


$image_rand = rand(1,4);
$number_rand = rand(1,10);

$cardnumber_sql = mysqli_query($con,"insert into card_number(card,number)values('$image_rand','$number_rand')");



$currentperiod = $game_rows + 1;
$result_sql = mysqli_query($con,"insert into periodid(period)values('$currentperiod')");

 




?>