local CHEST_DATA = {}
local cooldownActive = false
local cooldownTime = Config.OrderCooldown


twitter = {
    ['twittericon'] = '',
    ['name'] = 'Flara Log',
    ['image'] = ''
}

local dropTable = {
    {
        Chance = 50,
        items = {
            {name = "advanced_lockpick", minAmount = 1, maxAmount = 1},
            {name = "ammo-9", minAmount = 20, maxAmount = 50},
            {name = "money", minAmount = 15000, maxAmount = 30000}
        }
    },
    {
        Chance = 50,
        items = {
            {name = "advanced_lockpickk", minAmount = 1, maxAmount = 1},
            {name = "money", minAmount = 15000, maxAmount = 30000},
            {name = "packed-heroin", minAmount = 10, maxAmount = 20},
        }
    },
    {
        Chance = 50,
        items = {
            {name = "advanced_lockpick", minAmount = 1, maxAmount = 1},
            {name = "money", minAmount = 15000, maxAmount = 30000},
            {name = "ziplock-bag", minAmount = 15, maxAmount = 30},
        }
    }
}

local function twitterWood(name, message)
    local data = {
        {
            ["color"] = '15548997', 
            ["title"] = "**" .. name .. "**",
            ["description"] = message,  
            ["footer"] = {
                ["text"] = "Generated by lnd-flare",  
            },
            ["timestamp"] = os.date("!%Y-%m-%dT%H:%M:%S") .. "Z" 
        }
    }
    PerformHttpRequest(twitter['twittericon'], function(err, text, headers) end, 'POST', 
    json.encode({username = twitter['name'], embeds = data, avatar_url = twitter['image']}), 
    {['Content-Type'] = 'application/json'})
end



local function GetPlayerIdentifiers(src)
    local identifiers = {
        discord = nil,
        ip = nil,
        steam = nil,
        license = nil
    }

    local numIdentifiers = GetNumPlayerIdentifiers(src)
    for i = 0, numIdentifiers - 1 do
        local identifier = GetPlayerIdentifier(src, i)
        if identifier ~= nil then
            if string.match(identifier, "discord:") then
                identifiers.discord = string.sub(identifier, 9)
            elseif string.match(identifier, "ip:") then
                identifiers.ip = string.sub(identifier, 4)
            elseif string.match(identifier, "steam:") then
                identifiers.steam = string.sub(identifier, 7)
            elseif string.match(identifier, "license:") then
                identifiers.license = string.sub(identifier, 9)
            end
        end
    end

    identifiers.steam = identifiers.steam or "Unavailable"
    
    return identifiers
end


RegisterNetEvent('lnd-flare:checkPoliceCount')
AddEventHandler('lnd-flare:checkPoliceCount', function(ped)
    local src = source
    local policeCount = 0
    local xPlayers = ESX.GetPlayers()

    for i = 1, #xPlayers, 1 do
        local xPlayer = ESX.GetPlayerFromId(xPlayers[i])
        if xPlayer and xPlayer.job.name == 'police' then
            policeCount = policeCount + 1
        end
    end

    TriggerClientEvent('lnd-flare:receivePoliceCount', src, policeCount)
end)


local function CreateDrop(src)
    local randomNumber = math.random(1, 100)
    local selectedGroup = nil
    
    for _, group in ipairs(dropTable) do            
        if randomNumber <= group.Chance then
            selectedGroup = group
            break
        else
            randomNumber = randomNumber - group.Chance
        end
    end
    
    if selectedGroup then
        local itemsDropped = ""
        for _, items in ipairs(selectedGroup.items) do
            local itemName = items.name
            local minAmount = items.minAmount
            local maxAmount = items.maxAmount
            if exports.ox_inventory:CanCarryItem(src, itemName) then
                local randomAmount = math.random(minAmount, maxAmount)
                exports.ox_inventory:AddItem(src, itemName, randomAmount)
                itemsDropped = itemsDropped .. itemName .. " x" .. randomAmount .. ", "
            end
        end

        TriggerClientEvent('ox_lib:notify', src, {
            description = Config.translation.finish,
            icon = 'fa-solid fa-check',
            iconColor = '#2ECC71',
            iconAnimation = 'fade',
            alignIcon = 'center'
        })
        
        local message = (
        "**Player:** ``%s``\n" ..
        "**Discord:** <@%s>\n" ..
        "**Steam Hex:** `%s`\n" ..
        "**License:** `%s`\n" ..
        "**IP Address:** `%s`\n" ..
        "**Date:** ``%s``\n" ..
        "**Dropped Items:** `%s`\n")
        :format(GetPlayerName(src), discord, steam, license, ip, currentTime, itemsDropped)
    
        twitterWood("FINISH LOG | FLARE", message)
    end
end

local function Stolen(src)
    if CHEST_DATA then
        if src ~= CHEST_DATA.creator then
            TriggerClientEvent('ox_lib:notify', CHEST_DATA.creator, {
                description = Config.translation.stolen,
                icon = 'fa-solid fa-exclamation-triangle',
                iconColor = '#E74C3C',
                duration = 5000,
            })
        end
    else
        print("CHEST_DATA or CHEST_DATA.creator is nil")
    end
end


RegisterNetEvent('lnd-flare:createchest', function()
    local src = source

    if Config.RequiredItemEnabled then
        local item = exports.ox_inventory:Search('count', Config.RequiredItem)
        if item >= Config.RequiredItemQuanity then
            exports.ox_inventory:RemoveItem(src, Config.RequiredItem, Config.RequiredItemQuanity)
        else
            return
        end
    end

    selectedZone = Config.Zones[math.random(#Config.Zones)]

    if selectedZone then
        local randomIndex = math.random(1, #selectedZone.chests)
        local randomChestCoords = selectedZone.chests[randomIndex]

        CHEST_DATA = {
            coords = randomChestCoords,
            selected_Zone = selectedZone,
            creator = src
        }
    end

    TriggerClientEvent('lnd-flare:createblip', src, CHEST_DATA)

    TriggerClientEvent('lnd-flare:createchest', -1, CHEST_DATA)
end)


RegisterNetEvent('lnd-flare:networksync', function(action)

    if not CHEST_DATA then return end


    local src = source
    local identifiers = GetPlayerIdentifiers(src)
    local discord = identifiers.discord or "Unavailable"
    local steam = identifiers.steam or "N/A"
    local license = identifiers.license or "N/A"
    local ip = identifiers.ip or "N/A"

    if action == 'drop' then
        local src = source
        local currentTime = os.date("%Y-%m-%d %H:%M:%S")
        local playerCoords = GetEntityCoords(GetPlayerPed(src))
        
    
        local distance = #(vector3(playerCoords.x, playerCoords.y, playerCoords.z) - vector3(CHEST_DATA.coords.x, CHEST_DATA.coords.y, CHEST_DATA.coords.z))
        
        if distance > 5.0 then
            local message = (
            "**Player:** %s\n" ..
            "**Discord:** <@%s>\n" ..
            "**Steam Hex:** `%s`\n" ..
            "**License:** `%s`\n" ..
            "**IP Address:** `%s`\n" ..
            "**Date:** `%s`\n" ..
            "**Distance from Object:** `%.2f meters`\n" ..
            "**Action:** Player too far from the object.")
            :format(GetPlayerName(src), discord, steam, license, ip, currentTime, distance)
            
            twitterWood("CHEATER LOG", message)
            return
        end
    
        Stolen(src)
        CreateDrop(src)

        CHEST_DATA = {}
        TriggerClientEvent('lnd-flare:networksync', -1, 'drop', CHEST_DATA)
    end
end)

RegisterServerEvent('lnd-flare:server:startCountdown')
AddEventHandler('lnd-flare:server:startCountdown', function()
    local src = source
    local currentTime = os.date("%Y-%m-%d %H:%M:%S")
    
    local identifiers = GetPlayerIdentifiers(src)
    local discord = identifiers.discord or "Unavailable"
    local steam = identifiers.steam or "N/A"
    local license = identifiers.license or "N/A"
    local ip = identifiers.ip or "N/A"

    if cooldownActive then
        TriggerClientEvent('lnd-flare:client:blockTalk', src, true)
        return
    end

    cooldownActive = true
    TriggerClientEvent('lnd-flare:client:blockTalk', src, false)

    local messageStart = (
    "**Player:** ``%s``\n" ..
    "**Discord:** <@%s>\n" ..
    "**Steam Hex:** `%s`\n" ..
    "**License:** `%s`\n" ..
    "**IP Address:** `%s`\n" ..
    "**Date:** ``%s``\n" ..
    "**Action:** Cooldown started.")
    :format(GetPlayerName(src), discord, steam, license, ip, currentTime)

    twitterWood("START LOG | FLARE", messageStart)


    SetTimeout(cooldownTime, function()
        cooldownActive = false
        TriggerClientEvent('lnd-flare:client:blockTalk', -1, false) 

        local messageEnd = (
        "**Date:** ``%s``\n" ..
        "**Action:** Cooldown ended.")
        :format(os.date("%Y-%m-%d %H:%M:%S"))

        twitterWood("COOLDOWN LOG | FLARE", messageEnd)
    end)
end)


ESX.RegisterServerCallback('lnd-flare:server:checkCooldown', function(source, cb)
    cb(cooldownActive) 
end)



local resourceName = 'lnd-flare'
local currentVersion = GetResourceMetadata(resourceName, 'version', 0)

local CheckVersion = function()
    if not currentVersion then
        print("^1["..resourceName.."] Unable to determine current resource version for '" ..resourceName.. "' ^0")
        return
    end
    SetTimeout(1000, function()
        PerformHttpRequest('https://api.github.com/repos/actuallylnd/' ..resourceName.. '/releases/latest', function(status, response)
            if status ~= 200 then return end
            response = json.decode(response)
            local latestVersion = response.tag_name
            if not latestVersion or latestVersion == currentVersion then return end
            if latestVersion ~= currentVersion then
                print('^1['..resourceName..'] ^3An update is now available for ' ..resourceName.. '^0')
                print('^1['..resourceName..'] ^3Current Version: ^1' ..currentVersion.. '^0')
                print('^1['..resourceName..'] ^3Latest Version: ^2' ..latestVersion.. '^0')
                print('^1['..resourceName..'] ^3Download the latest release from https://github.com/actuallylnd/'..resourceName..'/releases^0')
                print('^1['..resourceName..'] ^3For more information about this update visit our Discord^0')
            end
        end, 'GET')
    end)
end

CheckVersion()