void StartHazard(object oTrap);
void StopHazard(object oTrap);

void StartHazard(object oTrap)
{
    SetLocalInt(oTrap, "bActive", TRUE);
    ExecuteScript("cas_plcvfxobject", oTrap); // Run the hazard script on the placeable
}

void StopHazard(object oTrap)
{
    SetLocalInt(oTrap, "bActive", FALSE);
}

void main()
{
    object oActivator = GetLastUsedBy(); // Default: Used by a switch
    if (!GetIsObjectValid(oActivator))
    {
        oActivator = GetLastSpeaker(); // If triggered by conversation, get the speaking PC
    }

    if (!GetIsObjectValid(oActivator))
    {
        return; // Safety check, should never happen
    }

    object oArea = GetArea(oActivator);
    if (!GetIsObjectValid(oArea))
    {
        SendMessageToPC(oActivator, "Could not determine the area.");
        return;
    }

    object oTrap = GetFirstObjectInArea(oArea);
    object oValidTrap = OBJECT_INVALID;

    // Loop through all placeables in the area
    while (GetIsObjectValid(oTrap))
    {
        if (GetObjectType(oTrap) == OBJECT_TYPE_PLACEABLE && GetTag(oTrap) == "CAS_PLC_VFXTRAP")
        {
            oValidTrap = oTrap;
            break; // Stop once we find the first valid trap
        }

        oTrap = GetNextObjectInArea(oArea);
    }

    if (!GetIsObjectValid(oValidTrap))
    {
        SendMessageToPC(oActivator, "No hazard found in this area.");
        return;
    }

    // Toggle the hazard activation
    int bActive = GetLocalInt(oValidTrap, "bActive");

    if (bActive == FALSE) 
    {
        SendMessageToPC(oActivator, "You activate the hazard!");
        StartHazard(oValidTrap);
    }
    else 
    {
        SendMessageToPC(oActivator, "You deactivate the hazard.");
        StopHazard(oValidTrap);
    }
}
