# Trust Level System

***

### 🚀 Overview

The Codex TrustLevel System introduces a **player-based reputation system** designed for immersive RedM gameplay.

Players earn or lose trust in multiple categories (moonshine, breaker, drugcooker, etc.), unlocking:

* Black‑market shops
* Exclusive missions
* Special NPC interactions

Built on **CodexCore**, it integrates directly with your:

* Economy
* Inventory
* Prompts
* Character data

***

### 🎯 Key Features

* Persistent trust levels per player (stored in SQL)
* Dynamic trust‑gated black‑market shops
* Custom missions and contraband systems
* Cinematic draggable NUI HUD
* Full CodexCore API integration
* Plug‑and‑play with VORP, RSGCore, TPZCore
* Developer‑friendly exports & events

***

### ⚙️ Setup & Installation

#### Requirements

* RedM Server (latest build)
* **CodexCore** (required)
* MySQL driver (`ghmattimysql`, `oxmysql`, or `mysql-async`)
* Optional: `codex_security` for anti‑abuse handling

***

#### Installation Steps

1. Drop the resource into your `resources/` directory.
2. Ensure CodexCore starts before this resource.

In `server.cfg`:

```cfg
ensure codex_core
ensure codex_trustlevel
```

3. Configure framework in:

`Shared/codex-main_shared.lua`

```lua
Codex.Framework = "vorp" -- or "rsg", "tpz"
```

4. Start your server. The system auto‑creates the trust table if migrations are enabled.

***

### 🧱 Database Schema

If `Codex.Databasemigration = true` is disabled, run manually:

```sql
CREATE TABLE IF NOT EXISTS `trustlevel` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `identifier` varchar(255) NOT NULL,
  `charidentifier` varchar(255) NOT NULL,
  `trust` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`trust`)),
  PRIMARY KEY (`id`),
  UNIQUE KEY `identifier` (`identifier`,`charidentifier`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```

#### Trust JSON Format

```json
{
  "moonshine": 10,
  "breaker": 5,
  "gunner": 3
}
```

***

## 💻 Client‑Side Developer Documentation

### 📦 Exported Functions

#### `getTrustLevel(category)`

```lua
local trust = exports['codex_trustlevel']:getTrustLevel('moonshine')
print('Current moonshine trust:', trust)
```

**Returns:** `number` — player’s trust value (defaults to `0`).

***

### 🔔 Client Events

| Event                       | Description                  |
| --------------------------- | ---------------------------- |
| `codex:setTrustLevel`       | Sync trust table from server |
| `codex:openTrustShop`       | Opens trust‑based shop       |
| `codex-core:toggleTrustHUD` | Toggle HUD visibility        |
| `codex:openUI`              | Open UI settings manually    |

***

### 🛒 Trust‑Based Shops

Defined in `codex-main_shared.lua` under `Codex.TrustShopPos`.

```lua
Codex.TrustShopPos = {
  ['Drug Shop'] = {
    label = 'Drugs',
    ped = 'amsp_robsdgunsmith_males_01',
    coords = vec4(-1850.24, -1739.08, 85.62, 74.02),
    menuTitle = 'Moonshine Market',
    menuDesc = 'Exclusive deals for trusted customers.',

    Items = {
      { label = 'Lockpick', name = 'lockpick', price = 5, trustRequired = 10 },
      { label = 'Moonshine Drink', name = 'moonshine', price = 3, trustRequired = 5 }
    }
  }
}
```

#### Behavior

* Player approaches NPC → Prompt appears (`E`)
* If trust ≥ required → Shop opens
* Else → Notification shown

***

### 🎮 Custom Missions & Interactions

#### Selling Contraband (Client)

```lua
RegisterNetEvent("codex:sellContrabandClient")
AddEventHandler("codex:sellContrabandClient", function()
  TriggerServerEvent("codex:sellContrabandServer")
  TriggerEvent("codex-core:notification", "⏳ Processing your sale...", 4000, "inform")
end)
```

***

#### Requesting a Mission

```lua
RegisterNetEvent("codex:requestJobClient")
AddEventHandler("codex:requestJobClient", function()
  TriggerServerEvent("codex:requestJobServer")
  TriggerEvent("codex-core:notification", "🤝 Asking the contact for work...", 4000, "inform")
end)
```

***

### 🎨 UI & Settings

Open in‑game:

```
/uisettings
```

You can:

* Change icon color & size
* Toggle HUD visibility
* Import / export layouts (JSON)

All settings are stored locally using `localStorage`.

***

## 🖥️ Server‑Side Developer Documentation

### 🔹 Core Trust Events

#### Add Trust

```lua
TriggerEvent("codex:addTrustLevelRequest", "moonshine", 5)
```

***

#### Remove Trust

```lua
TriggerEvent("codex:removeTrustLevelRequest", "breaker", 3)
```

***

#### Sync Trust to Client

```lua
TriggerServerEvent("codex:getTrustLevel")
```

***

### 💰 Example — Selling Contraband (Server)

```lua
RegisterNetEvent("codex:sellContrabandServer", function()
  local src = source
  local sellItem = "lockpick"
  local sellPrice = 4
  local trustGain = 2

  local count = Core.GetItemCount(src, sellItem)
  if not count or count <= 0 then
    TriggerClientEvent('codex-core:notification', src, '❌ No contraband to sell.', 3000, 'error')
    return
  end

  Core.RemoveItem(src, sellItem, count)
  Core.AddAccountMoney(src, Codex.CashMoneyType, count * sellPrice)
  TriggerEvent("codex:addTrustLevelRequest", "breaker", trustGain)
end)
```

***

### 🏪 Example — Server‑Side Purchases

```lua
RegisterNetEvent('codex:buyItem', function(itemName, itemPrice, SecurityToken)
  local src = source
  local balance = CodexCore.GetMoney(src)

  if balance >= itemPrice then
    CodexCore.RemoveAccountMoney(src, Codex.CashMoneyType, itemPrice)
    CodexCore.AddItem(src, itemName, Codex.GiveItemQuantity)
    TriggerClientEvent('codex-core:notification', src, '✅ Purchase successful!', 3000)
  else
    TriggerClientEvent('codex-core:notification', src, '❌ Not enough money!', 3000)
  end
end)
```

***

## 🧩 Integration Examples

### 🎁 Reward Trust After a Mission

```lua
TriggerEvent("codex:addTrustLevelRequest", "moonshine", 10)
```

***

### 🔒 Restrict Access by Trust Level

```lua
local trust = exports['codex_trustlevel']:getTrustLevel('breaker')
if trust < 50 then
  TriggerEvent('codex-core:notification', 'You are not trusted enough to enter.', 3000)
  return
end
```

***

### ⚰️ Remove Trust on Death

Already built‑in:

```lua
Codex.RemoveTrustOnDeath = true
Codex.RemoveAmmountOnDeath = 10
Codex.TypeMoonshineRemoveOnDeath = 'moonshine'
```

***

## 🧠 Customization & Extension

### ➕ Add a New Trust Category

1. Open `Shared/codex-main_shared.lua`
2. Add category:

```lua
Codex.PresetTrusts["smuggler"] = 0
```

3. Add icon: `/html/images/smuggler.png`
4. Duplicate a HUD block in `index.html`
5. Reward players:

```lua
TriggerEvent("codex:addTrustLevelRequest", "smuggler", 10)
```

***

## 🧩 Developer Commands

| Command           | Description                   |
| ----------------- | ----------------------------- |
| `/uisettings`     | Open UI settings              |
| `/getuidata`      | Print trust data + refresh    |
| `/add_trust`      | Add 1 breaker trust (dev)     |
| `/remove_trust`   | Remove 25 breaker trust (dev) |
| `/trustui_active` | Show HUD                      |
| `/trustui_hide`   | Hide HUD                      |
| `/close_ui_menu`  | Force close UI                |

***

## 🔐 Security & Debugging

* Enable secure events:

```lua
Codex.AccessToSecurityApi = true
```

* Enable developer logging:

```lua
Codex.DeveloperMode = true
```

All transactions & trust updates will be logged when enabled.

***

## 🧩 Framework Compatibility

| Framework | Status                   |
| --------- | ------------------------ |
| VORP      | ✅ Fully supported        |
| RSGCore   | ✅ Fully supported        |
| TPZCore   | ✅ Supported              |
| CodexCore | 🧠 Required base library |
