#include "inc_loot"

void main()
{
    object oContainer = OBJECT_SELF;
    object oOpener = GetLastOpenedBy();

    // Check if the player has I_CAS_CASINOHANDLE in their inventory
    object oHandle = GetItemPossessedBy(oOpener, "I_CAS_CASINOHANDLE");
    if (!GetIsObjectValid(oHandle))
    {
        SendMessageToPC(oOpener, "You need a casino handle to loot this area.");
        return;
    }

    // Check for specific chest loot variables on the casino handle
    int i;
    for (i = 1; i <= 7; i++) // Assuming there are 7 loot chest types
    {
        string sVarName = "I_CHEST_CHRISTENHOLMLOOT" + IntToString(i);
        if (GetLocalInt(oContainer, sVarName) && GetLocalInt(oHandle, sVarName))
        {
            SendMessageToPC(oOpener, "This chest has already been looted.");
            return; // This particular chest has been looted
        }
    }

    // Set the looted variable on both the chest and the casino handle
    string sLootedVar = "I_CHEST_CHRISTENHOLMLOOT" + IntToString(GetLocalInt(oContainer, "LOOT_ID"));
    SetLocalInt(oContainer, sLootedVar, 1);
    SetLocalInt(oHandle, sLootedVar, 1);

    // Move Silent skill check and breaking stealth, invisibility, and greater sanctuary
    int nMoveSilent = GetSkillRank(SKILL_MOVE_SILENTLY, oOpener);
    int nChanceToBreakStealth;

    if (nMoveSilent < 40)
    {
        nChanceToBreakStealth = 100;
    }
    else if (nMoveSilent <= 50)
    {
        nChanceToBreakStealth = 80;
    }
    else if (nMoveSilent <= 60)
    {
        nChanceToBreakStealth = 70;
    }
    else if (nMoveSilent <= 70)
    {
        nChanceToBreakStealth = 60;
    }
    else if (nMoveSilent <= 80)
    {
        nChanceToBreakStealth = 50;
    }
    else if (nMoveSilent <= 90)
    {
        nChanceToBreakStealth = 40;
    }
    else
    {
        nChanceToBreakStealth = 10;
    }

    if (Random(100) < nChanceToBreakStealth)
    {
        // Breaking stealth, invisibility, and greater sanctuary
        ActionDoCommand(SetCommandable(TRUE, oOpener));
        ApplyEffectToObject(DURATION_TYPE_INSTANT, EffectHeal(0), oOpener);
        ActionDoCommand(SetCommandable(FALSE, oOpener));
    }

    // Generate gold with a 33% chance
    if (Random(100) < 33)
    {
        int nGoldAmount = Random(7001) + 5000; // Gold amount between 5000 and 12000
        LOOT_AddGold(oContainer, nGoldAmount);
    }

    // Generate at least one item from the loot table
    LOOT_GenerateFromTable(521, oContainer);

    // Additional items based on Search skill
    int nSearchSkill = GetSkillRank(SKILL_SEARCH, oOpener);
    if (nSearchSkill >= 20)
    {
        int nExtraItems = (nSearchSkill - 20) / 20;
        for (i = 0; i <= nExtraItems; i++)
        {
            LOOT_GenerateFromTable(521, oContainer);
        }
    }
}


