# Rarx Banking

### Features

* 💰 **Full Banking** - Deposits, withdrawals & transfers with real-time updates
* 💳 **Debit Cards** - Card system with PIN security and lock/unlock
* 🏧 **ATM System** - Complete ATM interface with card validation
* 💎 **Savings Accounts** - Interest rates and separate balance
* 📊 **Credit System** - Configurable limits based on playtime
* 🏢 **Society Accounts** - Boss access to company funds
* 📈 **Transaction History** - Visual charts and detailed logs
* 🎨 **Customizable UI** - Colors, logo, and branding
* 🌍 **Multi-language** - EN, ES, FR, DE, PT

***

### Requirements

| Dependency             | Required   |
| ---------------------- | ---------- |
| QBCore / ESX / QBox    | ✅          |
| oxmysql                | ✅          |
| ox\_target / qb-target | ❌ Optional |

***

### Installation

#### Step 1: Extract

Download and extract `rarx_banking` to your resources folder:

```
resources/
└── [rarx]/
    └── rarx_banking/
```

#### Step 2: Configure server.cfg

```cfg
# Language (en, es, fr, de, pt)
setr rarx-lang "en"

# Start resource (after oxmysql)
ensure rarx_banking
```

#### Step 3: Restart Server

Database tables are created automatically on first start.

#### Step 4: Configure

Edit `config.lua` to customize the script.

***

### Auto-Detected Systems

The script automatically detects and uses popular systems. **No configuration needed!**

#### Inventory

| System            | Status |
| ----------------- | ------ |
| ox\_inventory     | ✅ Auto |
| qs-inventory      | ✅ Auto |
| origen\_inventory | ✅ Auto |
| ps-inventory      | ✅ Auto |
| codem-inventory   | ✅ Auto |
| qb-inventory      | ✅ Auto |

#### Notifications

| System         | Status |
| -------------- | ------ |
| ox\_lib        | ✅ Auto |
| okokNotify     | ✅ Auto |
| mythic\_notify | ✅ Auto |
| pNotify        | ✅ Auto |

#### Text UI

| System         | Status |
| -------------- | ------ |
| ox\_lib        | ✅ Auto |
| cd\_drawtextui | ✅ Auto |
| okokTextUI     | ✅ Auto |

#### Society / Job Accounts

| System            | Status |
| ----------------- | ------ |
| qb-management     | ✅ Auto |
| qb-bossmenu       | ✅ Auto |
| esx\_society      | ✅ Auto |
| esx\_addonaccount | ✅ Auto |
| okokBanking       | ✅ Auto |

> **Not listed?** Use the `custom/` folder to add your own integration.

***

### Configuration

#### Framework

```lua
-- Auto-detect (recommended)
Config.Framework = 'auto'

-- Or force specific framework
Config.Framework = 'qbcore'  -- 'qbcore', 'esx', 'qbox'
```

#### Language

Set in `server.cfg`:

```cfg
setr rarx-lang "en"
```

Available: `en`, `es`, `fr`, `de`, `pt`

#### Bank Locations

```lua
Config.BankLocations = {
    { coords = vector3(149.59, -1042.16, 29.37), heading = 337.0, length = 2.0, width = 2.0 },
    { coords = vector3(314.23, -280.77, 54.16), heading = 340.0, length = 2.0, width = 2.0 },
    -- Add more...
}
```

#### ATM Models

```lua
Config.ATMModels = {
    'prop_atm_01',
    'prop_atm_02',
    'prop_atm_03',
    'prop_fleeca_atm'
}
```

#### UI Colors

```lua
Config.Colors = {
    primary = '3b82f6',        -- Blue (hex without #)
    primary_dark = '2563eb',
    secondary = '10b981',      -- Green
    secondary_dark = '059669',
    accent = 'f59e0b',         -- Amber
    error = 'ef4444',
}
```

#### Loading Screen

```lua
Config.LoadingScreen = {
    enabled = true,
    logo = 'https://yourserver.com/logo.png',
    duration = 1500,
    bankName = 'Fleeca Bank',
}
```

#### Savings Account

```lua
Config.SavingsInterestRate = 0.5  -- 0.5% per real hour
```

#### Credit System

```lua
Config.Credit = {
    enabled = true,
    defaultLimit = 50000,
    maxLimit = 500000,
    interestRate = 5,           -- 5%
    paymentCycle = 'weekly',    -- 'weekly' or 'monthly'
    autoDeduct = true,

    -- Limits based on playtime (hours)
    limitTiers = {
        { minPlaytime = 0, limit = 10000 },
        { minPlaytime = 10, limit = 25000 },
        { minPlaytime = 50, limit = 50000 },
        { minPlaytime = 100, limit = 100000 },
    },
}
```

#### Society Accounts

```lua
Config.Society = {
    enabled = true,
    bossGrade = 4,  -- Default grade for boss access

    -- Custom grades per job
    bossGrades = {
        ['police'] = 3,
        ['ambulance'] = 3,
    },

    -- Restrict to specific jobs (empty = all)
    allowedJobs = {},
}
```

#### Target System

```lua
Config.UseTarget = true  -- Use ox_target/qb-target instead of DrawText
```

***

### Custom Integrations

The `custom/` folder allows you to add your own systems.

#### Custom Notifications

Edit `custom/client.lua`:

```lua
function CustomNotify(message, type)
    -- Your notification system
    exports['my-notify']:Send(message, type)
    return true  -- Return true to use custom
end
```

#### Custom Inventory

Edit `custom/client.lua`:

```lua
function HasCustomItem(itemName, amount)
    -- Your inventory check
    return exports['my-inventory']:HasItem(itemName, amount)
end
```

#### Custom Logging

Edit `custom/server.lua`:

```lua
function CustomLog(action, source, data)
    -- Discord webhook example
    PerformHttpRequest('YOUR_WEBHOOK', function() end, 'POST',
        json.encode({embeds = {{
            title = 'Banking: ' .. action,
            description = json.encode(data)
        }}}),
        { ['Content-Type'] = 'application/json' }
    )
end
```

#### Transaction Hook

Edit `custom/server.lua`:

```lua
function OnTransactionComplete(source, type, amount, newBalance)
    -- type: 'deposit', 'withdraw', 'transfer_in', 'transfer_out'
    print(('Transaction: %s $%d'):format(type, amount))
end
```

#### Custom Society

Edit `custom/server.lua`:

```lua
function GetCustomSocietyBalance(jobName)
    return exports['my-society']:GetBalance(jobName)
end

function AddCustomSocietyMoney(jobName, amount)
    exports['my-society']:AddMoney(jobName, amount)
    return true
end

function RemoveCustomSocietyMoney(jobName, amount)
    exports['my-society']:RemoveMoney(jobName, amount)
    return true
end
```

***

### Exports & Events

#### Client Exports

**Open Bank UI**

```lua
exports['rarx_banking']:OpenBank()
```

**Example: Open bank with command**

```lua
RegisterCommand('bank', function()
    exports['rarx_banking']:OpenBank()
end, false)
```

**Example: Open bank with keybind**

```lua
RegisterKeyMapping('openbank', 'Open Bank', 'keyboard', 'F5')
RegisterCommand('openbank', function()
    exports['rarx_banking']:OpenBank()
end, false)
```

**Open ATM UI**

```lua
exports['rarx_banking']:OpenATM()
```

**Example: Open ATM from target**

```lua
exports['ox_target']:addModel({'prop_atm_01'}, {
    {
        label = 'Use ATM',
        onSelect = function()
            exports['rarx_banking']:OpenATM()
        end
    }
})
```

**Close UI**

```lua
exports['rarx_banking']:CloseBank()
exports['rarx_banking']:CloseATM()
```

***

#### Server Exports

**GetBankBalance**

Get player's bank balance.

```lua
local balance = exports['rarx_banking']:GetBankBalance(source)
```

**Example: Check if player can afford something**

```lua
RegisterNetEvent('shop:buy', function(price)
    local src = source
    local balance = exports['rarx_banking']:GetBankBalance(src)

    if balance >= price then
        -- Player can afford
    else
        -- Not enough money
    end
end)
```

**AddBankMoney**

Add money to player's bank. Automatically logs the transaction.

```lua
local success = exports['rarx_banking']:AddBankMoney(source, amount, reason)
```

**Example: Pay salary**

```lua
function PaySalary(source, jobName, amount)
    local success = exports['rarx_banking']:AddBankMoney(source, amount, 'Salary: ' .. jobName)
    if success then
        TriggerClientEvent('ox_lib:notify', source, {
            title = 'Salary',
            description = 'You received $' .. amount,
            type = 'success'
        })
    end
end
```

**Example: Reward system**

```lua
RegisterNetEvent('rewards:claim', function(rewardId)
    local src = source
    local reward = Rewards[rewardId]

    if reward then
        exports['rarx_banking']:AddBankMoney(src, reward.amount, 'Reward: ' .. reward.name)
    end
end)
```

**RemoveBankMoney**

Remove money from player's bank. Automatically logs the transaction.

```lua
local success = exports['rarx_banking']:RemoveBankMoney(source, amount, reason)
```

**Example: Shop purchase**

```lua
RegisterNetEvent('shop:purchase', function(itemId, price)
    local src = source

    local success = exports['rarx_banking']:RemoveBankMoney(src, price, 'Shop: ' .. itemId)

    if success then
        -- Give item to player
        exports['ox_inventory']:AddItem(src, itemId, 1)
        TriggerClientEvent('ox_lib:notify', src, {
            title = 'Purchase',
            description = 'Item purchased!',
            type = 'success'
        })
    else
        TriggerClientEvent('ox_lib:notify', src, {
            title = 'Error',
            description = 'Insufficient funds',
            type = 'error'
        })
    end
end)
```

**Example: Vehicle purchase**

```lua
RegisterNetEvent('dealership:buy', function(vehicleModel, price)
    local src = source

    if exports['rarx_banking']:RemoveBankMoney(src, price, 'Vehicle: ' .. vehicleModel) then
        -- Spawn and give vehicle
        SpawnVehicleForPlayer(src, vehicleModel)
    end
end)
```

**Example: Property rent**

```lua
function ChargeRent(source, propertyName, amount)
    local success = exports['rarx_banking']:RemoveBankMoney(source, amount, 'Rent: ' .. propertyName)
    return success
end
```

**GetSavingsBalance**

Get player's savings account balance.

```lua
local savings = exports['rarx_banking']:GetSavingsBalance(source)
```

**Example: Show total wealth**

```lua
RegisterCommand('wealth', function(source)
    local bank = exports['rarx_banking']:GetBankBalance(source)
    local savings = exports['rarx_banking']:GetSavingsBalance(source)
    local total = bank + savings

    TriggerClientEvent('chat:addMessage', source, {
        args = { 'Total wealth: $' .. total }
    })
end, false)
```

**GetSavingsBalanceByCitizenId**

Get savings for offline players by citizenid.

```lua
local savings = exports['rarx_banking']:GetSavingsBalanceByCitizenId(citizenid)
```

**Example: Admin check player savings**

```lua
RegisterCommand('checksavings', function(source, args)
    local citizenid = args[1]
    local savings = exports['rarx_banking']:GetSavingsBalanceByCitizenId(citizenid)
    print('Savings for ' .. citizenid .. ': $' .. savings)
end, true) -- Admin only
```

**HasSavingsAccount**

Check if player has opened a savings account.

```lua
local hasSavings = exports['rarx_banking']:HasSavingsAccount(source)
```

**Example: Require savings for loan**

```lua
RegisterNetEvent('loan:request', function(amount)
    local src = source

    if not exports['rarx_banking']:HasSavingsAccount(src) then
        TriggerClientEvent('ox_lib:notify', src, {
            description = 'You need a savings account to request a loan',
            type = 'error'
        })
        return
    end

    -- Process loan...
end)
```

**AddSavingsMoney / RemoveSavingsMoney**

Add or remove money from savings account.

```lua
local success = exports['rarx_banking']:AddSavingsMoney(source, amount)
local success = exports['rarx_banking']:RemoveSavingsMoney(source, amount)
```

**Example: Interest payment**

```lua
function PayInterest(source)
    local savings = exports['rarx_banking']:GetSavingsBalance(source)
    local interest = math.floor(savings * 0.01) -- 1% interest

    if interest > 0 then
        exports['rarx_banking']:AddSavingsMoney(source, interest)
    end
end
```

**GetIBAN**

Get player's IBAN (formatted with spaces).

```lua
local iban = exports['rarx_banking']:GetIBAN(source)
-- Returns: "ES12 3456 7890 1234 5678"
```

**Example: Show IBAN in HUD**

```lua
RegisterNetEvent('hud:getBankInfo', function()
    local src = source
    local iban = exports['rarx_banking']:GetIBAN(src)
    local balance = exports['rarx_banking']:GetBankBalance(src)

    TriggerClientEvent('hud:updateBank', src, {
        iban = iban,
        balance = balance
    })
end)
```

**TransferMoney**

Transfer money between two online players.

```lua
local success = exports['rarx_banking']:TransferMoney(fromSource, toSource, amount, reason)
```

**Example: Pay another player**

```lua
RegisterNetEvent('player:pay', function(targetId, amount)
    local src = source

    local success = exports['rarx_banking']:TransferMoney(src, targetId, amount, 'Player payment')

    if success then
        TriggerClientEvent('ox_lib:notify', src, {
            description = 'Sent $' .. amount,
            type = 'success'
        })
        TriggerClientEvent('ox_lib:notify', targetId, {
            description = 'Received $' .. amount,
            type = 'success'
        })
    end
end)
```

**GetCreditData**

Get player's credit account data.

```lua
local credit = exports['rarx_banking']:GetCreditData(source)
-- Returns: { limit = 50000, used = 10000, available = 40000 }
```

**Example: Check credit before large purchase**

```lua
RegisterNetEvent('dealership:finance', function(vehiclePrice)
    local src = source
    local credit = exports['rarx_banking']:GetCreditData(src)

    if credit and credit.available >= vehiclePrice then
        -- Approve financing
    else
        -- Deny - not enough credit
    end
end)
```

**OpenBankUI / OpenATMUI**

Open bank or ATM UI for a specific player from server.

```lua
exports['rarx_banking']:OpenBankUI(source)
exports['rarx_banking']:OpenATMUI(source)
```

**Example: Bank NPC interaction**

```lua
RegisterNetEvent('banker:interact', function()
    local src = source
    exports['rarx_banking']:OpenBankUI(src)
end)
```

***

#### Events

**Client Events**

```lua
-- Open bank
TriggerEvent('rarx_banking:openBank')

-- Open ATM
TriggerEvent('rarx_banking:openATM')
```

**Server to Client Events**

```lua
-- Open bank for player
TriggerClientEvent('rarx_banking:openBank', source)

-- Open ATM for player
TriggerClientEvent('rarx_banking:openATM', source)
```

**Example: NPC banker with ox\_target**

```lua
-- Client
exports['ox_target']:addModel({'cs_bankman'}, {
    {
        label = 'Talk to Banker',
        onSelect = function()
            TriggerServerEvent('banker:talk')
        end
    }
})

-- Server
RegisterNetEvent('banker:talk', function()
    local src = source
    -- Maybe add a dialogue first, then:
    exports['rarx_banking']:OpenBankUI(src)
end)
```

***

### Troubleshooting

#### UI not showing

1. Check browser console (F8) for errors
2. Ensure `ui/` folder contains `index.html` and `assets/`
3. Restart the resource

#### Framework not detected

Force framework in `config.lua`:

```lua
Config.Framework = 'qbcore'
```

#### Language not changing

1. Check `server.cfg` has the convar:

   ```cfg
   setr rarx-lang "en"
   ```
2. Restart the **server** (not just the resource)

#### Database errors

1. Ensure `oxmysql` is running
2. Check server console for SQL errors
3. Tables are created automatically

***

### Support

Need help? Join our Discord: [**discord.gg/rarx**](https://discord.gg/rarx)
