if AK4Y.Framework == "esx" then
    ESX = nil
    TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
elseif AK4Y.Framework == "newEsx" then 
    ESX = exports["es_extended"]:getSharedObject()
end


ESX.RegisterServerCallback('ak4y-donateSystem:getPlayerDetails', function(source, cb)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local charInfo = GetPlayerName(_source)
    local identifier = GetPlayerIdentifiers(_source)[1]
    local steamid = tonumber(identifier:gsub("steam:",""), 16)
    local callbackData = {}
    if AK4Y.Mysql == "oxmysql" then 
        local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
        if result[1] == nil then 
            callbackData = {
                playerData = {
                    ["credit"] = 0,
                },
                charInfo = charInfo,
                apiKey = steamApiKey,
                steamid = steamid,
            }
        else
            callbackData = {
                playerData = result[1], 
                charInfo = charInfo,
                apiKey = steamApiKey,
                steamid = steamid,
            }
        end
        cb(callbackData)
    elseif AK4Y.Mysql == "mysql-async" then
        MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
            ["@citizenid"] = citizenId
        }, function (result)
            if result[1] == nil then 
                callbackData = {
                    playerData = {
                        ["credit"] = 0,
                    },
                    charInfo = charInfo,
                    apiKey = steamApiKey,
                    steamid = steamid,
                }
            else
                callbackData = {
                    playerData = result[1], 
                    charInfo = charInfo,
                    apiKey = steamApiKey,
                    steamid = steamid,
                }
            end
            cb(callbackData)
        end) 
    end
end)


function addCredit(player, creditCount)

    local xPlayer = player
    if xPlayer then 
        local citizenId = xPlayer.identifier
        local deger = tonumber(creditCount)
        local result = ExecuteSql("SELECT * FROM ak4y_donatesystem WHERE citizenid = '"..citizenId.."'")
        if result[1] ~= nil then 
            ExecuteSql("UPDATE ak4y_donatesystem SET credit = credit + '"..deger.."' WHERE citizenid = '"..citizenId.."'")
            return true
        else
            ExecuteSql("INSERT INTO ak4y_donatesystem (citizenid, credit) VALUES ('"..citizenId.."', '"..deger.."')")
            return true
        end
    else
        return false
    end 
end

function removeCredit(player, creditCount)
    local xPlayer = player
    if xPlayer then 
        local citizenId = xPlayer.identifier
        local deger = tonumber(creditCount)
        local result = ExecuteSql("SELECT * FROM ak4y_donatesystem WHERE citizenid = '"..citizenId.."'")
        if result[1] ~= nil then 
            ExecuteSql("UPDATE ak4y_donatesystem SET credit = credit - '"..deger.."' WHERE citizenid = '"..citizenId.."'")
            return true
        else
            return true
        end
    else
        return false
    end 
end


ESX.RegisterServerCallback('ak4y-donateSystem:getItem', function(source, cb, veri)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    for k, v in pairs(AK4Y.Items) do
        if v.id == veri.itemInfo.id then 
            data = v
            break
        end
    end
    if data then
        local costCredit = tonumber(data.costCredit)
        local rewardItem = data.itemName
        local rewardItemCount = data.itemCount
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                    xPlayer.addInventoryItem(rewardItem, rewardItemCount)
                    SendToDiscord("CitizenID: ``"..citizenId.."``\nItem: ``"..rewardItem.."``\nGot item!")
                    cb(true)
                else
                    cb(false)
                end
            else
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then 
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                        xPlayer.addInventoryItem(rewardItem, rewardItemCount)
                        SendToDiscord("CitizenID: ``"..citizenId.."``\nItem: ``"..rewardItem.."``\nGot item!")
                        cb(true)
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            end) 
        end
    else
        cb(false)
    end
end)


ESX.RegisterServerCallback('ak4y-donateSystem:sendInput', function(source, cb, data)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local inputData = data.input
    if AK4Y.Mysql == "oxmysql" then
        local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem_codes WHERE code = ?', { inputData })
        if result[1] ~= nil then
            MySQL.query('DELETE FROM ak4y_donatesystem_codes WHERE code = ?', { inputData })
            local result2 = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result2[1] ~= nil then 
                MySQL.update('UPDATE ak4y_donatesystem SET credit = credit + '..result[1].credit..' WHERE citizenid = ?', { citizenId })
            else
                MySQL.insert('INSERT INTO ak4y_donatesystem (citizenid, credit) VALUES (?, ?)', {
                    citizenId,
                    result[1].credit,
                })
            end
            SendToDiscord("CitizenID: ``"..citizenId.."``\nCredit: ``"..result[1].credit.."\nCode: ``"..inputData.."``\nUsed code!")
            cb(result[1].credit)
        else
            cb(false)
        end
    elseif AK4Y.Mysql == "mysql-async" then 
        MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem_codes WHERE code = @code", {
            ["@code"] = inputData
        }, function (result)
            if result[1] ~= nil then 
                MySQL.Async.execute('DELETE FROM ak4y_donatesystem_codes WHERE code = @code', {['@code'] = inputData})
                MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                    ["@citizenid"] = citizenId
                }, function (result2)
                    if result2[1] ~= nil then 
                        MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit + @credit WHERE citizenid = @citizenid", {
                            ['@citizenid'] = citizenId,
                            ['@credit'] = result[1].credit
                        })
                    else
                        MySQL.Async.execute('INSERT INTO ak4y_donatesystem (citizenid, credit) VALUES (@citizenid, @credit)', {
                            ["@citizenid"] = citizenId,
                            ["@credit"] = result[1].credit,
                        })
                    end
                    SendToDiscord("CitizenID: ``"..citizenId.."``\nCredit: ``"..result[1].credit.."\nCode: ``"..inputData.."``\nUsed code!")
                    cb(result[1].credit)
                end) 
            else
                cb(false)
            end
        end) 
    end
end)

ESX.RegisterServerCallback('ak4y-donateSystem:getVehicle', function(source, cb, veri, VehData)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    local data2 = veri
    if data2.itemInfo.vehType == "car" then
        for k, v in pairs(AK4Y.Vehicles) do
            if v.id == veri.itemInfo.id then 
                data = v
                break
            end
        end
    elseif data2.itemInfo.vehType == "air" then
        for k, v in pairs(AK4Y.Helicopters) do
            if v.id == veri.itemInfo.id then 
                data = v
                data2.itemInfo.vehType = "car"
                break
            end
        end
    end
    if data then
        local vehicle = data.spawnName
        local plate = GeneratePlate()
        local costCredit = tonumber(data.costCredit)
        local plateCheck = false
        if data2.extra ~= "undefined" then 
            plateCheck = true
            plate = data2.extra:upper()
            costCredit = costCredit + AK4Y.CustomPlatePriceOnBuyVehicle
        end

        local vehicleData = {}
        vehicleData.model = GetHashKey(vehicle)
        vehicleData.plate = plate
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    if plateCheck then 
                        local resultPlate = MySQL.query.await('SELECT * FROM owned_vehicles WHERE plate = ?', { plate })
                        if resultPlate[1] == nil then 
                            MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                            
                            ExecuteSql("INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES ('"..citizenId.."', '"..plate.."', '"..json.encode(vehicleData).."', '"..data2.itemInfo.vehType.."', 0)")

                            -- MySQL.insert('INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES (?, ?, ?, ?, ?)', {
                            --     citizenId,
                            --     plate,
                            --     json.encode(vehicleData),
                            --     data2.itemInfo.vehType,
                            --     1
                            -- })
                            SendToDiscord("CitizenID: ``"..citizenId.."``\nVehicle: ``"..vehicle.."``\nPlate: ``"..plate.."``\nPurchased vehicle!")
                            cb(true)
                        else
                            print("4")
                            cb(false)
                        end
                    else
                        MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                        ExecuteSql("INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES ('"..citizenId.."', '"..plate.."', '"..json.encode(vehicleData).."', '"..data2.itemInfo.vehType.."', 0)")

                        -- MySQL.insert('INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES (?, ?, ?, ?, ?)', {
                        --     citizenId,
                        --     plate,
                        --     json.encode(vehicleData),
                        --     data2.itemInfo.vehType,
                        --     1
                        -- })
                        SendToDiscord("CitizenID: ``"..citizenId.."``\nVehicle: ``"..vehicle.."``\nPlate: ``"..plate.."``\nPurchased vehicle!")
                        cb(true)
                    end
                else
                    cb(false)
                end
            else
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        if plateCheck then 
                            MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE plate = @plate', {
                                ["@plate"] = plate
                            }, function (resultPlate)
                                if resultPlate[1] == nil then 
                                    MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                                    ExecuteSql("INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES ('"..citizenId.."', '"..plate.."', '"..json.encode(vehicleData).."', '"..data2.itemInfo.vehType.."', 0)")

                                    -- MySQL.Async.execute('INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES (@owner, @plate, @vehicle, @type, @stored)', {
                                    --     ["@owner"] = citizenId,
                                    --     ["@plate"] = plate,
                                    --     ["@vehicle"] = json.encode(vehicleData),
                                    --     ["@type"] = data2.itemInfo.vehType,
                                    --     ["@stored"] = 1
                                    -- })
                                    SendToDiscord("CitizenID: ``"..citizenId.."``\nVehicle: ``"..vehicle.."``\nPlate: ``"..plate.."``\nPurchased vehicle!")
                                    cb(true)
                                else
                                    cb(false)
                                end
                            end) 
                        else
                            MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                            ExecuteSql("INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES ('"..citizenId.."', '"..plate.."', '"..json.encode(vehicleData).."', '"..data2.itemInfo.vehType.."', 0)")

                            -- MySQL.Async.execute('INSERT INTO owned_vehicles (owner, plate, vehicle, type, stored) VALUES (@owner, @plate, @vehicle, @type, @stored)', {
                            --     ["@owner"] = citizenId,
                            --     ["@plate"] = plate,
                            --     ["@vehicle"] = json.encode(vehicleData),
                            --     ["@type"] = data2.itemInfo.vehType,
                            --     ["@stored"] = 1
                            -- })
                            SendToDiscord("CitizenID: ``"..citizenId.."``\nVehicle: ``"..vehicle.."``\nPlate: ``"..plate.."``\nPurchased vehicle!")
                            cb(true)
                        end
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            end) 
        end
    else
        cb(false)
    end
end)

ESX.RegisterServerCallback('ak4y-donateSystem:getWeapon', function(source, cb, veri)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    for k, v in pairs(AK4Y.Weapons) do
        if v.id == veri.itemInfo.id then 
            data = v
            break
        end
    end
    if data then
        local costCredit = tonumber(data.costCredit)
        local rewardItem = data.weaponName
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                    if AK4Y.WeaponType == "item" then 
                        xPlayer.addInventoryItem(rewardItem, 1)
                    elseif AK4Y.WeaponType == "weapon" then 
                        xPlayer.addWeapon(rewardItem, 1)
                    end
                    SendToDiscord("CitizenID: ``"..citizenId.."``\nItem: ``"..rewardItem.."``\nGot item!")
                    cb(true)
                else
                    cb(false)
                end
            else
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then 
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                        if AK4Y.WeaponType == "item" then 
                            xPlayer.addInventoryItem(rewardItem, 1)
                        elseif AK4Y.WeaponType == "weapon" then 
                            xPlayer.addWeapon(rewardItem, 1)
                        end
                        SendToDiscord("CitizenID: ``"..citizenId.."``\nItem: ``"..rewardItem.."``\nGot item!")
                        cb(true)
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            end) 
        end
    else
        cb(false)
    end
end)

ESX.RegisterServerCallback('ak4y-donateSystem:getMoney', function(source, cb, veri)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    for k, v in pairs(AK4Y.Money) do
        if v.id == veri.itemInfo.id then 
            data = v
            break
        end
    end
    if data then 
        local costCredit = tonumber(data.costCredit)
        local rewardMoney = data.inGameMoney
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                    xPlayer.addMoney(rewardMoney)
                    SendToDiscord("CitizenID: ``"..citizenId.."``\nMoney:``"..rewardMoney.."``\nGot money!")
                    cb(true)
                else
                    cb(false)
                end
            else
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then 
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                        xPlayer.addMoney(rewardMoney)
                        SendToDiscord("CitizenID: ``"..citizenId.."``\nMoney:``"..rewardMoney.."``\nGot money!")
                        cb(true)
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            end) 
        end
    else
        cb(false)
    end
end)

ESX.RegisterServerCallback('ak4y-donateSystem:getCustomPlate', function(source, cb, veri, plate)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    for k, v in pairs(AK4Y.Customize) do
        if v.id == veri.itemInfo.id then 
            data = v
            break
        end
    end
    if data then 
        local costCredit = tonumber(data.costCredit)
        local newPlate = veri.input:upper()
        local oldPlate = string.gsub(plate, "%s+", "")
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    print("1")
                    local resultPlate = MySQL.query.await('SELECT * FROM owned_vehicles WHERE plate = ?', { newPlate })
                    if resultPlate[1] == nil then
                        print("2")
                        local lastCheckPlate = MySQL.query.await('SELECT * FROM owned_vehicles WHERE plate = ?', { oldPlate })
                        if lastCheckPlate[1] == nil then 
                            print("3")
                            cb(false)
                        else
                            print("4")
                            if lastCheckPlate[1].owner == citizenId then 
                                MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                                local jsonData = json.decode(lastCheckPlate[1].vehicle)
                                if jsonData.plate ~= nil then 
                                    jsonData.plate = newPlate
                                    local mods = json.encode(jsonData)
                                    MySQL.update('UPDATE owned_vehicles SET plate = ?, vehicle = ? WHERE plate = ?', { newPlate, mods, oldPlate })
                                else
                                    MySQL.update('UPDATE owned_vehicles SET plate = ? WHERE plate = ?', { newPlate, oldPlate })
                                end
                                SendToDiscord("CitizenID: ``"..citizenId.."``\nOld Plate: ``"..oldPlate.."``\nNew Plate: ``"..newPlate.."``\nVehicle plate changed!")
                                cb(true)
                                print("9")
                            else
                                print("8")
                                cb(false)
                            end
                        end
                    else
                        print("5")
                        cb(false)
                    end
                else
                    print("6")
                    cb(false)
                end
            else
                print("7")
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        MySQL.Async.fetchAll("SELECT * FROM owned_vehicles WHERE plate = @plate", {
                            ["@plate"] = newPlate
                        }, function (resultPlate)
                            if resultPlate[1] == nil then
                                MySQL.Async.fetchAll("SELECT * FROM owned_vehicles WHERE plate = @plate", {
                                    ["@plate"] = oldPlate
                                }, function (lastCheckPlate)
                                    if lastCheckPlate[1] == nil then 
                                        cb(false)
                                    else
                                        if lastCheckPlate[1].owner == citizenId then 
                                            MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                                            local jsonData = json.decode(lastCheckPlate[1].mods)
                                            if jsonData.plate ~= nil then 
                                                jsonData.plate = newPlate
                                                local mods = json.encode(jsonData)
                                                MySQL.Async.execute("UPDATE owned_vehicles SET plate = @plate, vehicle = @mods WHERE plate = @oldPlate", {
                                                    ["@oldPlate"] = oldPlate,
                                                    ["@plate"] = newPlate,
                                                    ["@mods"] = mods,
                                                })              
                                            else
                                                MySQL.Async.execute("UPDATE owned_vehicles SET plate = @plate WHERE plate = @oldPlate", {
                                                    ["@oldPlate"] = oldPlate,
                                                    ["@plate"] = newPlate,
                                                })  
                                            end
                                            SendToDiscord("CitizenID: ``"..citizenId.."``\nOld Plate: ``"..oldPlate.."``\nNew Plate: ``"..newPlate.."``\nVehicle plate changed!")
                                            cb(true)
                                        else
                                            cb(false)
                                        end
                                    end
                                end)
                            else
                                cb(false)
                            end
                        end) 
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            end) 
        end
    else
        cb(false)
    end
end)

ESX.RegisterServerCallback('ak4y-donateSystem:getPrivNumber', function(source, cb, veri)
    local _source = source
    local xPlayer = ESX.GetPlayerFromId(_source)
    local citizenId = xPlayer.identifier
    local data = nil
    for k, v in pairs(AK4Y.Customize) do
        if v.id == veri.itemInfo.id then 
            data = v
            break
        end
    end
    if data then
        local costCredit = tonumber(data.costCredit)
        local newNumber = veri.input
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem WHERE citizenid = ?', { citizenId })
            if result[1] ~= nil then 
                if result[1].credit >= costCredit then
                    local resultData = MySQL.query.await('SELECT * FROM users WHERE identifier = ?', { citizenId })
                    if resultData[1] ~= nil then 
                        if AK4Y.Phone == "qb-phone" then 
                            local query = '%' .. newNumber .. '%'
                            local checkPhone = MySQL.prepare.await('SELECT COUNT(*) as count FROM players WHERE charinfo LIKE ?', { query })
                            if checkPhone == 0 then
                                local charInfo = json.decode(resultData[1].charinfo)
                                if charInfo.phone then 
                                    MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                                    charInfo.phone = newNumber
                                    cb(true)
                                    DropPayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                    SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                    Wait(5000)
                                    local newInfo = json.encode(charInfo)
                                    MySQL.update('UPDATE users SET charinfo = ? WHERE identifier = ?', { newInfo, citizenId })
                                else
                                    cb(false)
                                end
                            else
                                cb(false)
                            end
                        elseif AK4Y.Phone == "gcphone" then
                            local resultPhone = MySQL.query.await('SELECT * FROM users WHERE phone_number = ?', { newNumber })
                            if resultPhone[1] == nil then
                                MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                                cb(true)
                                DropPlayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                Wait(5000)
                                MySQL.update('UPDATE users SET phone_number = ? WHERE identifier = ?', { newNumber, citizenId })
                            else
                                cb(false)                                    
                            end
                        elseif AK4Y.Phone == "gksphone" then
                            local resultPhone = MySQL.query.await('SELECT * FROM users WHERE phone_number = ?', { newNumber })
                            if resultPhone[1] == nil then
                                MySQL.update('UPDATE ak4y_donatesystem SET credit = credit - ? WHERE citizenid = ?', { costCredit, citizenId })
                                cb(true)
                                DropPlayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                Wait(5000)
                                MySQL.update('UPDATE users SET phone_number = ? WHERE identifier = ?', { newNumber, citizenId })
                                local result = ExecuteSql("SELECT * FROM gksphone_settings WHERE citizenid = '"..citizenId.."'")
                                if result then 
                                    ExecuteSql("UPDATE gksphone_settings SET phone_number = '"..newNumber.."' WHERE citizenid = '"..citizenId.."'")
                                end
                            else
                                cb(false)                                    
                            end
                        end
                    else
                        cb(false)
                    end
                else
                    cb(false)
                end
            else
                cb(false)
            end
        elseif AK4Y.Mysql == "mysql-async" then 
            MySQL.Async.fetchAll("SELECT * FROM ak4y_donatesystem WHERE citizenid = @citizenid", {
                ["@citizenid"] = citizenId
            }, function (result)
                if result[1] ~= nil then 
                    if result[1].credit >= costCredit then
                        MySQL.Async.fetchAll("SELECT * FROM users WHERE identifier = @citizenid", {
                            ["@citizenid"] = citizenId
                        }, function (resultData)
                            if resultData[1] ~= nil then 
                                if AK4Y.Phone == "qb-phone" then 
                                    local query = '%' .. newNumber .. '%'
                                    MySQL.Async.fetchAll("SELECT COUNT(*) as count FROM players WHERE charinfo LIKE @number", {
                                        ["@number"] = query
                                    }, function (checkPhone)
                                        if checkPhone[1].count == 0 then 
                                            local charInfo = json.decode(resultData[1].charinfo)
                                            if charInfo.phone then 
                                                charInfo.phone = newNumber
                                                MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                                                cb(true)
                                                DropPlayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                                SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                                Wait(5000)
                                                local newInfo = json.encode(charInfo)
                                                MySQL.Async.execute("UPDATE users SET charinfo = @charinfo WHERE identifier = @citizenid", {
                                                    ["@citizenid"] = citizenId,
                                                    ["@charinfo"] = newInfo,
                                                })  
                                            else
                                                cb(false)
                                            end
                                        else
                                            cb(false)
                                        end
                                    end)
                                elseif AK4Y.Phone == "gcphone" then 
                                    MySQL.Async.fetchAll("SELECT * FROM users WHERE phone_number = @number", {
                                        ["@number"] = newNumber
                                    }, function (resultPhone)
                                        if resultPhone[1] == nil then
                                            MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                                            cb(true)
                                            DropPlayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                            SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                            Wait(5000)
                                            MySQL.Async.execute("UPDATE users SET phone_number = @phone_number WHERE identifier = @citizenid", {
                                                ["@citizenid"] = citizenId,
                                                ["@phone_number"] = newNumber,
                                            })  
                                        else
                                            cb(false)                                    
                                        end
                                    end)
                                elseif AK4Y.Phone == "gksphone" then 
                                    MySQL.Async.fetchAll("SELECT * FROM users WHERE phone_number = @number", {
                                        ["@number"] = newNumber
                                    }, function (resultPhone)
                                        if resultPhone[1] == nil then
                                            MySQL.Async.execute("UPDATE ak4y_donatesystem SET credit = credit - "..costCredit.." WHERE citizenid = @citizenid", {["@citizenid"] = citizenId})
                                            cb(true)
                                            DropPlayer(_source, "[ak4y-donateSystem] Phone number changed!")
                                            SendToDiscord("CitizenID: ``"..citizenId.."``\nNew Number: ``"..newNumber.."``\nPhone number changed!")
                                            Wait(5000)
                                            MySQL.Async.execute("UPDATE users SET phone_number = @phone_number WHERE identifier = @citizenid", {
                                                ["@citizenid"] = citizenId,
                                                ["@phone_number"] = newNumber,
                                            })  
                                            local result = ExecuteSql("SELECT * FROM gksphone_settings WHERE citizenid = '"..citizenId.."'")
                                            if result then 
                                                ExecuteSql("UPDATE gksphone_settings SET phone_number = '"..newNumber.."' WHERE citizenid = '"..citizenId.."'")
                                            end
                                        else
                                            cb(false)                                    
                                        end
                                    end)
                                end
                            else
                                cb(false)
                            end
                        end)
                    else
                        cb(false)
                    end
                end
            end)
        end
    else
        cb(false)
    end
end)


RegisterCommand('purchase_donate_credit', function(source, args)
	local src = source
    if src == 0 then
        local dec = json.decode(args[1])
        local tbxid = dec.transid
        local credit = dec.credit
        while inProgress do
            Wait(1000)
        end
        inProgress = true
        if AK4Y.Mysql == "oxmysql" then
            local result = MySQL.query.await('SELECT * FROM ak4y_donatesystem_codes WHERE code = ?', { tbxid })
            if result[1] == nil then
                MySQL.insert('INSERT INTO ak4y_donatesystem_codes (code, credit) VALUES (?, ?)', { tbxid, credit })
                SendToDiscord("Code: ``"..tbxid.."``\nCredit: ``"..credit.."``\nsuccessfuly into your database!")
            end
            inProgress = false  
        elseif AK4Y.Mysql == "mysql-async" then
            MySQL.Async.fetchAll('SELECT * FROM ak4y_donatesystem_codes WHERE code = @code', {['@code'] = tbxid}, function(result)
                if result[1] == nil then
                    MySQL.Async.execute('INSERT INTO ak4y_donatesystem_codes (code, credit) VALUES (@code, @credit)', {
                        ["@code"] = tbxid,
                        ["@credit"] = credit,
                    })
                    SendToDiscord("Code: ``"..tbxid.."``\nCredit: ``"..credit.."``\nsuccessfuly into your database!")
                end
                inProgress = false
            end)  
        end
    end
end)


AddEventHandler('onResourceStart', function(resource)
    if resource == GetCurrentResourceName() then
        if AK4Y.UseTebex then 
            local tebexConvar = GetConvar('sv_tebexSecret', '')
            if tebexConvar == '' or tebexConvar == nil then
                print('^1////////////////////////////////////////////////////////////////////////////////////////////////////////////')
                print('^1//////////////////////////////////////////^Tebex Secret Missing.^1//////////////////////////////////////////')
                print('^1////////////////////////////////////////////////////////////////////////////////////////////////////////////')
                print('ak4y-donateSystem: Tebex Secret Missing please set in server.cfg and try again. Script will not work correctly.')
                shouldStop = true
            end
        end
	end
end)

local DISCORD_NAME = "ak4y-donateSystem"
local DISCORD_IMAGE = "https://i.imgur.com/Q72RWcB.png"
DiscordWebhook = Discord_Webhook
function SendToDiscord(name, message, color)
	if DiscordWebhook == "CHANGE_WEBHOOK" then
	else
		local connect = {
            {
                ["color"] = color,
                ["title"] = "**".. name .."**",
                ["description"] = message,
                ["footer"] = {
                ["text"] = "ak4y development",
                },
            },
	    }
		PerformHttpRequest(DiscordWebhook, function(err, text, headers) end, 'POST', json.encode({username = DISCORD_NAME, embeds = connect, avatarrl = DISCORD_IMAGE}), { ['Content-Type'] = 'application/json' })
	end
end

ESX.RegisterServerCallback('esx_vehicleshop:isPlateTaken', function (source, cb, plate)
	MySQL.Async.fetchAll('SELECT 1 FROM owned_vehicles WHERE plate = @plate', {
		['@plate'] = plate
	}, function (result)
		cb(result[1] ~= nil)
	end)
end)

local NumberCharset = {}
local Charset = {}

for i = 48,  57 do table.insert(NumberCharset, string.char(i)) end

for i = 65,  90 do table.insert(Charset, string.char(i)) end
for i = 97, 122 do table.insert(Charset, string.char(i)) end

function GeneratePlate()
	local generatedPlate
	local doBreak = false

	while true do
		Citizen.Wait(2)
		math.randomseed(GetGameTimer())
		generatedPlate = string.upper(GetRandomLetter(3) .. GetRandomNumber(3))

        if AK4Y.Mysql == "mysql-async" then 
            MySQL.Async.fetchAll('SELECT 1 FROM owned_vehicles WHERE plate = @plate', {
                ['@plate'] = generatedPlate
            }, function (result)
                if result[1] == nil then 
                    doBreak = true
                end
            end)
        elseif AK4Y.Mysql == "oxmysql" then 
            local result = MySQL.query.await('SELECT 1 FROM owned_vehicles WHERE plate = ?', { generatedPlate })
            if result[1] == nil then 
                doBreak = true
            end
        end

		if doBreak then
			break
		end
	end

	return generatedPlate
end

function GetRandomNumber(length)
	Citizen.Wait(1)
	math.randomseed(GetGameTimer())
	if length > 0 then
		return GetRandomNumber(length - 1) .. NumberCharset[math.random(1, #NumberCharset)]
	else
		return ''
	end
end

function GetRandomLetter(length)
	Citizen.Wait(1)
	math.randomseed(GetGameTimer())
	if length > 0 then
		return GetRandomLetter(length - 1) .. Charset[math.random(1, #Charset)]
	else
		return ''
	end
end

function ExecuteSql(query)
    local IsBusy = true
    local result = nil
    if AK4Y.Mysql == "oxmysql" then
        if MySQL == nil then
            exports.oxmysql:execute(query, function(data)
                result = data
                IsBusy = false
            end)
        else
            MySQL.query(query, {}, function(data)
                result = data
                IsBusy = false
            end)
        end
    elseif AK4Y.Mysql == "ghmattimysql" then
        exports.ghmattimysql:execute(query, {}, function(data)
            result = data
            IsBusy = false
        end)
    elseif AK4Y.Mysql == "mysql-async" then   
        MySQL.Async.fetchAll(query, {}, function(data)
            result = data
            IsBusy = false
        end)
    end
    while IsBusy do
        Citizen.Wait(0)
    end
    return result
end