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

local car = nil
local ped = nil
local object = nil
local activeItems = {}
local activeVan = nil
local currentVan = nil

local function ds()
    if car ~= nil then
        DeleteEntity(car)
        exports['qb-target']:RemoveZone(currentVan)
        car = nil
        currentVan = nil
    end
    if ped ~= nil then
        DeleteEntity(ped)
        ped = nil
    end
    if object ~= nil then
        DeleteEntity(object)
        object = nil
    end
    if activeItems ~= nil then
        activeItems = {}
    end
    if activeVan ~= nil then
        activeVan = nil
    end
end

local function spawnTargetMenu(x, y, z, h)
    exports['qb-target']:AddBoxZone(currentVan, GetEntityCoords(ped), 1.5, 1.5  , {
            name = currentVan,
            heading = h,
            minZ = z - 1.0,
            maxZ = z + 1.0,
            debugPoly = false
        },
        {
            options = {
                {
                    num = 1,
                    type = "client",
                    icon = "fas fa-gun",
                    label = Config.Lang.Buy ..
                        " " .. activeItems[1].label .. " | " .. activeItems[1].price .. Config.Lang.Currency,
                    action = function(entity)
                        if IsPedAPlayer(entity) then return false end

                        TriggerServerEvent('_hp_gv:server:_giveItem', 1)
                    end,
                    canInteract = function(entity, distance, data)
                        if IsPedAPlayer(entity) then return false end
                        return true
                    end,
                },
                {
                    num = 2,
                    type = "client",
                    icon = "fas fa-gun",
                    label = Config.Lang.Buy ..
                        " " .. activeItems[2].label .. " | " .. activeItems[2].price .. Config.Lang.Currency,
                    action = function(entity)
                        if IsPedAPlayer(entity) then return false end

                        TriggerServerEvent('_hp_gv:server:_giveItem', 2)
                    end,
                    canInteract = function(entity, distance, data)
                        if IsPedAPlayer(entity) then return false end
                        return true
                    end,
                },
            },
            distance = 3.0
        })
end

local function spawnProp(car)
    local prop = "xm3_prop_xm3_crate_ammo_01a"
    local model = GetHashKey(prop)

    object = CreateObject(model, 0, 0, 0, true, true, true)
    AttachEntityToEntity(object, car, -1, 0, 0.0 - 1.2, 0.0 - 0.2, 0, 0, 0, false, false, false, false, 1, true)
end

local function addNPC(x, y, z)
    local animDict = "amb@world_human_leaning@male@wall@back@hands_together@base"
    local anim = "base"

    local model = GetHashKey(Config.Gunvans.ped)

    RequestModel(model)
    while not HasModelLoaded(model) do
        Wait(15)
    end
    ped = CreatePed(4, model, x, y, z, 0.0, true, true)
    AttachEntityToEntity(ped, car, -1, 0 - 0.7, 0.0 - 3.0, 0.0 + 0.3, 0, 0, 220.0, false, false, false, false, 1, true)

    if not HasAnimDictLoaded(animDict) then
        RequestAnimDict(animDict)
        while not HasAnimDictLoaded(animDict) do
            Wait(100)
        end
    end

    TaskPlayAnim(ped, animDict, anim, 2.0, 2.5, -1, 50, 0, false, false, false)

    SetPedCanBeTargetted(ped, false)
    SetEntityInvincible(ped, true)
    SetEntityAsMissionEntity(ped, true, true)
    SetModelAsNoLongerNeeded(model)
    FreezeEntityPosition(ped, true)

    spawnProp(car)
end

local function addCar(x, y, z, h)
    local vehiclehash = GetHashKey('speedo4')

    RequestModel(vehiclehash)

    Citizen.CreateThread(function()
        local waiting = 0
        while not HasModelLoaded(vehiclehash) do
            waiting = waiting + 100
            Citizen.Wait(100)
        end

        car = CreateVehicle(vehiclehash, x, y, z, h, true, false)
        SetVehicleOnGroundProperly(car)

        SetEntityInvincible(car, true)
        SetVehicleNumberPlateText(car, "GUN00VAN")
        SetVehicleDoorsLocked(car, 2)

        SetVehicleDoorOpen(car, 2, true, true)
        SetVehicleDoorOpen(car, 3, true, true)

        FreezeEntityPosition(car, true)
        SetVehicleUndriveable(car, true)

        SetVehicleMod(car, 5, 1, false)
        SetVehicleMod(car, 48, 24, false)

        addNPC(x, y, z)
        spawnTargetMenu(x, y, z, h)
    end)
end

RegisterNetEvent('_hp_gv:client:_spawnVan')
AddEventHandler('_hp_gv:client:_spawnVan', function(van)
    activeVan = van
    currentVan = "GunVan"..math.random(100000000, 999999999)

    if Config.perVanItems then
        activeItems = Config.Gunvans.vehicles[activeVan].items
    else
        activeItems = Config.VanItems
    end

    addCar(Config.Gunvans.vehicles[van].coords['x'], Config.Gunvans.vehicles[van].coords['y'], Config.Gunvans.vehicles[van].coords['z'], Config.Gunvans.vehicles[van].heading)
end)

RegisterNetEvent('_hp_gv:client:_destroyVan')
AddEventHandler('_hp_gv:client:_destroyVan', function(van)
    ds()
end)

AddEventHandler('onResourceStop', function(resourceName)
    if (GetCurrentResourceName() ~= resourceName) then
        return
    end
    
    ds()
end)