<?php
$total_amount = $balance + $winning;

if ($total_amount >= $entry_fee) {

    // কত টাকা balance থেকে, কতটা winning থেকে কাটবে
    $deduct_balance = min($balance, $entry_fee);
    $remaining = $entry_fee - $deduct_balance;
    $deduct_winning = max(0, $remaining);

    // ইউজার আপডেট
    $update_sql = "UPDATE users 
                   SET balance = balance - $deduct_balance, 
                       winning = winning - $deduct_winning, 
                       total_play = total_play + 1 
                   WHERE email = '$email'";

    // insert into statistics
    $statistics = "INSERT INTO statistics (email, type, match_id, match_title, played_on, paid, winnings)
                   VALUES ('$email', 'freefire', '$match_id', '$match_title', '$played_on', '$entry_fee', $deduct_winning)";

    // match join increment
    $add_join = ($type === 'duo') ? 2 : (($type === 'squad') ? 4 : 1);
    $another_sql = "UPDATE freefire SET total_joiner = total_joiner + $add_join WHERE id = $match_id";

    // insert joiners
    $insert_sqls = [];
    $insert_sqls[] = "INSERT INTO joiners (name, type, email, match_id, fcm_key)
                      VALUES ('$name', 'freefire', '$email', '$match_id', '$fcm_key')";
    if ($type === 'duo') $insert_sqls[] = "INSERT INTO joiners (name, type, email, match_id, fcm_key)
                                           VALUES ('{$_POST['name2']}', 'freefire', '$email', '$match_id', '$fcm_key')";
    if ($type === 'squad') {
        $insert_sqls[] = "INSERT INTO joiners (name, type, email, match_id, fcm_key)
                          VALUES ('{$_POST['name2']}', 'freefire', '$email', '$match_id', '$fcm_key')";
        $insert_sqls[] = "INSERT INTO joiners (name, type, email, match_id, fcm_key)
                          VALUES ('{$_POST['name3']}', 'freefire', '$email', '$match_id', '$fcm_key')";
        $insert_sqls[] = "INSERT INTO joiners (name, type, email, match_id, fcm_key)
                          VALUES ('{$_POST['name4']}', 'freefire', '$email', '$match_id', '$fcm_key')";
    }

    $ok = $conn->query($update_sql) && $conn->query($another_sql) && $conn->query($statistics);
    foreach ($insert_sqls as $sql) $ok = $ok && $conn->query($sql);

    echo $ok ? "Join Successfully" : "Error Joining: " . $conn->error;

} else {
    echo "Insufficient Balance";
}
?>