#include "cas_casinoinc"

void main() 
{
    object oPC = GetLastUsedBy();
    string sPCName = GetName(oPC);
    string sPlayerUsername = GetPCPlayerName(oPC);
    string sCDKey = GetPCPublicCDKey(oPC, TRUE); // TRUE for the short version of the CD key

    object oSlotMachine = OBJECT_SELF;
    object oHandle = GetItemPossessedBy(oPC, "I_CAS_CASINOHANDLE");

    if (GetLocalInt(oSlotMachine, "SLOT_MACHINE_USED")) 
    {
        SendMessageToPC(oPC, "The slot machine is cooling down. Please wait.");
        return;
    }

    SetLocalInt(oSlotMachine, "SLOT_MACHINE_USED", 1);
    DelayCommand(15.0, SetLocalInt(oSlotMachine, "SLOT_MACHINE_USED", 0));
    DelayCommand(15.0, SendMessageToPC(oPC, "The slot machine is ready for another pull!"));

    EnsureTokenPouch(oPC);

    int nCurrentTokens = GetLocalInt(oHandle, "nCAS_TOKEN");
    int nBetAmount = GetLocalInt(oHandle, "nBET_AMOUNT");

    if (nCurrentTokens < nBetAmount) 
    {
        SendMessageToPC(oPC, "Not enough tokens. You need at least " + IntToString(nBetAmount) + " tokens to play.");
        return;
    }

    DeductTokens(oPC, nBetAmount);

    int nSlot1 = Random(6) + 1;
    int nSlot2 = Random(6) + 1;
    int nSlot3 = Random(6) + 1;
    int nVFX = VFX_NONE;
    string sAnnouncement = "";

    // Display slot results and determine tickets awarded
    DisplaySlotResults(oPC, nSlot1, nSlot2, nSlot3, nBetAmount, nVFX, sAnnouncement);

    // Retrieve the number of tickets awarded
    int nTicketsAwarded = GetLocalInt(oPC, "nTicketsAwarded"); // Ensure DisplaySlotResults sets this value

    // Prepare the log message
    string sLogMessage;

    // Check for winning combination and create log message
    if (nSlot1 == nSlot2 && nSlot2 == nSlot3)
    {
        sLogMessage = "The character, " + sPCName + ", Player Name: " + sPlayerUsername + " (" + sCDKey + "), bet " + IntToString(nBetAmount) + " tokens, won on combination " + IntToString(nSlot1) + IntToString(nSlot2) + IntToString(nSlot3) + ", and was awarded " + IntToString(nTicketsAwarded) + " tickets. Game: Slot Machine";
    }
    else
    {
        sLogMessage = "The character, " + sPCName + ", Player Name: " + sPlayerUsername + " (" + sCDKey + "), bet " + IntToString(nBetAmount) + " tokens and lost. Game: Slot Machine";
    }

    // Log the result
    LogDebug(sLogMessage, "cas");
}
