-- QBCore Framework Import
local QBCore = exports['qb-core']:GetCoreObject()

-- Client-side code here
print('^2[ICManager]^7 Client-side Lua script loaded')

-- Performance upgrade function
local performanceModIndices = { 11, 12, 13, 15 }
local function PerformanceUpgradeVehicle(vehicle, customWheels)
    customWheels = customWheels or false
    local max
    if DoesEntityExist(vehicle) and IsEntityAVehicle(vehicle) then
        SetVehicleModKit(vehicle, 0)
        for _, modType in ipairs(performanceModIndices) do
            max = GetNumVehicleMods(vehicle, tonumber(modType)) - 1
            SetVehicleMod(vehicle, modType, max, customWheels)
        end
        ToggleVehicleMod(vehicle, 18, true)
        SetVehicleFixed(vehicle)
    end
end

-- Receive vehicle event
RegisterNetEvent('icmanager:client:getvehicle', function(model, renk1, renk2, fullmod, plate)
    local ped = PlayerPedId()
    local coords = GetEntityCoords(ped)
    
    QBCore.Functions.SpawnVehicle(model, function(vehicle)
        -- Set plate
        SetVehicleNumberPlateText(vehicle, plate)
        
        -- Set primary color
        local renkler1 = { renk1:match("(%d+) (%d+) (%d+)") }
        local renk1_r = tonumber(renkler1[1]) or 0
        local renk1_g = tonumber(renkler1[2]) or 0
        local renk1_b = tonumber(renkler1[3]) or 0
        SetVehicleCustomPrimaryColour(vehicle, renk1_r, renk1_g, renk1_b)
        
        -- Set secondary color
        local renkler2 = { renk2:match("(%d+) (%d+) (%d+)") }
        local renk2_r = tonumber(renkler2[1]) or 0
        local renk2_g = tonumber(renkler2[2]) or 0
        local renk2_b = tonumber(renkler2[3]) or 0
        SetVehicleCustomSecondaryColour(vehicle, renk2_r, renk2_g, renk2_b)
        
        -- Warp player into vehicle
        TaskWarpPedIntoVehicle(ped, vehicle, -1)
        
        -- Give vehicle keys
        TriggerEvent("vehiclekeys:client:SetOwner", QBCore.Functions.GetPlate(vehicle))
        
        -- Apply full mod if requested
        Wait(100)
        if fullmod then
            PerformanceUpgradeVehicle(vehicle, true)
        end
        
        -- Notify player
        QBCore.Functions.Notify('Vehicle received!', 'success')
    end, coords, true)
end)
