# Server

## 📦 Core Item Operations

These functions are the most commonly used for interacting with player items, such as adding, removing, and checking item counts.

### AddItem

Adds an item to an inventory. This function handles all logic regarding stacking, weight limits, and finding available slots. If the inventory is full or the item is invalid, it returns `false`.

```lua
exports['ak47_inventory']:AddItem(inv, item, amount, slot, info, weight, expiretime)
```

* inv: `string` or `number`
  * player id (source) or unique inventory identifier
* item: `string`
  * item name
* amount: `number`
  * amount of the item to add
* slot: `number` (optional)
  * specific slot index to place the item in (force placement)
* info: `table` (optional)
  * item metadata table (e.g., durability, serial number)
* weight: `number` (optional)
  * override the default weight of this specific item instance
* expiretime: `number` (optional)
  * override the default expiration timestamp of this specific item instance

Return: `boolean`, `string` or `number`

* success (true/false)
* reason (if failed) OR slot index (if success)

### RemoveItem

Removes a specific quantity of an item from an inventory. It prioritizes removing from specific slots if provided, otherwise it searches and removes from the first available stack(s).

```lua
exports['ak47_inventory']:RemoveItem(inv, item, amount, slot)
```

* inv: `string` or `number`
  * player id (source) or unique inventory identifier
* item: `string`
  * item name
* amount: `number`
  * amount of the item to remove
* slot: `number` (optional)
  * specific slot index to remove the item from

Return: `boolean`, `string`

* success (true/false)
* reason (e.g., "notenough")

### HasItems

Verifies if an inventory contains a list of specific items in the required quantities. This is commonly used for crafting recipes or trade requirements.

```lua
exports['ak47_inventory']:HasItems(inv, items)
```

* inv: `string` or `number`
* items: `table`
  * Key-value table: `{[item_name] = amount}` (e.g., `{'bread' = 1, 'water' = 2}`)

Return: `boolean`, `table`

* hasAll (true if all items are present)
* missingItems (table of missing items and the amounts still needed)

### GetItem

Retrieves a consolidated object containing data about a specific item in an inventory. This is useful for checking if a player has an item and getting its total combined count across all slots.

```lua
exports['ak47_inventory']:GetItem(inv, item, info, strict)
```

* inv: `string` or `number`
* item: `string`
  * item name
* info: `table` (optional)
  * filter by specific metadata
* strict: `boolean` (optional)
  * if true, checks for an exact metadata match (does not sum duplicates with different metadata)

Return: `table`

* item table with total item amount & properties

### GetAmount

Returns the total numeric count of a specific item in an inventory. It sums up all stacks of that item.

```lua
exports['ak47_inventory']:GetAmount(identifier, item, info, strict)
```

* identifier: `string` or `number`
* item: `string`
* info: `table` (optional)
* strict: `boolean` (optional)

Return: `number`

### CanAddItem

Checks if an inventory has enough weight capacity and slot space to accept an item. This function **does not** actually add the item, it only performs the check.

```lua
exports['ak47_inventory']:CanAddItem(identifier, item, amount, skipWeight)
```

* identifier: `string` or `number`
* item: `string`
* amount: `number`
* skipWeight: `boolean` (optional)
  * if true, ignores weight limit checks (only checks slot limit)

Return: `boolean`

#### CanCarryAmount

Calculates the maximum amount of a specific item that fits into the inventory's remaining weight capacity.

```lua
exports['ak47_inventory']:CanCarryAmount(identifier, item)
```

* identifier: `string` or `number`
* item: `string` or `table`

Return: `number`

* amount that fits

### CanSwapItem

Determines if two items can be swapped between slots or inventories without exceeding weight limits. This is used during drag-and-drop operations.

```lua
exports['ak47_inventory']:CanSwapItem(inv, firstItem, firstItemCount, testItem, testItemCount)
```

* inv: `string` or `number`
* firstItem: `string`
* firstItemCount: `number`
* testItem: `string`
* testItemCount: `number`

Return: `boolean`

## 🗃️ Inventory Management

Functions for managing inventory instances (opening, creating, loading, saving).

### OpenInventory

Opens the inventory user interface for a specific player. This allows them to view the specified inventory identifier.

```lua
exports['ak47_inventory']:OpenInventory(source, identifier, data)
```

* source: `number`
  * The player ID opening the inventory
* identifier: `string`
  * The identifier of the inventory to open
* data: `table` (optional)
  * Configuration data for creating the inventory on-the-fly (e.g., dumpsters)

### CloseInventory

Forces the inventory UI to close for a specific player.

```lua
exports['ak47_inventory']:CloseInventory(source)
```

* source: `number`

### CreateInventory

Initializes a new inventory in the system memory. This is required for creating stashes, trunks, or other non-player inventories before they can be accessed.

```lua
exports['ak47_inventory']:CreateInventory(identifier, data)
```

* identifier: `string`
* data: `table`
  * label: `string`
  * maxWeight: `number`
  * slots: `number`
  * type: `string` (backpack, stash, player, shop, trunk, glovebox)
  * type2: `string` (optional, e.g. 'smallBackpack')
  * temp: `boolean` (optional, true = not saved to database)
  * whitelist: `table` (optional)
  * blacklist: `table` (optional)

Example:

```lua
-- server side
exports['ak47_inventory']:CreateInventory('housing:123', {
    label = 'Housing',
    maxWeight = 500000,
    slots = 50,
    type = 'stash',
})

--open from server side
exports['ak47_inventory']:OpenInventory(source, 'housing:123')

--open from client side
exports['ak47_inventory']:OpenInventory('housing:123')
```

### LoadInventory

lLoads an inventory from the database. If provided with `data`, it can also create the inventory if it doesn't already exist.

{% tabs %}
{% tab title="Load Existing Inventory" %}

```lua
exports['ak47_inventory']:LoadInventory(identifier)
```

{% endtab %}

{% tab title="Create & Load" %}

```lua
--if missing in database then create & load an inventory
exports['ak47_inventory']:LoadInventory(identifier, data)
```

{% endtab %}
{% endtabs %}

Return: `boolean`

Example:

```lua
-- server side
exports['ak47_inventory']:LoadInventory('housing:123', {
    label = 'Housing',
    maxWeight = 500000,
    slots = 50,
    type = 'stash',
})
```

### SaveInventory

Forces an immediate save of a specific inventory to the database.

```lua
exports['ak47_inventory']:SaveInventory(identifier)
```

* identifier: `string` or `number`

#### SaveAllInventory

Forces a save of *all* currently loaded inventories that have pending changes. This is typically run automatically on server stop/restart.

```lua
exports['ak47_inventory']:SaveAllInventory()
```

### ClearInventory

Removes all items from an inventory, effectively wiping it clean.

```lua
exports['ak47_inventory']:ClearInventory(identifier)
```

* identifier: `string` or `number`

### UnloadInventory

Unloads an inventory from server memory (saving it first) to free up resources. It will be reloaded from the database if accessed again.

```lua
exports['ak47_inventory']:UnloadInventory(identifier)
```

* identifier: `string` or `number`

### DeleteInventory

Permanently deletes an inventory from the database and removes it from server memory.

```lua
exports['ak47_inventory']:DeleteInventory(identifier)
```

* identifier: `string` or `number`

## 🔍 Data Retrieval & Getters

Functions for reading specific states or configurations.

### GetInventory

Retrieves the full inventory object, including the list of items, current weight, max weight, and other configuration properties.

```lua
exports['ak47_inventory']:GetInventory(identifier)
```

* identifier: `string` or `number`

Return: `table`

* inventoryTable

### GetInventoryItems

Retrieves just the list (table) of items from an inventory. Useful for iteration when you don't need weight or other inventory properties.

```lua
exports['ak47_inventory']:GetInventoryItems(identifier)
```

* identifier: `string` or `number`

Return: `table`

* itemsTable

### Search

A versatile search function to find item counts or full slot data.

```lua
exports['ak47_inventory']:Search(identifier, search, item, info)
```

* identifier: `string` or `number`
* search: `string`
  * `'slots'` (returns a table of item data) or `'count'`/`'amount'` (returns the total numeric count)
* item: `table` (list of item names) or `string`
* info: `table` or `string` (optional)

### Items

Retrieves the shared item configuration from the server. You can use this to fetch the definition of every item or a specific item's details (label, weight, etc.).

{% tabs %}
{% tab title="All Items" %}

```lua
exports['ak47_inventory']:Items()
```

{% endtab %}

{% tab title="Single Item" %}

```lua
exports['ak47_inventory']:Items('water')
```

{% endtab %}
{% endtabs %}

### GetItemLabel

Returns the friendly display label of a specific item name (e.g., returns "Water Bottle" for input "water").

```lua
exports['ak47_inventory']:GetItemLabel(item)
```

* item: `string`
  * item name

Return: `string`

### GetCurrentWeapon

Retrieves the item data of the weapon currently equipped by the player.

```lua
exports['ak47_inventory']:GetCurrentWeapon(identifier)
```

* identifier: `string` or `number`

Return: `table`

* weaponItemData

### CanCarryWeight

Checks if the inventory has enough remaining capacity to hold a specific amount of weight.

```lua
exports['ak47_inventory']:CanCarryWeight(identifier, weight)
```

* identifier: `string` or `number`
* weight: `number`

Return: `boolean`, `number`

* canHold (true/false)
* availableWeight (remaining weight capacity)

### GetEmptySlot

Returns the index of the **first available empty slot** in the inventory. Returns `nil` if full.

```lua
exports['ak47_inventory']:GetEmptySlot(identifier)
```

* identifier: `string` or `number`

Return: `number`

* slotId

### GetContainerFromSlot

If a slot contains a container item (like a backpack), this retrieves the actual inventory data object associated with that container.

```lua
exports['ak47_inventory']:GetContainerFromSlot(identifier, slotId)
```

* identifier: `string` or `number`
* slotId: `number`

Return: `table`

* containerInventoryData

## 📍 Slot Operations

Functions for interacting with specific slots or finding item locations.

### GetSlot

Retrieves the item data stored at a specific slot index. Returns `nil` or an empty table if the slot is empty.

```lua
exports['ak47_inventory']:GetSlot(identifier, slot)
```

* identifier: `string` or `number`
* slot: `number`

Return: `table`

* The item data table at that slot

### GetSlotForItem

Finds the optimal slot index for an item. It will return the index of an existing stack (if stackable and space exists) or the first available empty slot.

```lua
exports['ak47_inventory']:GetSlotForItem(identifier, itemName, info)
```

* identifier: `string` or `number`
* itemName: `string`
* info: `table` (optional)

Return: `number`

* slotId

### GetSlotWithItem

Retrieves the data of the **first slot found** containing the specific item.

```lua
exports['ak47_inventory']:GetSlotWithItem(identifier, itemName, info, strict)
```

* identifier: `string` or `number`
* itemName: `string`
* info: `table` (optional)
* strict: `boolean` (optional)

Return: `table`

* slotData

### GetSlotIdWithItem

Retrieves the slot index (ID) of the **first slot found** containing the specific item.

```lua
exports['ak47_inventory']:GetSlotIdWithItem(identifier, itemName, info, strict)
```

* identifier: `string` or `number`
* itemName: `string`
* info: `table` (optional)
* strict: `boolean` (optional)

Return: `number`

* slotId

### GetSlotsWithItem

Retrieves a list of **all slot data tables** that contain the specific item. Useful for finding every instance of an item split across multiple slots.

```lua
exports['ak47_inventory']:GetSlotsWithItem(identifier, itemName, info, strict)
```

* identifier: `string` or `number`
* itemName: `string`
* info: `table` (optional)
* strict: `boolean` (optional)

Return: `table`

* list of slotData objects

### GetSlotIdsWithItem

Retrieves a list of **all** slot IDs containing the item.

```lua
exports['ak47_inventory']:GetSlotIdsWithItem(inv, itemName, info, strict)
```

* **Return**: `table` (List of IDs).

### GetItemSlots

Provides detailed information about where an item is located, including a map of slots-to-amounts and the count of empty slots.

```lua
exports['ak47_inventory']:GetItemSlots(identifier, item, info)
```

* identifier: `string` or `number`
* item: `table` (must have .name) or `string`
* info: `table` (optional)

Return: `table`, `number`, `number`

* slots (key=slotId, value=amount)
* totalAmount
* emptySlotsCount

### GetFirstItem

Finds and returns the data of the **first occurrence** of an item found in the inventory, regardless of how many stacks exist.

```lua
exports['ak47_inventory']:GetFirstItem(inv, item)
```

* inv: `string` or `number`
* item: `string`
  * item name

Return: `table`

* first found item table

## ✏️ Updates & Modification

Functions that modify existing items or inventory properties.

### SetItemInfo

Updates the metadata (info table) of an item in a specific slot.

```lua
exports['ak47_inventory']:SetItemInfo(identifier, slot, info)
```

* identifier: `string` or `number`
* slot: `number`
* info: `table`

### SetQuality

Sets the quality (durability) of an item in a specific slot.

```lua
exports['ak47_inventory']:SetQuality(identifier, slot, quality)
```

* identifier: `string` or `number`
* slot: `number`
* quality: `number`

### RemoveQuality

Reduces the quality (durability) of an item in a specific slot. Can optionally remove the item if quality reaches zero.

```lua
exports['ak47_inventory']:RemoveQuality(identifier, slot, value)
```

* identifier: `string` or `number`
* slot: `number`
* value: `number`

### SetMaxWeight

Dynamically updates the maximum weight limit of an inventory.

```lua
exports['ak47_inventory']:SetMaxWeight(identifier, newWeight)
```

* identifier: `string` or `number`
* newWeight: `number`

### SetSlotCount <a href="#setslotcount" id="setslotcount"></a>

Changes the number of slots an inventory is currently have.

```lua
exports['ak47_inventory']:SetSlotCount(identifier, slots)
```

* identifier: `string` or `number`
* slots: `number`

### UpdatePlayerInv

Forces a synchronization of the server-side inventory data to the client-side UI for a specific player. Use this if you modify inventory data manually.

```lua
exports['ak47_inventory']:UpdatePlayerInv(identifier)
```

* identifier: `string` or `number`

### SetInvItems

Completely overwrites the items in an inventory with a new table of items. **Warning**: This replaces the entire item set.

```lua
exports['ak47_inventory']:SetInvItems(identifier, items)
```

* identifier: `string` or `number`
* items: `table`

### ClearClothing

Removes all items stored in the clothing slots of an inventory (e.g., masks, hats).

```lua
exports['ak47_inventory']:ClearClothing(identifier)
```

* identifier: `string` or `number`

## 🛠️ Administrative & Special

Specialized functions for shops, police systems, and vehicle handling.

### ConfiscateInventory

Moves all items from a player's inventory to a temporary "confiscated" storage (prefixed with `conf:`) and clears their main inventory.

```lua
exports['ak47_inventory']:ConfiscateInventory(identifier)
```

* identifier: `string` or `number`

### ReturnInventory

Restores items from the "confiscated" storage back to the player's main inventory.

```lua
exports['ak47_inventory']:ReturnInventory(identifier)
```

* identifier: `string` or `number`

### CreateShop

Helper to create a shop inventory with items for sale. Supports job restrictions, licenses, and custom sell prices.

```lua
exports['ak47_inventory']:CreateShop(identifier, name, itemTable, account)
```

* **identifier**: `string` - Unique ID for this shop.
* **name**: `string` - Label displayed to the player.
* **itemTable**: `table` - List of items with configurations (see example below).
* **account**: `string` - Currency to use (e.g., 'money', 'bank', 'black\_money').

**Supported `itemTable` options:**

* `item`: Item name (required)
* `buyPrice`: Cost to purchase from shop
* `sellPrice`: Money given to player when selling TO shop
* `stock`: Available quantity (-1 for infinite)
* `jobs`: Table of allowed jobs/grades `{[jobName] = minGrade}`
* `gangs`: Table of allowed gangs/grades `{[gangName] = minGrade}`
* `license`: Table `{ name = "weapon", class = "A" }` (optional class)
* `requires`: Table of items needed to purchase `{[item_name] = amount}`
* `hasSerial`: Boolean (true generates random serial on purchase)
* `quality`: Initial quality (default 100)

**Example:**

```lua
local shopItems = {
    {
        item = 'bread',
        buyPrice = 10,
        stock = 100,
    },
    {
        item = 'weapon_pistol',
        buyPrice = 5000,
        stock = 5,
        hasSerial = true,
        jobs = { police = 0 }, -- Only police can buy
        license = { name = 'weapon' } -- Requires weapon license
    },
    {
        item = 'gold_bar',
        sellPrice = 1000, -- Shop buys gold bars for 1000
        buyPrice = 2000
    }
}

exports['ak47_inventory']:CreateShop('general_store', 'General Store', shopItems, 'money')

-- open shop from client side
exports['ak47_inventory']:OpenInventory('general_store')

-- open shop from server side
exports['ak47_inventory']:OpenInventory(source, 'general_store')
```

### SetWhitelistedItemsForContainer

Restricts an inventory to only accept a specific list of items. Any item not in this list cannot be added.

```lua
exports['ak47_inventory']:SetWhitelistedItemsForContainer(identifier, items)
```

* identifier: `string` or `number`
* items: `table` (list of allowed item names)

Example:

```lua
exports['ak47_inventory']:SetWhitelistedItemsForContainer('stash:123', {'water', 'bread'})
```

### SetBlacklistedItemsForContainer

Restricts an inventory by preventing specific items from being stored in it.

```lua
exports['ak47_inventory']:SetBlacklistedItemsForContainer(identifier, items)
```

* identifier: `string` or `number`
* items: `table` (list of disallowed item names)

Example:

```lua
exports['ak47_inventory']:SetBlacklistedItemsForContainer('stash:123', {'water', 'bread'})
```

### OnChangeVehiclePlate

A utility helper to migrate trunk and glovebox inventories when a vehicle's plate is changed (e.g., applying a fake plate).

```lua
exports['ak47_inventory']:OnChangeVehiclePlate(oldPlate, newPlate)
```

* oldPlate: `string`
* newPlate: `string`
