if (file_exists($cachefile)) {
    $all_bets = json_decode(file_get_contents($cachefile), TRUE);
} else {
    $all_bets = getAllUserBetsNoWinnerAndWriteToCache();
}
$time1 = time();
$time2 = time() + 60 * 60 * 15;
$where = "g_schedTo >= '{$time1}' AND g_schedTo <= '{$time2}' AND g_betMinimum > 0 AND g_isClosed = 0";
$all_games = getAllGames($where);
// get all the games
if ($all_games) {
    foreach ($all_games as $ag) {
        $total_coins = 0;
        $g_id = $ag['g_id'];
        $bet_minimum = $ag['g_betMinimum'];
        if ($all_bets) {
            foreach ($all_bets as $ab) {
                if ($ab['g_id'] == $g_id) {
                    $total_coins += $ab['ub_coins'];
                }
            }
        } else {
            break;
        }
        if ($bet_minimum > $total_coins) {
            cancelGame($g_id);
            // cancel this game
        }
    }
    // foreach $all_games
}
}
$bool = false;
$game_id = isset($_POST['gi']) ? $_POST['gi'] : 0;
$bi_id = isset($_POST['wi']) ? $_POST['wi'] : 0;
// winning item
$coin_div = isset($_POST['div']) ? $_POST['div'] : 0;
// commission
$is_cancel = isset($_POST['cancel']) ? $_POST['cancel'] : 0;
// cancel this game
$house_com = isset($_POST['hc']) ? $_POST['hc'] : 0;
// house commission
$total_bet_amt = isset($_POST['tc']) ? $_POST['tc'] : 0;
// total coins bet for this game
if ($is_cancel != 'false') {
    // cancel the game; return bets
    cancelGame($game_id);
    $user_bets = getUserBets($game_id);
    // get all user bets from this game
    $bool = returnUserBets($user_bets, $game_id, true);
    // insert to coin_deals table and update users' COIN. true means it's cancelled
} else {
    // close the game; process winners
    closeGame($game_id);
    // close this game
    setBetItemWinner($bi_id);
    // bet_item db table
    setUserBetWinners($game_id, $bi_id);
    // tag the winners in user_bets db table
    $winners = getUserBetWinners($game_id, $bi_id);
    // get all user bets that won from this game
    //$total_bet_amt = returnUserBets($winners); // return users' bets and update users' coins