# Usage / Integration

## Usage & Integration

This guide covers all events, callbacks, and integration examples available in Force Burglary for developers who want to integrate the system with their own scripts.

### Table of Contents

* Server Events
* Client Events
* Server Callbacks
* Integration Examples
* Custom Framework Integration
* Custom Dispatch Integration

### Server Events

#### force-burglary:server:updateActiveRobberies

Updates the active robberies table when a player starts a new robbery.

**Parameters:**

* `houseData` (table) - The house data from Config.HouseList

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:updateActiveRobberies", houseData)
```

**Description:** Called when a player initiates a burglary. Adds the robbery to the server's active robberies list and syncs it with all clients.

***

#### force-burglary:server:updateTargetOnHouse

Updates whether a house has been lockpicked/entered.

**Parameters:**

* `UID` (number) - Unique identifier for the active robbery
* `lockpicked` (boolean) - Whether the house has been successfully lockpicked

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:updateTargetOnHouse", UID, true)
```

**Description:** Called after successful lockpicking or entry. Updates the robbery state on the server.

***

#### force-burglary:server:removeActiveRobbery

Removes a robbery from the active robberies list.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery to remove

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:removeActiveRobbery", UID)
```

**Description:** Called when a robbery is completed or abandoned. Cleans up the robbery instance.

***

#### force-burglary:server:playerInInterior

Updates whether a player is currently inside an interior.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery
* `inInterior` (boolean) - Whether player is inside

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:playerInInterior", UID, true)
```

**Description:** Tracks player location for proper cleanup and instance management.

***

#### force-burglary:server:updateActiveRobberiesHasLootSpawned

Updates whether loot has been spawned in the interior.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery
* `hasSpawned` (boolean) - Whether loot has spawned

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:updateActiveRobberiesHasLootSpawned", UID, true)
```

**Description:** Prevents duplicate loot spawning and manages loot state.

***

#### force-burglary:server:updateActiveRobberiesHasTenantsLoaded

Updates whether tenant NPCs have been loaded.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery
* `hasLoaded` (boolean) - Whether tenants have been loaded

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:updateActiveRobberiesHasTenantsLoaded", UID, true)
```

**Description:** Manages NPC loading state to prevent duplicates.

***

#### force-burglary:server:updatePedNetIds

Updates the network IDs of spawned tenant NPCs.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery
* `pedNetIds` (table) - Array of network IDs for spawned peds

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:updatePedNetIds", UID, {123, 456, 789})
```

**Description:** Stores ped network IDs for proper cleanup and synchronization.

***

#### force-burglary:server:onAlarmTrigger

Triggers when a house alarm is activated.

**Parameters:**

* `UID` (number) - Unique identifier for the robbery

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:onAlarmTrigger", UID)
```

**Description:** Sends a police dispatch when alarm is triggered.

***

#### force-burglary:server:sendDispatch

Sends a dispatch alert to police.

**Parameters:**

* `data` (table) - Dispatch information including coordinates and type

**Trigger:**

```lua
TriggerServerEvent("force-burglary:server:sendDispatch", {
  coords = vector3(x, y, z),
  type = "burglary"
})
```

**Description:** Manually trigger a police dispatch. Used for alarm systems and NPC alerts.

***

### Client Events

#### force-burglary:client:sendDispatch

Sends a dispatch from the client side.

**Parameters:**

* `data` (table) - The dispatch data

**Trigger:**

```lua
TriggerEvent("force-burglary:client:sendDispatch", data)

-- Or from server:
TriggerClientEvent("force-burglary:client:sendDispatch", source, data)
```

**Example:**

```lua
local dispatchData = {
  coords = GetEntityCoords(PlayerPedId()),
  type = "houseAlarm",
  message = "House alarm triggered"
}
TriggerEvent("force-burglary:client:sendDispatch", dispatchData)
```

***

#### force-burglary:client:removeZoneByName

Removes a specific interaction zone.

**Parameters:**

* `zoneToRemove` (string) - Name of the zone to remove

**Trigger:**

```lua
TriggerEvent("force-burglary:client:removeZoneByName", "loot_point_1")

-- Or from server:
TriggerClientEvent("force-burglary:client:removeZoneByName", source, "loot_point_1")
```

**Description:** Removes an ox\_lib zone. Useful for cleanup or dynamic zone management.

***

#### force-burglary:client:updateActiveRobberies

Updates the client's active robberies list.

**Parameters:**

* `activeRobberies` (table) - Updated active robberies data

**Trigger:**

```lua
-- From server only:
TriggerClientEvent("force-burglary:client:updateActiveRobberies", source, activeRobberies)
```

**Description:** Syncs active robberies from server to client. Automatically called by the server.

***

### Server Callbacks

All callbacks use ox\_lib's callback system. Here's how to register and call them:

#### force-burglary:callback:getCurrentDay

Gets the current day of the week.

**Returns:** `string` - Day name ("monday", "tuesday", etc.)

**Usage:**

```lua
-- Client side:
local currentDay = lib.callback.await("force-burglary:callback:getCurrentDay", false)
print("Today is: " .. currentDay)
```

***

#### force-burglary:callback:fetchPlayerHouses

Fetches all available houses for the player.

**Returns:** `table` - Array of house data with cooldown information

**Usage:**

```lua
-- Client side:
local houses = lib.callback.await("force-burglary:callback:fetchPlayerHouses", false)
for i, house in ipairs(houses) do
  print(house.title, house.difficulty, house.isOnCooldown)
end
```

**Response Format:**

```lua
{
  {
    title = "Davis Residence",
    difficulty = "easy",
    isOnCooldown = false,
    cooldownRemaining = 0,
    -- ... all other house data from Config.HouseList
  }
}
```

***

#### force-burglary:callback:canRob

Checks if a player can rob a specific house.

**Parameters:**

* `data` (table) - House data to check

**Returns:** `table` - Response with success status and message

**Usage:**

```lua
-- Client side:
local response = lib.callback.await("force-burglary:callback:canRob", false, houseData)
if response.success then
  print("You can rob this house!")
else
  print("Cannot rob: " .. response.message)
end
```

**Response Format:**

```lua
{
  success = true/false,
  message = "Error or success message"
}
```

**Checks:**

* House cooldown
* Required police online
* Player inventory for required items
* Player XP level requirements

***

#### force-burglary:callback:attemptLootItem

Attempts to loot an item from a loot point.

**Parameters:**

* `UID` (number) - Robbery unique identifier
* `difficulty` (string) - House difficulty ("easy", "medium", "hard")
* `itemIndex` (number) - Index of the loot point

**Returns:** `table` - Response with success status and item data

**Usage:**

```lua
-- Client side:
local response = lib.callback.await("force-burglary:callback:attemptLootItem", false, UID, "easy", 1)
if response.success then
  print("Looted: " .. response.itemName .. " x" .. response.count)
end
```

**Response Format:**

```lua
{
  success = true/false,
  itemName = "phone",
  count = 1,
  xpGained = 2
}
```

***

#### force-burglary:callback:fetchPawnshopItems

Fetches items the player can sell at the pawnshop.

**Parameters:**

* `sellItems` (table) - List of items the pawnshop accepts

**Returns:** `table` - Array of items player has that can be sold

**Usage:**

```lua
-- Client side:
local pawnshopItems = Config.PawnShop.locations[1].sellItems
local playerItems = lib.callback.await("force-burglary:callback:fetchPawnshopItems", false, pawnshopItems)
```

**Response Format:**

```lua
{
  {
    name = "ipad",
    label = "iPad",
    price = 1200,
    count = 2 -- How many player has
  }
}
```

***

#### force-burglary:callback:attemptSellToPawnshop

Attempts to sell an item to the pawnshop.

**Parameters:**

* `item` (table) - Item data with name and price

**Returns:** `table` - Response with success status

**Usage:**

```lua
-- Client side:
local item = { name = "ipad", price = 1200 }
local response = lib.callback.await("force-burglary:callback:attemptSellToPawnshop", false, item)
if response.success then
  print("Item sold!")
end
```

***

#### force-burglary:callback:hasItem

Checks if player has a specific item.

**Parameters:**

* `item` (string) - Item name to check

**Returns:** `boolean` - Whether player has the item

**Usage:**

```lua
-- Client side:
local hasLockpick = lib.callback.await("force-burglary:callback:hasItem", false, "lockpick")
if hasLockpick then
  print("Player has a lockpick")
end
```

***

#### force-burglary:callback:getTimeOfDay

Gets the current in-game time.

**Returns:** `number` - Current hour (0-23)

**Usage:**

```lua
-- Client side:
local currentHour = lib.callback.await("force-burglary:callback:getTimeOfDay", false)
print("Current hour: " .. currentHour)
```

***

#### force-burglary:callback:attemptBuyInformation

Attempts to purchase house information.

**Parameters:**

* `houseData` (table) - House data
* `info` (table) - Information being purchased

**Returns:** `table` - Response with success status

**Usage:**

```lua
-- Client side:
local response = lib.callback.await("force-burglary:callback:attemptBuyInformation", false, houseData, infoData)
```

***

#### force-burglary:callback:isPlayerAdmin

Checks if a player is an admin.

**Parameters:**

* `target` (number) - Player source to check (optional, defaults to caller)

**Returns:** `boolean` - Whether player is admin

**Usage:**

```lua
-- Client side:
local isAdmin = lib.callback.await("force-burglary:callback:isPlayerAdmin", false)
```

***

#### force-burglary:callback:attemptPurchaseMarketItem

Attempts to purchase an item from the market.

**Parameters:**

* `item` (table) - Item data with name and price

**Returns:** `table` - Response with success status

**Usage:**

```lua
-- Client side:
local item = { name = "lockpick", price = 250 }
local response = lib.callback.await("force-burglary:callback:attemptPurchaseMarketItem", false, item)
if response.success then
  print("Item purchased!")
end
```

***

#### force-burglary:callback:getPlayerXP

Gets the player's current XP and level.

**Returns:** `table` - XP data

**Usage:**

```lua
-- Client side:
local xpData = lib.callback.await("force-burglary:callback:getPlayerXP", false)
print("Level: " .. xpData.level)
print("XP: " .. xpData.xp .. "/" .. xpData.xpToNextLevel)
```

**Response Format:**

```lua
{
  xp = 1234,
  level = 12,
  xpToNextLevel = 100
}
```

***

### Integration Examples

#### Opening the Burglary Menu

```lua
-- From a command
RegisterCommand("burglary", function()
  -- Open the burglary house selection menu
  TriggerEvent("force-burglary:client:openApp")
end)

-- From an interaction point
exports.ox_target:addBoxZone({
  coords = vec3(264.41, -1108.59, 29.72),
  size = vec3(2, 2, 2),
  options = {
    {
      label = "Browse Houses",
      icon = "fa-solid fa-house",
      onSelect = function()
        TriggerEvent("force-burglary:client:openApp")
      end
    }
  }
})
```

***

#### Checking Player Level Before Allowing Entry

```lua
-- Example: Restrict access based on burglary level
local function CanAccessBurglaryDealer()
  local xpData = lib.callback.await("force-burglary:callback:getPlayerXP", false)
  local level = xpData.level or 0

  if level < 5 then
    lib.notify({
      title = "Access Denied",
      description = "You need to be level 5 to access this dealer",
      type = "error"
    })
    return false
  end

  return true
end

-- Use in your interaction
exports.ox_target:addBoxZone({
  coords = vec3(-324.19, -598.85, 33.55),
  size = vec3(2, 2, 2),
  options = {
    {
      label = "Talk to Dealer",
      icon = "fa-solid fa-user",
      canInteract = function()
        return CanAccessBurglaryDealer()
      end,
      onSelect = function()
        -- Open market or custom menu
      end
    }
  }
})
```

***

#### Custom Reward System

```lua
-- Server-side: Give bonus rewards for completing hard robberies
RegisterNetEvent("force-burglary:server:removeActiveRobbery")
AddEventHandler("force-burglary:server:removeActiveRobbery", function(UID)
  local source = source
  local activeRobbery = ActiveRobberies[UID]

  if activeRobbery and activeRobbery.difficulty == "hard" then
    -- Give bonus reputation in your custom system
    exports['your-reputation']:addReputation(source, "criminal", 10)

    -- Give bonus money
    local Player = GetPlayerFromFramework(source)
    if Player then
      Player.addMoney("black_money", 500)
    end
  end
end)
```

***

#### Integrating with a Gang System

```lua
-- Client-side: Only allow gang members to rob certain houses
RegisterNetEvent("force-burglary:client:checkGangAccess")
AddEventHandler("force-burglary:client:checkGangAccess", function(houseData)
  if houseData.difficulty == "hard" then
    local hasGang = lib.callback.await("your-gang:hasGang", false)

    if not hasGang then
      lib.notify({
        title = "Restricted",
        description = "Hard houses require a gang",
        type = "error"
      })
      return
    end
  end

  -- Proceed with robbery
  TriggerEvent("force-burglary:client:attemptRobbery", houseData)
end)
```

***

#### Custom Dispatch Alert

```lua
-- Server-side custom dispatch
RegisterNetEvent("force-burglary:server:sendDispatch")
AddEventHandler("force-burglary:server:sendDispatch", function(data)
  local source = source

  -- Send to your custom dispatch
  exports['your-dispatch']:CreateDispatchCall({
    job = "police",
    coords = data.coords,
    title = "House Alarm Triggered",
    description = "A house alarm has been triggered. Investigate the location.",
    sprite = 459,
    color = 1,
    scale = 1.0,
    blipDuration = 5 * 60 * 1000 -- 5 minutes
  })
end)
```

***

#### Tracking Player Statistics

```lua
-- Server-side: Track burglary statistics
local PlayerStats = {}

RegisterNetEvent("force-burglary:server:updateActiveRobberies")
AddEventHandler("force-burglary:server:updateActiveRobberies", function(houseData)
  local source = source
  local identifier = GetPlayerIdentifier(source)

  if not PlayerStats[identifier] then
    PlayerStats[identifier] = {
      totalRobberies = 0,
      successfulRobberies = 0,
      totalValueStolen = 0
    }
  end

  PlayerStats[identifier].totalRobberies = PlayerStats[identifier].totalRobberies + 1
end)

-- Track successful completion
RegisterNetEvent("force-burglary:server:robberyCompleted")
AddEventHandler("force-burglary:server:robberyCompleted", function(UID, valueStolen)
  local source = source
  local identifier = GetPlayerIdentifier(source)

  if PlayerStats[identifier] then
    PlayerStats[identifier].successfulRobberies = PlayerStats[identifier].successfulRobberies + 1
    PlayerStats[identifier].totalValueStolen = PlayerStats[identifier].totalValueStolen + valueStolen
  end
end)
```

***

### Custom Framework Integration

To integrate Force Burglary with a custom framework, modify the files in the `custom/frameworks/` folders.

#### Client-Side Framework (`client/custom/frameworks/custom.lua`)

```lua
function GetPlayerDataClient()
  -- Return player data from your framework
  return YourFramework.GetPlayerData()
end

function GetPlayerJobClient()
  -- Return player job
  local playerData = YourFramework.GetPlayerData()
  return playerData.job.name
end

function ShowNotificationClient(message, type)
  -- Show notification using your system
  YourFramework.ShowNotification(message, type)
end
```

#### Server-Side Framework (`server/custom/frameworks/custom.lua`)

```lua
function GetPlayerFromSource(source)
  -- Get player object from your framework
  return YourFramework.GetPlayer(source)
end

function GetPlayerIdentifierServer(source)
  -- Return player identifier
  return YourFramework.GetIdentifier(source)
end

function AddItemServer(source, item, count)
  local Player = GetPlayerFromSource(source)
  if Player then
    Player.addItem(item, count)
    return true
  end
  return false
end

function RemoveItemServer(source, item, count)
  local Player = GetPlayerFromSource(source)
  if Player then
    Player.removeItem(item, count)
    return true
  end
  return false
end

function AddMoneyServer(source, moneyType, amount)
  local Player = GetPlayerFromSource(source)
  if Player then
    Player.addMoney(moneyType, amount)
    return true
  end
  return false
end

function GetItemCountServer(source, item)
  local Player = GetPlayerFromSource(source)
  if Player then
    return Player.getItemCount(item)
  end
  return 0
end
```

***

### Custom Dispatch Integration

To integrate with a custom dispatch system, modify `client/custom/dispatch.lua`:

```lua
function SendDispatch(data)
  -- Your custom dispatch logic
  exports['your-dispatch']:SendAlert({
    coords = data.coords,
    title = "House Burglary",
    description = "A house alarm has been triggered",
    job = "police",
    sprite = Config.Dispatch.sprite,
    color = 1,
    duration = Config.Dispatch.time * 60 * 1000
  })
end

return SendDispatch
```

***

### Additional Tips

#### Debugging

Enable debug mode in config to see detailed logs:

```lua
Config.Debug = true
```

#### Performance Considerations

1. **Callback Usage**: Callbacks are synchronous - avoid calling them in loops
2. **Event Throttling**: Don't spam events, especially server events
3. **NUI Communication**: Minimize SendNUIMessage calls

#### Best Practices

1. **Always check returns**: Callbacks may return nil if something fails
2. **Validate data**: Always validate house data before processing
3. **Clean up**: Always clean up zones, blips, and peds when done
4. **Error handling**: Wrap custom code in pcall for safety

```lua
local success, result = pcall(function()
  -- Your risky code here
  return lib.callback.await("force-burglary:callback:canRob", false, houseData)
end)

if not success then
  print("Error: " .. tostring(result))
end
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forcedevelopments.com/resources/force-burglary/usage-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
