засунь всё внутрь toggle самое важное снаружи пологаюсь на тебя
repeat task.wait() until game:IsLoaded()

-- Load Rayfield
local Rayfield = loadstring(game:HttpGet("https://sirius.menu/rayfield"))()

-- Create Main Window
local Window = Rayfield:CreateWindow({
Name = "Prime Hub JJI",
LoadingTitle = "Prime Hub",
LoadingSubtitle = "Loading...",
Theme = "Default",
ConfigurationSaving = {
Enabled = true,
FolderName = "Prime Hub",
FileName = "JJI"
},
Discord = {
Enabled = true,
Invite = "primeh",
RememberJoins = true
},
})

-- Main Tab
local MainTab = Window:CreateTab("Main", "activity")

-- Globals
getgenv().AutoFarm = false

local BOSS_SPAWN_NAME = "BossSpawn" -- Убедись, что имя совпадает с твоим
local SAFE_PLACE = Vector3.new(0, 50, 0)
local FLIP_SPAM_DELAY = 0.1 -- Задержка между нажатиями Flip
local REPLAY_WAIT = 26 -- Секунд перед нажатием Replay
local CHEST_NAME_MATCH = "chest" -- Подстрока для идентификации сундуков (без учёта регистра)

-- Флаг для предотвращения повторного нажатия Replay
local hasReplayed = false

-- Safe Platform
local safePlatform = Instance.new("Part")
safePlatform.Name = "SafePlatform"
safePlatform.Anchored = true
safePlatform.Size = Vector3.new(100,1,100)
safePlatform.Position = SAFE_PLACE
safePlatform.Material = Enum.Material.Neon
safePlatform.BrickColor = BrickColor.new("Bright green")
safePlatform.CanCollide = true
safePlatform.Parent = workspace

-- Press GUI Button with VirtualInputManager
local function pressGuiButton(button)
local vim = game:GetService("VirtualInputManager")
local gs = game:GetService("GuiService")


vim:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game) -- Открыть курсор геймпада
task.wait(0.15)
gs.SelectedObject = button
task.wait(0.15)

vim:SendKeyEvent(true, Enum.KeyCode.Return, false, game)    -- Нажать Enter
task.wait(0.1)
vim:SendKeyEvent(false, Enum.KeyCode.Return, false, game)   -- Отпустить Enter
task.wait(0.1)

vim:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game) -- Закрыть курсор геймпада
end

-- Teleport function
local function teleportTo(pos)
local plr = game:GetService("Players").LocalPlayer
if not plr or not plr.Character or not plr.Character:FindFirstChild("HumanoidRootPart") then
print("Teleport Failed: Player or HumanoidRootPart not found.")
return
end
plr.Character.HumanoidRootPart.CFrame = CFrame.new(pos)
Rayfield:Notify({
Title = "Teleport",
Content = "Teleported to "..tostring(pos),
Duration = 2
})
print("Teleported to:", pos)
end

-- Insta Kill Loop
local function instaKillLoop()
local plr = game:GetService("Players").LocalPlayer
while getgenv().AutoFarm do
local char = plr.Character or plr.CharacterAdded:Wait()
for _, obj in ipairs(workspace:GetDescendants()) do
if not getgenv().AutoFarm then break end
if obj:IsA("Humanoid") and obj.Parent ~= char then
if obj.Health > 0 then
obj.Health = 0
Rayfield:Notify({
Title = "InstaKill",
Content = "Killed "..(obj.Parent and obj.Parent.Name or "Unknown"),
Duration = 1
})
print("Killed:", obj.Parent and obj.Parent.Name or "Unknown")
end
end
end
task.wait(0.5)
end
end

-- Flip Loop
local function autoFlip()
local plr = game:GetService("Players").LocalPlayer
local VirtualInputManager = game:GetService("VirtualInputManager")
local GuiService = game:GetService("GuiService")


while getgenv().AutoFarm do
    if plr and plr.PlayerGui:FindFirstChild("Loot") and plr.PlayerGui.Loot.Enabled then
        VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
        print("BackSlash pressed to open GUI cursor.")
        task.wait(0.2)

        local targetElement = plr.PlayerGui.Loot.Frame:FindFirstChild("Flip")
        if targetElement and targetElement:IsA("GuiObject") then
            GuiService.SelectedObject = targetElement
            print("Flip button selected.")

            while plr.PlayerGui.Loot.Enabled and getgenv().AutoFarm do
                VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                task.wait(0.1)
                VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                print("Flip pressed.")
                task.wait(0.1) -- Задержка между нажатиями
            end
        else
            Rayfield:Notify({
                Title = "Flip Not Found",
                Content = "Couldn't find the 'Flip' GuiButton",
                Duration = 2
            })
            print("Flip GuiButton not found in Frame.")
        end

        VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
        task.wait(0.1)
        VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
        print("BackSlash released to close GUI cursor.")
    end
    task.wait(0.1)
end
end

-- Directly Open Chests via ProximityPrompt
local function openChest(chestModel)
local prompt = chestModel:FindFirstChildOfClass("ProximityPrompt")
if not prompt then
Rayfield:Notify({
Title = "Chest",
Content = "No ProximityPrompt found in: "..chestModel.Name,
Duration = 2
})
print("No ProximityPrompt found in:", chestModel.Name)
return
end


local basePart = chestModel:FindFirstChild("HumanoidRootPart") 
    or chestModel:FindFirstChildWhichIsA("BasePart")
if not basePart then
    Rayfield:Notify({
        Title = "Chest",
        Content = "No BasePart found in: "..chestModel.Name,
        Duration = 2
    })
    print("No BasePart found in:", chestModel.Name)
    return
end

-- Teleport above the chest
teleportTo(basePart.Position + Vector3.new(0,3,0))

local holdTime = 0.1
if typeof(prompt.HoldDuration) == "number" and prompt.HoldDuration > 0 then
    holdTime = prompt.HoldDuration + 0.1
end

Rayfield:Notify({
    Title = "Chest",
    Content = "Opening: "..chestModel.Name.." (holding "..holdTime.."s)",
    Duration = 2
})
print("Opening chest:", chestModel.Name, "for", holdTime, "seconds.")

prompt:InputHoldBegin()
task.wait(holdTime)
prompt:InputHoldEnd()
print("Chest opened:", chestModel.Name)
end

-- Scans 'workspace.Objects.Drops' for Chests
local function processAllChests()
local objectsFolder = workspace:FindFirstChild("Objects")
if not objectsFolder then
print("Objects folder not found.")
return
end
local dropsFolder = objectsFolder:FindFirstChild("Drops")
if not dropsFolder or not dropsFolder:IsA("Folder") then
print("Drops folder not found or not a Folder.")
return
end


for _, item in ipairs(dropsFolder:GetDescendants()) do
    if not getgenv().AutoFarm then break end
    if item:IsA("Model") and item.Name:lower():find(CHEST_NAME_MATCH) then
        openChest(item)
    end
end
end

-- Globals
getgenv().AutoFarm = false
getgenv().WebhookEnabled = false

-- Independent Chest Loop
-- Эта петля будет запускаться отдельно и открывать сундуки независимо от Replay
local function chestLoop()
while getgenv().AutoFarm do
processAllChests()
task.wait(2) -- Как часто проверять новые сундуки
end
end

-- Auto Replay Loop (26s Wait, then Replay)
-- Эта петля только ждёт ReadyScreen, ждёт 26 секунд и нажимает Replay
local function autoReplayLoop()
local plr = game:GetService("Players").LocalPlayer
local pg = plr:FindFirstChild("PlayerGui")
if not pg then
print("PlayerGui not found.")
return
end


while getgenv().AutoFarm do
    local rs = pg:FindFirstChild("ReadyScreen")
    if rs and rs:IsA("ScreenGui") and rs.Enabled then
        if not hasReplayed then
            Rayfield:Notify({
                Title = "Replay Timer",
                Content = "ReadyScreen detected. Will press Replay in "..REPLAY_WAIT.."s",
                Duration = 3
            })
            print("ReadyScreen detected. Waiting "..REPLAY_WAIT.." seconds before Replay.")
            task.wait(REPLAY_WAIT)

            if getgenv().AutoFarm and rs.Enabled then
                local frm = rs:FindFirstChild("Frame")
                if frm then
                    local replayBtn = frm:FindFirstChild("Replay")
                    if replayBtn and replayBtn:IsA("GuiButton") then
                        Rayfield:Notify({
                            Title = "Replay",
                            Content = "Pressing Replay now...",
                            Duration = 2
                        })
                        pressGuiButton(replayBtn)
                        print("Replay button pressed.")
                        hasReplayed = true -- Устанавливаем флаг после нажатия Replay
                    else
                        Rayfield:Notify({
                            Title = "Replay Error",
                            Content = "Replay button not found or not a GuiButton",
                            Duration = 2
                        })
                        print("Replay GuiButton not found in Frame.")
                    end
                else
                    print("Frame not found in ReadyScreen.")
                end
            end
        end
    else
        hasReplayed = false -- Сбрасываем флаг, когда ReadyScreen не активен
    end
    task.wait(1)
end
end

-- Boss Teleport
local function teleportToBoss()
local spawns = workspace:FindFirstChild("Objects")
if spawns and spawns:FindFirstChild("Spawns") then
local bossSpawn = spawns.Spawns:FindFirstChild(BOSS_SPAWN_NAME)
if bossSpawn and bossSpawn:IsA("BasePart") then
teleportTo(bossSpawn.Position + Vector3.new(0,5,0))
else
Rayfield:Notify({
Title = "Boss Error",
Content = "Boss spawn not found or not a BasePart. Check BOSS_SPAWN_NAME.",
Duration = 3
})
print("Boss spawn not found or not a BasePart.")
end
else
Rayfield:Notify({
Title = "Boss Error",
Content = "Objects/Spawns folder not found. Check your structure.",
Duration = 3
})
print("Objects/Spawns folder not found.")
end
end

-- Main Automation Function
local function mainAutomation()
Rayfield:Notify({
Title = "AutoFarm",
Content = "Starting up all loops...",
Duration = 2
})
print("Starting AutoFarm automation.")


task.spawn(instaKillLoop)    -- Убивает всё
task.spawn(autoFlip)         -- Непрерывно нажимает Flip
task.spawn(autoReplayLoop)   -- Ждёт 26 секунд после завершения, затем нажимает Replay
task.spawn(chestLoop)        -- Непрерывно сканирует и открывает сундуки

teleportToBoss()

while getgenv().AutoFarm do
    -- Дополнительная логика, если нужно
    task.wait(1)
end
end

-- UI Toggle
MainTab:CreateToggle({
Name = "AutoFarm",
CurrentValue = false,
Flag = "Autofarm",
Callback = function(state)
getgenv().AutoFarm = state
if state then
Rayfield:Notify({
Title = "AutoFarm",
Content = "Enabled",
Duration = 2
})
print("AutoFarm Enabled.")
task.spawn(mainAutomation)
else
Rayfield:Notify({
Title = "AutoFarm",
Content = "Disabled",
Duration = 2
})
print("AutoFarm Disabled.")
end
end
})

local function isValidWebhook(url)
return string.match(url, "^https://discord%.com/api/webhooks/%d+/%S+$") ~= nil
end
MainTab:CreateInput({
Name = "Webhook URL",
CurrentValue = "",
PlaceholderText = "Enter webhook URL here",
RemoveTextAfterFocusLost = false,
Flag = "webhookurl",
Callback = function(Text)
if isValidWebhook(Text) then
getgenv().webhookinput = Text
print("Webhook URL set to:", Text)
Rayfield:Notify({
Title = "Webhook URL",
Content = "Webhook URL has been set successfully.",
Duration = 2
})
else
Rayfield:Notify({
Title = "Invalid URL",
Content = "Please enter a valid Discord Webhook URL.",
Duration = 2
})
print("Invalid Webhook URL entered:", Text)
end
end,
})

local function sendWebhook(content, retries)
retries = retries or 3


if getgenv().webhookinput and getgenv().webhookinput ~= "" then
    for attempt = 1, retries do
        local success, err = pcall(function()
            http_request({
                Url = getgenv().webhookinput,
                Method = "POST",
                Headers = {
                    ["Content-Type"] = "application/json"
                },
                Body = game:GetService("HttpService"):JSONEncode({
                    content = content
                })
            })
        end)
        if success then
            print("Webhook sent successfully on attempt " .. attempt)
            Rayfield:Notify({
                Title = "Webhook Sent",
                Content = "Webhook was sent successfully.",
                Duration = 2
            })
            return
        else
            print("Attempt " .. attempt .. " failed: " .. tostring(err))
            wait(1) -- Wait before retrying
        end
    end
    print("All attempts to send webhook failed.")
    Rayfield:Notify({
        Title = "Webhook Failed",
        Content = "Failed to send webhook after multiple attempts.",
        Duration = 2
    })
else
    print("No webhook URL set or it's empty.")
    Rayfield:Notify({
        Title = "Webhook URL Missing",
        Content = "Please set a valid webhook URL before testing.",
        Duration = 2
    })
end
end

-- Button to test the webhook
MainTab:CreateButton({
Name = "Test Webhook",
Callback = function()
sendWebhook("🔔 Test Webhook: Mix here!")
end
})

MainTab:CreateToggle({
Name = "Send Webhook when finished",
CurrentValue = false,
Flag = "sendwebhook",
Callback = function(Value)


    -- Чтобы логика работала только когда Toggle включён
    if not Value then
        print("Send Webhook when finished: OFF. Сбрасываем логику.")
        return
    end

    local Players = game:GetService("Players")
    local LocalPlayer = Players.LocalPlayer
    local ReadyScreen = LocalPlayer:WaitForChild("PlayerGui"):WaitForChild("ReadyScreen")
    
    -- Убедимся, что существуют объекты GUI Loot, Cards и Replay:
    local LootGui = LocalPlayer.PlayerGui:FindFirstChild("Loot")
    if not LootGui or not LootGui:FindFirstChild("Frame") or not LootGui.Frame:FindFirstChild("Cards") then
        print("Loot GUI or Cards not found! Проверьте правильность имен.")
        return
    end
    local Cards = LootGui.Frame.Cards

    -- Таблица для хранения предыдущего текста
    local previousTexts = {}
    local rewardsCount = {}

    -- Функция для обработки изменений текста
    local function checkAndLogChanges()
        for _, lootCard in ipairs(Cards:GetChildren()) do
            if lootCard:IsA("Frame") and lootCard:FindFirstChild("Back") and lootCard.Back:FindFirstChild("Reward") then
                local rewardLabel = lootCard.Back.Reward
                if rewardLabel:IsA("TextLabel") then
                    local currentText = rewardLabel.Text
                    local previousText = previousTexts[lootCard] -- Получаем предыдущий текст для этой карточки

                    if currentText ~= previousText then
                        previousTexts[lootCard] = currentText
                        if currentText and currentText ~= "" then
                            rewardsCount[currentText] = (rewardsCount[currentText] or 0) + 1
                        end
                    end
                end
            end
        end
    end

    -- Функция для подготовки списка наград
    local function generateRewardList()
        local rewardStrings = {}
        for text, count in pairs(rewardsCount) do
            if count > 1 then
                table.insert(rewardStrings, text .. " х" .. count)
            else
                table.insert(rewardStrings, text)
            end
        end
        return rewardStrings
    end

    -- Функция для отправки EMBED вебхука (Discord-стиль)
    local function sendWebhookEmbed(username, takentime, rewardStrings)
        if not getgenv().webhookinput or getgenv().webhookinput == "" then
            print("No valid webhook URL.")
            return
        end

        local success, err = pcall(function()
            http_request({
                Url = getgenv().webhookinput,
                Method = "POST",
                Headers = {
                    ["Content-Type"] = "application/json"
                },
                Body = game:GetService("HttpService"):JSONEncode({
                    embeds = {
                        {
                            title = "PrimeHub - Webhook",
                            color = 3447003,
                            timestamp = os.date("!%Y-%m-%dT%H:%M:%SZ"),
                            thumbnail = {
                                url = "https://c.tenor.com/Bqix4zMtV_YAAAAd/tenor.gif"
                            },
                            image = {
                                url = "https://i.gifer.com/Dv9E.gif"
                            },
                            fields = {
                                {
                                    name = "📦 Username",
                                    value = "```" .. username .. "```",
                                    inline = true
                                },
                                {
                                    name = "⏱ Time",
                                    value = "```" .. takentime .. "```",
                                    inline = true
                                },
                                {
                                    name = "🎁 Rewards",
                                    value = "```" .. table.concat(rewardStrings, "\n") .. "```",
                                    inline = false
                                }
                            }
                        }
                    }
                })
            })
        end)
        if not success then
            print("Failed to send webhook: " .. tostring(err))
        else
            print("Webhook sent successfully with EMBED!")
        end
    end

    -- Запускаем корутину, которая каждые 1с проверяет изменения наград
    task.spawn(function()
        while Value do
            checkAndLogChanges()
            task.wait(1)
        end
    end)

    -- Подключаемся к кнопке Replay
    local replayButton = ReadyScreen:FindFirstChild("Frame") and ReadyScreen.Frame:FindFirstChild("Replay")
    if replayButton and replayButton:IsA("ImageButton") then
        local con
        con = replayButton.MouseButton1Click:Connect(function()
            if not Value then
                -- Если Toggle уже отключили, выходим
                con:Disconnect()
                return
            end

            local username = LocalPlayer.Name
            local takentime = os.date("%H:%M:%S")
            local rewardStrings = generateRewardList()

            if #rewardStrings == 0 then
                print("No rewards collected. Possibly no new flips or no items found.")
            else
                print("Summary on Replay click: " .. table.concat(rewardStrings, ", "))
                sendWebhookEmbed(username, takentime, rewardStrings)
            end

            -- Можно очистить rewardsCount, если хотите заново считать после Replay
            rewardsCount = {}
            previousTexts = {}
        end)
    else
        print("Replay button not found in ReadyScreen!")
    end

    print("Send Webhook when finished: ON. Начинаем отслеживание наград.")
end,
})

-- Load Configuration
Rayfield:LoadConfiguration()