

int CountTotalTokens(object oPC, string sTokenTag) {
    object oItem = GetFirstItemInInventory(oPC);
    int nTotalTokens = 0;

    while (GetIsObjectValid(oItem)) {
        if (GetTag(oItem) == sTokenTag) {
            int stackSize = GetItemStackSize(oItem);
            nTotalTokens += stackSize;
            // Debug message
          //  SendMessageToPC(oPC, "Found " + IntToString(stackSize) + " tokens in stack. Total now: " + IntToString(nTotalTokens));
        }
        oItem = GetNextItemInInventory(oPC);
    }

    return nTotalTokens;
}

// Function to deduct tokens
void DeductTokens(object oPC, string sTokenTag, int nTokensToDeduct) {
    object oItem = GetFirstItemInInventory(oPC);

    while (GetIsObjectValid(oItem) && nTokensToDeduct > 0) {
        if (GetTag(oItem) == sTokenTag) {
            int nStackAmount = GetItemStackSize(oItem);
            if (nStackAmount <= nTokensToDeduct) {
                DestroyObject(oItem);
                nTokensToDeduct -= nStackAmount;
            } else {
                SetItemStackSize(oItem, nStackAmount - nTokensToDeduct);
                nTokensToDeduct = 0; // All tokens have been deducted
            }
        }
        oItem = GetNextItemInInventory(oPC);
    }
}


void main()
{
    object oPC = GetPlaceableLastClickedBy(); // The player character interacting with a placeable
    object oClickedObject = OBJECT_SELF; // The object that was clicked

    // Check if the player already has a bet placed
    if (GetLocalInt(oPC, "WHEEL_BET_AMOUNT") > 0)
    {
        // Inform the player they already placed a bet
        SendMessageToPC(oPC, "You already placed a bet! Be sure to select a number on the wheel and play a round before betting a new amount of tokens.");
        return;
    }

    // Retrieve the token bet amount set on the clicked object
    int nTokenBet = GetLocalInt(oClickedObject, "TOKEN_BET");

    // Check how many tokens the player has
    string sTokenTag = "I_CAS_TOKEN"; // Tag for the token item
    int nTotalTokens = CountTotalTokens(oPC, sTokenTag);

    // Check if the player has enough tokens
    if (nTotalTokens < nTokenBet)
    {
        // Player does not have enough tokens
        SendMessageToPC(oPC, "You do not have enough tokens to place this bet.");
        return;
    }

    // Deduct the tokens from the player's inventory
    DeductTokens(oPC, sTokenTag, nTokenBet);

    // Set the WHEEL_BET_AMOUNT variable on the player character
    SetLocalInt(oPC, "WHEEL_BET_AMOUNT", nTokenBet);

    // Send a confirmation message to the player
    SendMessageToPC(oPC, "You have placed a bet of " + IntToString(nTokenBet) + " tokens.");
}

